<?php
header("Access-Control-Allow-Origin: *");
  session_start();

  include '../config.php';
  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');
  $status = '';
  
  if ( isset($_GET['captcha']) && ($_GET['captcha']!="") ){
    // Validation: Checking entered captcha code with the generated captcha code
    if(strcasecmp($_SESSION['captcha2'], $_GET['captcha']) != 0){
    // Note: the captcha code is compared case insensitively.
    // if you want case sensitive match, update the check above to strcmp()
    //echo "<p class='errormsg'>El captcha es inválido.</p> ";
    //exit();
    }
  }

$intentos = $_COOKIE['loginattempts'];
  

  if(strlen($intentos)<1){
    setcookie("loginattempts", 1, time()+ (60 * 20), '/');
  }

  //echo $intentos;

  if($intentos > 5){

    echo "<p class='errormsg' style='text-align: center;'>Se han detectado múltiples intentos de inicio de sesión incorrectos, por su seguridad, intente nuevamente en 20 minutos.</p>";

    echo "<script>$('#contactform .buttonBlue').remove();</script>";
    exit();
    
  }
  


  $correo = trim($_GET['email']);
  $correo = strip_tags($correo);
  $correo = htmlspecialchars($correo);

  $pass = urldecode($_GET['password']);
  $pass = trim($pass);
  $pass = strip_tags($pass);
  $pass= htmlspecialchars($pass);
  $hash =  hash('sha256', $pass);
  //echo $hash;


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

  if(strlen($correo) > 5 && strlen($pass) > 5){
    $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":"query MyQuery {\\r\\n  usuariosSitioPrivado(where: {email: \\"'.$correo.'\\"}) {\\r\\n    id\\r\\n  password\\r\\n  }\\r\\n}\\r\\n","variables":{}}',
        CURLOPT_HTTPHEADER => array(
          'Content-Type: application/json',
          'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
        ),
    ));
      
    $response = curl_exec($curl);
    curl_close($curl);
    //echo $response;

    $jsonrespuesta = json_decode($response, true);
    $id = $jsonrespuesta['data']['usuariosSitioPrivado'][0]['id'];

    if(strlen($id)<5){

      if($lang == 'es'){
        echo "<p class='errormsg'>El usuario no es válido. Verifique e intente nuevamente.</p>";
      }
      if($lang == 'en'){
        echo "<p class='errormsg'>Invalid user. Please verify it and try again.</p>";
      }

      $numintentos = $intentos + 1;
      setcookie("loginattempts", $numintentos, time()+ (60 * 20), '/');
      exit();

    }
    //echo "<br>";
    //echo $id;
    $passworduser = $jsonrespuesta['data']['usuariosSitioPrivado'][0]['password'];
    echo "<p style='display:none;'>ID: ".$id."</p>";

    if($passworduser != $hash){
      if($lang == 'es'){
        echo "<p class='errormsg'>La contraseña es incorrecta. Verifique e intente nuevamente.</p>";
      }
      if($lang == 'en'){
        echo "<p class='errormsg'>Invalid password. Please verify it and try again.</p>";
      }
      
      $numintentos = $intentos + 1;
      setcookie("loginattempts", $numintentos, time()+ (60 * 20), '/');
      exit();
    }
    //echo $id;

    if($lang == 'es'){
      $sucess = "<p class='successmsg'>Inicio de sesión correcto, por favor espera un momento.</p><script>loginSuccess();</script>";
      $fail = "<p class='errormsg'>El usuario no es válido. Verifique e intente nuevamente.</p> ";
    }
    if($lang == 'en'){
      $sucess = "<p class='successmsg'>Login successful, please wait a moment.</p><script>loginSuccess();</script>";
      $fail = "<p class='errormsg'>Invalid user. Please verify it and try again.</p> ";
    }

    

    if(strlen($id)>10){
      $_SESSION['user'] = $correo;
      //setcookie("persistID", "$correo", time() + (20 * 2 * 12 * 60 * 60), "/", null, true, true);
      setcookie("persistPrivado", "$correo", time()+ (1 * 2 * 12 * 60 * 60), '/');

      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(6);
      $generado = time();

      $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  createCodigoDobleFactor(data: {codigo: \\"'.$token.'\\", correo: \\"'.$correo.'\\", fuente: \\"Sitio\\", generado: \\"'.$generado.'\\", localizations: {create: {data: {codigo: \\"'.$token.'\\", correo: \\"'.$correo.'\\", generado: \\"'.$generado.'\\", fuente: \\"Sitio\\"}, locale: es_MX}}}) {\\r\\n    id\\r\\n  }\\r\\n}\\r\\n","variables":{}}',
        CURLOPT_HTTPHEADER => array(
          'Content-Type: application/json',
          'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
        ),
      ));

      $response = curl_exec($curl);
      curl_close($curl);
      //echo $response;
      $EmailEnvio = $correo;

      if(strlen($EmailEnvio)>5){

        $to = $EmailEnvio; 
        $email = 'noreply@arjm.xyz';
      
        $email_subject = "Clave de acceso | 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($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;">CÓDIGO DE ACCESO</h3>
            
                    <div style="text-align:center; color:#444; margin-top:20px; width:80%;background-color: #eee;
                    border-radius: 30px;
                    padding: 30px;"><b>Tú código de acceso es:</b><br>
                    <h4 style="font-size:40px; text-align:center;"> '.$token.'</h4>
                    <br /><br />
                    <p>Recuerda que este código es de un solo uso y expirará <b>10 minutos</b> después de ser generado. Si necesitas un nuevo código, puedes solicitarlo desde la página de acceso.</p>
                    
                    </td></tr>							 
              </table>
              <p>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;
          $intentos = 0;
        }
        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
        
      }
      else{
        echo $fail;
      }
    }

    else{

      echo "<p class='errormsg'>El usuario no es válido. Verifique e intente nuevamente.</p>";
      //echo "<p class='errormsg'>Intento: ".$intentos."</p> ";

      $numintentos = $intentos + 1;
      setcookie("loginattempts", $numintentos, time()+ (60 * 20), '/');

    }
  }