<?php
    session_start();
    include 'config.php';
    if(isset($_COOKIE['persistID']))
    {
        $userid = $_COOKIE['persistID'];
        $_SESSION['user'] = $userid;
    }

    if(strlen($userid) < 5){
        header("Location: ".$base_url);
    }
    date_default_timezone_set('America/Mexico_City');
    $correo = $userid; 

    $user = trim($_POST['user']);
    $user = strip_tags($user);
    $user = htmlspecialchars($user);

    if(strlen($user)<5){
        exit();

    }

    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: \\"CMS\\", generado: \\"'.$generado.'\\", localizations: {create: {data: {codigo: \\"'.$token.'\\", correo: \\"'.$correo.'\\", generado: \\"'.$generado.'\\", fuente: \\"CMS\\"}, 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;

    $sucess = "<p class='successmsg'>Código enviado correctamente.</p><script>removeCodeBtn();</script>";
    $fail = "<p class='errormsg'>Ocurrió un error al enviar el código. Por favor intenta más adelante.</p> ";

    if(strlen($EmailEnvio)>5){
        $emailList="armando@wearetrafika.com";
        $to = $EmailEnvio; 
        $email = 'noreply@arjm.xyz';
      
        $email_subject = "Clave de acceso | INDEVAL CMS"; //Asunto

        //enviar mail
        include "phpmailer/class.phpmailer.php";
        include "phpmailer/class.smtp.php";

        $email_user = "indeval@trafikatest.com";
        $email_password = "indeval2020";
        $the_subject = "Clave de acceso | INDEVAL CMS";
        $address_to = $EmailEnvio;
        $from_name = "Indeval CMS";
        $phpmailer = new PHPMailer();
        $phpmailer->CharSet = 'UTF-8';

        // ---------- datos de la cuenta de Gmail -------------------------------
        $phpmailer->Username = $email_user;
        $phpmailer->Password = $email_password; 
        //-----------------------------------------------------------------------
        // $phpmailer->SMTPDebug = 1;
        $phpmailer->SMTPSecure = 'ssl';
        $phpmailer->Host = "mail.trafikatest.com"; // GMail
        $phpmailer->Port = 465;
        $phpmailer->IsSMTP(); // use SMTP
        $phpmailer->SMTPAuth = true;

        $phpmailer->setFrom($phpmailer->Username,$from_name);
        $phpmailer->AddAddress($address_to); // recipients email

        $phpmailer->Subject = $the_subject;	
        $phpmailer->Body .= '
          <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 del CMS.</p>
                  
                  </td></tr>							 
            </table>
            <p>Fecha y Hora de envío: '.date("d-m-Y h:i:s").'</p>
          </body>
        ';
        $phpmailer->IsHTML(true);
            
        if(!$phpmailer->Send()) {
          //echo "Error: " . $phpmailer->ErrorInfo;
          echo $fail;
          exit();
        } 
        else {
          //echo "Correo enviado a".$EmailEnvio;
        }
        //termina mail
        echo $sucess;
    }
   