<?php
  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,
        'secret'  => $aws_secret_access_key,
      )
    ));
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['captcha'], $_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();
}
}


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

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

$email = $correo;

//echo $correo;

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

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

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


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

if($lang == 'es'){

    $sucess = "<p class='successmsg'>Su solicitud fue enviada correctamente, una vez evaluada será contactado vía email.</p><script>resetFormSolicitud();</script>";
    $fail = "<p class='errormsg'>Ocurrió un problema al enviar tu solicitud, por avor intenta nuevamente</p> ";

}

if($lang == 'en'){

    $sucess = "<p class='successmsg'>Your request was sent. We'll contact you back soon. </p><script>resetForm();</script>";
    $fail = "<p class='errormsg'>Something went wrong. Please try again</p>";

}

  // make sure we've got a valid email
  if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
    // split on @ and return last value of array (the domain)
    $domainemail = array_pop(explode('@', $email));

    // output domain
    // echo "Email: " .$domainemail;
}


//echo $lang;
$curldomains = curl_init();
curl_setopt_array($curldomains, 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  __typename\\r\\n  generalidadesSitioPrivado(where: {id: \\"ckuwqltrkpenm0b788cug2f0d\\"}) {\\r\\n    id\\r\\n    dominiosPermitidos\\r\\n    firmasDigitales\\r\\n    manualDeTarifas\\r\\n    terminosYCondiciones\\r\\n    localizations {\\r\\n      archivoIsin\\r\\n      dominiosPermitidos\\r\\n      firmasDigitales\\r\\n      manualDeTarifas\\r\\n      terminosYCondiciones\\r\\n    }\\r\\n    archivoIsin\\r\\n  }\\r\\n}","variables":{}}',
    CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json',
    'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
    ),
));

$responsedomains = curl_exec($curldomains);

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

$jsonrespuestadomains = json_decode($responsedomains, true);
$iddomains = $jsonrespuestadomains['data']['generalidadesSitioPrivado']['id'];

$dominios = $jsonrespuestadomains['data']['generalidadesSitioPrivado']['localizations'][0]['dominiosPermitidos'];

$textodominios = rawurldecode($dominios);

//echo $textodominios;

if (strpos($textodominios, $domainemail)) {
    //echo "El dominio del correo <b>".$domainemail." </b>es admitido.";
    //exit();
}
else
{
    echo "<span style='float: left; width: 100%; text-align: center; padding: 10px;'>El dominio del correo <b>".$domainemail." </b>no es admitido.</span>";
    exit();
}


if(strlen($correo)>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":"mutation MyMutation {\\r\\n  __typename\\r\\n  createSolicitudDeAcceso(data: {email: \\"'.$correo.'\\", institucion: \\"'.$institucion.'\\", area: \\"'.$area.'\\", funcion: \\"'.$funcion.'\\", nombre: \\"'.$nombre.'\\"}) {\\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;


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

    if(strlen($id)>10){

      //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('armando@wearetrafika.com')
        );

        //Next we will form the body of the email:
        $msg['Message'] = array(
            // Subject is required
            'Subject' => array(
              // Data is required
              'Data' => 'Nueva solicitud de acceso | INDEVAL',
              'Charset' => 'UTF-8',
          ),
          // Body
          'Body' => array(
            'Text' => array(
            // Data
            'Data' => 'Nueva solicitud de acceso | INDEVAL',
            '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;">NUEVA SOLICITUD DE ACCESO</h3>
            
                    <div style="text-align:left; color:#444; margin-top:20px; width:80%;background-color: #eee;
                    border-radius: 30px;
                    padding: 30px;">
                    <p><b>Nombre: </b> '.$nombre.'</p>
  
                    <p><b>Correo: </b> '.$correo.'</p>
  
                    <p><b>Institución Financiera: </b> '.$institucion.'</p>
  
                    <p><b>Área: </b> '.$area.'</p>
                    
                    <p><b>Función: </b> '.$funcion.'</p>
  
                    <br><br>
  
                    <p><b>Fecha y Hora de solicitud:</b> '.date("d-m-Y h:i:s").'</p>
                  
  
                    </td></tr>							 
              </table>
              
            </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
    }

    else{
        echo $fail;
    }
}


