<?php
include '../config.php';
$id = trim($_GET['id']);
$id = strip_tags($id);
$id = htmlspecialchars($id);

$rol = "usuario";
$permisos = implode(', ', $_POST['permisos']);
$enviado = "";

require '../aws-sdk/aws-autoloader.php';
use Aws\Ses\SesClient;
/* Reference to the ses client */
$client = SesClient::factory(array(
  'version' => 'latest',
  'region'  => $aws_region,
  'credentials' => array(
    'key' => $aws_access_key_id,
    'secret'  => $aws_secret_access_key,
  )
));
date_default_timezone_set('America/Mexico_City');

function cvf_ps_generate_random_code($length=10) {
    $string = '';
    $characters = "123456789ABCDEFHJKLMNPRTVWXYZ*";
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters)-1)];
    }
    return $string;
  }

$token = cvf_ps_generate_random_code(8);
$hash =  hash('sha256', $token);

$curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => $endpoint_graph_cms,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',

    CURLOPT_POSTFIELDS =>'{"query":"mutation MyMutation {\\r\\n  updateSolicitudDeAcceso(data: {aprobado: \\"1\\"}, where: {id: \\"'.$id.'\\"}) {\\r\\n    id\\r\\n    nombre\\r\\n    email\\r\\n  }\\r\\n}\\r\\n","variables":{}}',
  ));

  
  
$response = curl_exec($curl);

curl_close($curl);
//echo $response;

$jsonrespuesta = json_decode($response, true);
$id = $jsonrespuesta['data']['updateSolicitudDeAcceso']['id'];
$nombre = $jsonrespuesta['data']['updateSolicitudDeAcceso']['nombre'];
$email = $jsonrespuesta['data']['updateSolicitudDeAcceso']['email'];

//echo $id;


  $sucess = "<p class='successmsg'>Usuario aprobado y creado correctamente.</script>";
  $fail = "<p class='errormsg'>Falló la actualización..</p> ";


if(strlen($id)>10){


    $curl2 = curl_init();

    curl_setopt_array($curl2, array(
    CURLOPT_URL => $endpoint_graph_cms,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',

    CURLOPT_POSTFIELDS =>'{"query":"mutation MyMutation {\\r\\n createUsuarioSitioPrivado(data: {email: \\"'.$email.'\\", estatus: \\"publicado\\", nombre: \\"'.$nombre.'\\", password: \\"'.$hash.'\\", resetPass: \\"1\\", localizations: {create: {data: {rol: \\"'.$rol.'\\", permisos: \\"'.$permisos.'\\", email: \\"'.$email.'\\", enviadoRevision: \\"'.$enviado.'\\", password: \\"'.$hash.'\\", resetPass: \\"1\\", estatus: \\"publicado\\", nombre: \\"'.$nombre.'\\"}, locale: es_MX}}, permisos: \\"'.$permisos.'\\", rol: \\"'.$rol.'\\"}) {\\r\\n  id\\r\\n}\\r\\n}\\r\\n","variables":{}}',
  ));

  
  
    $response2 = curl_exec($curl2);

    curl_close($curl2);
    //echo $response;

    $jsonrespuesta2 = json_decode($response2, true);
    $id2 = $jsonrespuesta2['data']['createUsuarioSitioPrivado']['id'];

    if(strlen($id2)>10){

      $curlpub = curl_init();

      curl_setopt_array($curlpub, array(
          CURLOPT_URL => $endpoint_graph_cms,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
  
          CURLOPT_POSTFIELDS =>'{"query":"mutation MyMutation {\\r\\n  publishUsuarioSitioPrivado(\\r\\n    where: {id: \\"'.$id2.'\\"}\\r\\n    to: PUBLISHED\\r\\n    locales: es_MX\\r\\n  ) {\\r\\n    id\\r\\n  }\\r\\n}\\r\\n","variables":{}}',
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
          ),
        ));

        $responsepub = curl_exec($curlpub);
        curl_close($curlpub);


        //echo $responsepub;

        $EmailEnvio = $email;

        if(strlen($EmailEnvio)>5){
          $emailList="armando@wearetrafika.com";
          $to = $EmailEnvio; 
          //$email = 'noreply@arjm.xyz';
        
          $email_subject = "Acceso a área de clientes | INDEVAL"; //Asunto
    
    
          //ENVIAR CORREO CON AMAZON SES
    
          //Now that you have the client ready, you can build the message
          $msg = array();
          $msg['Source'] = "indeval@grupobmv.com.mx";
          //ToAddresses must be an array
          $msg['Destination'] = array(
            'ToAddresses' => array($EmailEnvio)
          );
    
          //Next we will form the body of the email:
          $msg['Message'] = array(
              // Subject is required
              'Subject' => array(
                // Data is required
                'Data' => $email_subject,
                'Charset' => 'UTF-8',
            ),
            // Body
            'Body' => array(
              'Text' => array(
              // Data
              'Data' => $email_subject,
              'Charset' => 'UTF-8',
              ),
              'Html' => array(
              // Data is required
              'Data' => '
              <body style="background-color:#2b4365;">
                <table border=0 width="90%" style="border: 2px solid #2b4365; font-family: Century gothic, Helvetica, sans-serif;color:#2b4365;font-size: 15px;background-color: #ebebee;max-width: 700px;padding: 40px 20px;border-radius: 20px;position: relative;margin: 0 auto;top: 1em; text-align:center;">
                      <tr><td align="center">
                      <img src="https://indeval-webdocs-publico-01122020.s3.amazonaws.com/img/indeval_logo.png" alt="Indeval" style="width:200px; margin: 0px auto 20px;"/>
                      </td></tr>
    
                      <tr><td align="center" height="200">
                      <h3 style="color:#2b4365; foont-weight:bold; text-align:center;">BIENVENIDO AL ÁREA DE CLIENTES</h3>

                      <h2 style="color:#2b4365; foont-weight:bold; text-align:center;">CONTRASEÑA DE ACCESO ÚNICO</h2>
              
                      <div style="text-align:center; color:#444; margin-top:20px; width:80%;background-color: #eee;
                      border-radius: 30px;
                      padding: 30px;"><b>Su contraseña de acceso es:</b><br>
                      <h4 style="font-size:20px; text-align:center;"> '.$token.'</h4>
                      <br /><br />
                      <p>Esta contraseña es de un solo uso. Cuando inicies sesión por primera vez, tendrás que establecer una nueva contraseña segura.</p>
                      
                      </td></tr>							 
                </table>
                <p style="color:#fff; width:100%; text-align:center;">Fecha y Hora de envío: '.date("d-m-Y h:i:s").'</p>
              </body>
            ',
              'Charset' => 'UTF-8',
              ),
            )
          );
    
          //Now you are all set. You call sendEmail to send the email:
    
          try{
          $result = $client->sendEmail($msg);
    
          //Msg id from AWS. Can be used for tracking.
          $msg_id = $result->get('MessageId');
          //echo("MessageId: $msg_id");
    
          //view sample output
          //print_r($result);
          } catch (Exception $e) {
          //Exception Caught.
          //echo($e->getMessage());
          echo "<p class='errormsg'>Ocurrió un error al enviar el correo, intente nuevamente en unos minutos.</p> ";
          }
    
          if(strlen($msg_id)>5){
            echo $sucess;
          }
          else{
            echo "<p class='errormsg'>Ocurrió un error al enviar el correo, intente nuevamente en unos minutos.</p> ";
          }
    
          //Print the result to check if it is successful
          //print_r($result);
    
          //termina mail SES
          
        }

        $newstatus = "<span class='statusentregado'>Procesado</span>";

        $string = $newstatus;
        $string = '"'.$string.'"';
        echo '<script>
        $("#status'.$id.'").html('.$string.');
            setTimeout(() => {
                $(".popUpAprobar").fadeOut();
            }, 1500);
        </script>';

    }

   
}

else{
    echo $fail;
}