<?php

include '../config.php';
$email = trim($_GET['email']);
$email = strip_tags($email);

$lang = trim($_GET['lang']);
$lang = strip_tags($lang);
//$id = htmlspecialchars($id);

//echo $email;

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_PROD,
    'secret'  => $aws_secret_access_key_PROD,
  )
));
date_default_timezone_set('America/Mexico_City');


$stage = "PUBLISHED";


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);

//echo $id;
$curluser = curl_init();
curl_setopt_array($curluser, 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":"query MyQuery {\\r\\n  usuariosSitioPrivado(where: {email: \\"'.$email.'\\"}, last: 1, stage: PUBLISHED) {\\r\\n    id\\r\\n  resetPass\\r\\n fechaCambioPassword\\r\\n nombre\\r\\n  empresa\\r\\n  permisos\\r\\n  rol\\r\\n  tycAceptados\\r\\n  }\\r\\n}\\r\\n","variables":{}}',
CURLOPT_HTTPHEADER => array(
  'Content-Type: application/json',
  'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
),
));

$responseuser = curl_exec($curluser);
curl_close($curluser);

$jsonrespuestauser = json_decode($responseuser, true);
$idgraph = $jsonrespuestauser['data']['usuariosSitioPrivado'][0]['id'];
$id = $jsonrespuestauser['data']['usuariosSitioPrivado'][0]['id'];
$resetPass_privado = $jsonrespuestauser['data']['usuariosSitioPrivado'][0]['resetPass'];
$fechaPass = $jsonrespuestauser['data']['usuariosSitioPrivado'][0]['fechaCambioPassword'];
$rol_user_privado = $jsonrespuestauser['data']['usuariosSitioPrivado'][0]['rol'];
$nombre_user_privado = $jsonrespuestauser['data']['usuariosSitioPrivado'][0]['nombre'];
$tyc = $jsonrespuestauser['data']['usuariosSitioPrivado'][0]['tycAceptados'];
$empresa = $jsonrespuestauser['data']['usuariosSitioPrivado'][0]['empresa'];
$permisos = $jsonrespuestauser['data']['usuariosSitioPrivado'][0]['permisos'];

//echo $id;

$url = $base_url."?t=".$token."&resetPass=1";



if($lang == 'es'){
    $titulomail = "Recuperar password | INDEVAL";
    $titulo = "Recuperación de contraseña";
    $textomail1 = "Ingrese al siguiente enlace para establecer una nueva contraseña:"; 
    $textomail2 = "El enlace será válido por los siguientes 30 minutos.";
    $textofecha = "Fecha y Hora de envío";
    $sucess = "<p>Correo enviado correctamente. Recuerde revisar su bandeja de Spam.</p>";
    $fail = "<p class='errormsg'>Ocurrió un error al enviar el correo, intente nuevamente en unos minutos.</p>";
    $noexiste =  "El usuario no está registrado.";
}

if($lang == 'en'){
    $titulomail = "Reset password | INDEVAL";
    $titulo = "Reset your password";
    $textomail1 = "Visit the following link to reset your password:"; 
    $textomail2 = "The link will be valid for the next 30 minutes.";
    $textofecha= "Date and hour:";
    $sucess = "<p>Email sent. Remember to check your spam folder.</p>";
    $fail = "<p class='errormsg'>Error, please try again in a few minutes.</p>";
    $noexiste =  "The email is not a registered user.";
}

if(strlen($id)>10){
    $modelo = "UsuarioSitioPrivado";

    $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  update'.$modelo.'(data: {tokenRecuperaPass: \\"'.$token.'\\", localizations: {update: {data: {tokenRecuperaPass: \\"'.$token.'\\"}, locale: es_MX}}}, where: {id: \\"'.$id.'\\"}) {\\r\\n    id\\r\\n  }\\r\\n  unpublish'.$modelo.'(where: {id: \\"'.$id.'\\"}) {\\r\\n    id\\r\\n  }\\r\\n publish'.$modelo.'(where: {id: \\"'.$id.'\\"}, locales: es_MX, to: PUBLISHED) {\\r\\n    id\\r\\n  }\\r\\n}\\r\\n","variables":{}}',
    CURLOPT_HTTPHEADER => array(
      'Content-Type: application/json',
      'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
    ),
  ));
  
  
$response = curl_exec($curl);

    $correo = $email;
    $EmailEnvio = $correo;

    if(strlen($EmailEnvio)>5){
      $emailList="armando@wearetrafika.com";
      $to = $EmailEnvio; 
      //$email = 'noreply@arjm.xyz';
    
      $email_subject = $titulomail; //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($correo)
      );

      //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;">'.$titulo.'</h3>
          
                  <div style="text-align:center; color:#444; margin-top:20px; width:80%;background-color: #eee;
                  border-radius: 30px;
                  padding: 30px;"><b>'.$textomail1.'</b><br>
                  <h4 style="font-size:12px; text-align:center;"><a href="'.$url.'">'.$url.'</a></h4>
                  <br /><br />
                  <p>'.$textomail2.'</p>
                  
                  </td></tr>							 
            </table>
            <p style="color:#fff; width:100%; text-align:center;">'.$textofecha.': '.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;
        echo "<script>$('#email_pass').val('');</script>";
        echo "<script>$('#formrpassemail .buttonBlue').hide(); $('#email_pass').hide();  $('#formrpassemail .group').hide(); $('#resetpassEmail .modal-body h1').hide();</script>";
      }
      else{
        echo $fail;
      }

      //Print the result to check if it is successful
      //print_r($result);

      //termina mail SES
      
    }
    
}

else{
   echo $noexiste;
}