<?php
header('Access-Control-Allow-Origin: *');
include_once("lib/general/cGeneral.php");
include_once("Controllers/WhatsappController.php");

include_once("phpmailer/PHPMailerAutoload.php");
include_once("email_configuraciones.php");
require_once("variables-globales.php");
ini_set('display_errors', 1); 
class UsersController extends cGeneral{
    
    #SETTK
    public function settoken($token,$apikey){
        global $General;
        #Actuliza los tokens para inutilizarlos
        $conexion = $General->getConexion(MOD_AMBIENT); 
        $sql_update_user = "UPDATE tokens_consumo SET status = 1, apikey = '".$apikey."' WHERE token = '".$token."'";
        $resultado = mysqli_query($conexion,$sql_update_user);

            if (!$resultado) {
                throw new Exception("Error consultando el token, ERROR: COD: CHMKKP::QDM::SETTK::INU-01");
                $this->closeConexcionDB($conexion);
                return "COD: CHMKKP::QDM::SETTK::INU-01";
            }
            else{
                
                $General->closeConexcionDB($conexion);
                return "Se inutilizo el token";
            }
    }

    #CKTK
    public function checktoken($token){
        global $General;
        $data = $this->postRequest();
        $conexion = $General->getConexion(MOD_AMBIENT);
        
        #Obtengo todos los addons activos e inactivos de la cuenta donde se inicia sesion
        $sql_get_tokens = "SELECT * FROM
                                tokens_consumo 
                            WHERE token = '".$token."';";
                
        $resultado = mysqli_query($conexion,$sql_get_tokens);
        if (!$resultado) {
            throw new Exception("Error consultando el token, ERROR: COD: CHMKKP::QDM::CKTK::CCSSDB-01");
            $this->closeConexcionDB($conexion);
            return "COD: CHMKKP::QDM::CKTK::CCSSDB-01";

        }
        else{
            while ($fila =mysqli_fetch_array($resultado, MYSQLI_ASSOC)){
                $get_row[] =$fila;
            }
            $this->closeConexcionDB($conexion);
            for($x=0; count($get_row)>$x;$x++){
                if($get_row[$x]["status"] == 1){
                    return "Token expirado";
                }
                else{
                    //Token válido
                    return "OK";
                }
            }
        }
    }
    
    
    /*
    CFMTNTGS
    */
    public function confirmationregis(){
        global $General;
        $data = $this->postRequest();
        $conexion = $General->getConexion(MOD_AMBIENT);
        $response = array();
        $response_addons = array();

        if($this->checktoken($data["token"])== "OK"){
            $sql_new_user = "INSERT INTO usuarios (nombre, apellidos, correo, celular, fecha_nacimiento, id_estado, id_site) VALUES ('".$data["nombre"]."', '".$data["apellidos"]."', '".$data["correo"]."','".$data["celular"]."','".$data["fecha_nacimiento"]."',".$data["id_estado"].",'".$data["kyUser"]."')";
            $resultado = mysqli_query($conexion,$sql_new_user);
    
            if (!$resultado) {
                throw new Exception("Error de BD, no se pudo consultar la base de datos " );
                $General->closeConexcionDB($conexion);
                $response["code"] = 300;
                $response["msj"] = "ERROR! ---- COD: CHMKKP::QDM::CFMTNTGS::NSRT-01";
            }
            else{

                $body = "¡Hola ".$data["nombre"]." ".$data["apellidos"].", gracias por registrarte!\n";

                $curl = curl_init();
                curl_setopt_array($curl, array(
                CURLOPT_URL => "https://api.ultramsg.com/".base64_decode("aW5zdGFuY2UyMDA1NQ==")."/messages/chat",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => "token=".base64_decode("NzVpNnZobjdqc28xbzRuOA==")."&to=+52".$data["celular"]."&body=".$body."&priority=10&referenceId=",
                CURLOPT_HTTPHEADER => array(
                    "content-type: application/x-www-form-urlencoded"
                ),
                ));

                $_response = curl_exec($curl);
                $err = curl_error($curl);

                curl_close($curl);

                //print_r($_response);
                
                if ($err) {
                    $response['code'] = 301;
                    $response['msj'] = "ERROR! ---- COD: CHMKKP::QDM::CFMTNTGS::SNDMSJTXT-01";     
                } else {
                    

/*                    
                    //Envio de Imagen
                    $curl2 = curl_init();

                    curl_setopt_array($curl2, array(
                    CURLOPT_URL => "https://api.ultramsg.com/".base64_decode("aW5zdGFuY2UyMDA1NQ==")."/messages/image",
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_SSL_VERIFYHOST => 0,
                    CURLOPT_SSL_VERIFYPEER => 0,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => "POST",
                    CURLOPT_POSTFIELDS => "token=".base64_decode("NzVpNnZobjdqc28xbzRuOA==")."&to=+52".$data["celular"]."&image=https://quinieladelmundial.kiper.io/webroot/img/Felicidades.png&referenceId=&nocache=",
                    CURLOPT_HTTPHEADER => array(
                        "content-type: application/x-www-form-urlencoded"
                    ),
                    ));

                    $response2 = curl_exec($curl2);
                    $err2 = curl_error($curl2);

                    curl_close($curl2);

*/
/*
                    $body = "¡Da click en el siguiente link o copia y pega en tu navegador y sigue las instrucciones!";

                    $curl4 = curl_init();
                    curl_setopt_array($curl4, array(
                    CURLOPT_URL => "https://api.ultramsg.com/".base64_decode("aW5zdGFuY2UyMDA1NQ==")."/messages/chat",
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => "POST",
                    CURLOPT_POSTFIELDS => "token=".base64_decode("NzVpNnZobjdqc28xbzRuOA==")."&to=+52".$data["celular"]."&body=".$body."&priority=10&referenceId=",
                    CURLOPT_HTTPHEADER => array(
                        "content-type: application/x-www-form-urlencoded"
                    ),
                    ));

                    $_response = curl_exec($curl4);
                    $err = curl_error($curl4);

                    curl_close($curl4);
*/
                    
                    $links[0] = "https://bit.ly/3Nyl9yy";
                    $links[1] = "https://bit.ly/3fAJyam";
                    $links[2] = "https://bit.ly/3DZTZgX";
                    $links[3] = "https://bit.ly/3fweLeK";
                    $links[4] = "https://bit.ly/3zI6Y4q";

                   /* $links[0] = "https://d2eay.app.goo.gl/?link=http://www.mcdonalds.com.mx/mx/campaign/60da7b8bbc210a456e48b7bf?country%3DMX%26apn=com.mcdo.mcdonalds%26isi=1114009187%26ibi=com.mcdo.mcdonalds%26dfl=http://www.mcdonalds.com.mx/apps";
                    $links[1] = "https://d2eay.app.goo.gl/?link=http://www.mcdonalds.com.mx/mx/campaign/621fee2184e76002a69410c6?country%3DMX%26apn=com.mcdo.mcdonalds%26isi=1114009187%26ibi=com.mcdo.mcdonalds%26dfl=http://www.mcdonalds.com.mx/apps";
                    $links[2] = "https://d2eay.app.goo.gl/?link=http://www.mcdonalds.com.mx/mx/campaign/621d8325c36db602ac5fe37e?country%3DMX%26apn=com.mcdo.mcdonalds%26isi=1114009187%26ibi=com.mcdo.mcdonalds%26dfl=http://www.mcdonalds.com.mx/apps";
                    $links[3] = "https://d2eay.app.goo.gl/?link=http://www.mcdonalds.com.mx/mx/campaign/61f424bb5035404c9d5a0251?country%3DMX%26apn=com.mcdo.mcdonalds%26isi=1114009187%26ibi=com.mcdo.mcdonalds%26dfl=http://www.mcdonalds.com.mx/apps";
                    $links[4] = "https://d2eay.app.goo.gl/?link=http://www.mcdonalds.com.mx/mx/campaign/6261738bc171d573514a27e6?country%3DMX%26apn=com.mcdo.mcdonalds%26isi=1114009187%26ibi=com.mcdo.mcdonalds%26dfl=http://www.mcdonalds.com.mx/apps";
*/

/*                   
                    $body = ($links[rand(0,4)]);

                    
                    $curl3 = curl_init();

                  

                    curl_setopt_array($curl3, array(
                    CURLOPT_URL => "https://api.ultramsg.com/".base64_decode("aW5zdGFuY2UyMDA1NQ==")."/messages/link",
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => "POST",
                    CURLOPT_POSTFIELDS => "token=".base64_decode("NzVpNnZobjdqc28xbzRuOA==")."&to=+52".$data["celular"]."&link=".$body."&referenceId=",
                    CURLOPT_HTTPHEADER => array(
                        "content-type: application/x-www-form-urlencoded"
                    ),
                    ));


                    $_response3 = curl_exec($curl3);
                    $err3 = curl_error($curl3);

                    curl_close($curl3);

                    $body = "Revisa tu mail para completar el registro y comienza a jugar GRATIS. Llena tus predicciones mundialistas y no te pierdas de increíbles premios en cada fase \n";

                    $curl4 = curl_init();
                    curl_setopt_array($curl4, array(
                    CURLOPT_URL => "https://api.ultramsg.com/".base64_decode("aW5zdGFuY2UyMDA1NQ==")."/messages/chat",
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => "POST",
                    CURLOPT_POSTFIELDS => "token=".base64_decode("NzVpNnZobjdqc28xbzRuOA==")."&to=+52".$data["celular"]."&body=".$body."&priority=10&referenceId=",
                    CURLOPT_HTTPHEADER => array(
                        "content-type: application/x-www-form-urlencoded"
                    ),
                    ));

                    $_response = curl_exec($curl4);
                    $err = curl_error($curl4);

                    curl_close($curl4);

                    $curl3 = curl_init();

                    $body = "https://www.quinielaoficialmundial.com";
                    curl_setopt_array($curl3, array(
                        CURLOPT_URL => "https://api.ultramsg.com/".base64_decode("aW5zdGFuY2UyMDA1NQ==")."/messages/link",
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => "",
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 30,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => "POST",
                        CURLOPT_POSTFIELDS => "token=".base64_decode("NzVpNnZobjdqc28xbzRuOA==")."&to=+52".$data["celular"]."&link=".$body."&referenceId=",
                        CURLOPT_HTTPHEADER => array(
                            "content-type: application/x-www-form-urlencoded"
                        ),
                        ));
                        
    
                        $_response3 = curl_exec($curl3);
                        $err3 = curl_error($curl3);
    
                        curl_close($curl3);

                    
                    //print_r($_response);
*/
                    


                    $mail = new PHPMailer;
                    $mail->isSMTP();
                    $mail->SMTPDebug = 0;
                    $mail->Debugoutput = 'html';
                    $mail->Host = "smtp.gmail.com";
                    $mail->Port = 587;
                    $mail->SMTPAuth = true;
                    $mail->Username = "quinielaoficialdelmundial2022@gmail.com";
                    $mail->Password = "tvnpzgkrxjlqoztc";
                    $mail->setFrom("quinielaoficialdelmundial2022@gmail.com", "Quiniela Oficial FIFA WORLD CUP 2022TM");
                    $mail->addAddress($data["correo"],"");
                    $mail->addBCC('leslye@concepthaus.mx');
                    $mail->Subject = utf8_decode("¡Gracias por registrarte a la Quiniela Oficial del Mundial!");



                    $plantilla = '<!DOCTYPE html>
                    <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
                    <head>
                      <meta charset="utf-8">
                      <meta name="viewport" content="width=device-width">
                      <meta http-equiv="X-UA-Compatible" content="IE=edge">
                      <meta name="x-apple-disable-message-reformatting">
                      <title></title>
                      <!-- <link rel="preconnect" href="https://getnet-resources.s3.us-east-2.amazonaws.com" crossorigin> -->
                      <style type="text/css" data-noprefix>
                        /* @font-face {
                          font-family: "Santander-regular";
                          src: url("https://getnet-resources.s3.us-east-2.amazonaws.com/SantanderText-Regular.ttf");
                        }
                        @font-face {
                          font-family: "Santander-italic";
                          src: url("https://getnet-resources.s3.us-east-2.amazonaws.com/SantanderText-Italic.ttf");
                        }
                        @font-face {
                          font-family: "Santander-bold";
                          src: url("https://getnet-resources.s3.us-east-2.amazonaws.com/SantanderText-Bold.ttf");
                        } */
                        *, html {
                          padding: 0; margin: 0;
                        }
                        body { font-weight: 500; font-family: "Arial", Helvetica, sans-serif; font-size: 15px; line-height: 1; color: #000000; }
                        h1, h2, h3, h4, h5, h6 {
                          font-weight: 700; padding: 0; margin: 0;
                        }
                        p {
                          font-weight: 500;
                        }
                        strong, b {
                          font-weight: 700;
                        }
                        .titleRegis {
                          line-height: 1.2;font-size: 26px;color: #000000; margin: 0; padding: 0; text-align: center;
                        }
                        .fifaImg {
                          display: block; margin: 0 auto; padding: 0; width: 100%; max-width: 550px; height: auto; border: 0;
                        }
                        .cuponLink {
                          display: block; margin: 0 auto; padding: 0; width: 100%; max-width: 500px; height: auto; border: 0;
                        }
                        .cintHero {
                          display: block; margin: 0 auto; padding: 0; width: 100%; max-width: 500px; height: auto; border: 0;
                        }
                        .listTerms {
                          margin: 0 auto 0 auto; padding: 0; text-align: center; display: flex;flex-direction: column; list-style-type: none; width: 500px;
                        }
                        .listTerms li {
                          color: #000000;margin: 0 0 8px 0;font-size: 16px;text-align: center;line-height: 1.2;font-weight: 600;
                        }
                        .listTerms li:last-child {
                          margin: 0;
                        }
                        .titleCupon {
                          line-height: 1.2;font-size: 22px;color: #3d3d3d; margin: 0 0 16px; padding: 0; text-align: center;
                        }
                        .descCupon {
                          padding: 0;margin: 0 0 20px;line-height: 1.2;font-size: 13px;color:#3d3d3d;text-align: center;line-height: 1.2;font-weight: 600;
                        }
                        .btnCupon {
                          display: block;width: 250px;height: 40px;line-height: 40px; padding: 0;margin: 0 auto 30px;border: 2px solid #3d3d3d;background-color: transparent; text-align: center;color: #3d3d3d;text-decoration: none;font-weight: 700;text-transform: uppercase;font-size: 20px;
                        }
                        .logosImages {
                          display: block; margin: 0 auto; padding: 0; width: 100%; max-width: 400px; height: auto; border: 0;
                        }
                        .textFooter {
                          padding: 0;margin: 0;line-height: 1.2;font-size: 11px;color:#3d3d3d;text-align: center;font-weight: 700;
                        }
                        @media only screen and (min-width:600px) {
                          .descCupon {
                            font-size: 16px;
                          }
                          .listTerms li {
                            font-size: 22px;margin: 0 0 15px 0;
                          }
                          .textFooter {
                            font-size: 18px;
                          }
                        }
                      </style>
                    </head>
                    
                    <body width="100%" style="margin: 0; padding: 0 !important; mso-line-height-rule: exactly; background: #ffffff;">
                      <center style="width: 100%; background: #ffffff;">
                        <div style="width:100%;max-width: 600px; margin: 40px auto;">
                          <table align="center" bgcolor="#ffffff" role="presentation" cellspacing="0" cellpadding="0" border="0"
                          width="100%" style="margin: 0 auto;">
                            <tbody>
                              <tr>
                                <td align="center" >
                              <!--[if gte mso 9]>
                              <v:rect xmlns_v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="width:600px; background-color:#2f291f;">
                              <v:fill type="frame" src="https://kiper-bucket.s3.us-east-2.amazonaws.com/transactional/quiniela_del_mundial/bg_fifa_world.jpg" />
                              <v:textbox style="mso-fit-shape-to-text:true" inset="0,0,0,0">
                              <![endif]-->
                                <table role="presentation" border="0" cellspacing="0" cellpadding="0" width="100%">
                                  <tbody>
                                    <tr>
                                      <td style="padding: 0 0 20px;">
                                        <h2 class="titleRegis">¡FELICIDADES,  '.$data["nombre"]." ".$data["apellidos"].'!<br>YA ESTÁS REGISTRADO EN LA</h2>
                                      </td>
                                    </tr>
                                    <tr>
                                      <td style="padding: 0 0 45px;">
                                        <img class="fifaImg" src="https://kiper-bucket.s3.us-east-2.amazonaws.com/transactional/quiniela_del_mundial/Hisense FifaQuinela_CuponMailing_600px.png" alt="Quiniela FIFA 2022">
                                      </td>
                                    </tr>
                                    
                                    
                                    <tr>
                                      <td style="padding: 0;text-align: center;">
                                        <a href="'.$links[rand(0,4)].'" target="_blank" class="btnCupon" style="color:black;">Haz click aquí</a>
                                      </td>
                                    </tr>
                                  </tbody>
                                </table><!-- end.table -->
                              <!--[if gte mso 9]>
                              </v:textbox>
                              </v:rect>
                              <![endif]-->
                                </td>
                              </tr>
                              <tr>
                                <td align="center" style="padding: 20px 20px 20px 15px;margin: 0;background-color: #ffffff;">
                                  
                                    <p style="color: #000000;margin: 0 0 8px 0;font-size: 16px;text-align: center;line-height: 1.2;font-weight: 600;">Baja la app de McDonald\'s y sigue las instrucciones</p><br/>
                                    <p style="color: #000000;margin: 0 0 8px 0;font-size: 16px;text-align: center;line-height: 1.2;font-weight: 600;">Presenta tu código en cualquier sucursal de la República Mexicana</p>
                                  
                                </td>
                              </tr>
                              <tr>
                                <td >
                                  <img class="fifaImg" src="https://kiper-bucket.s3.us-east-2.amazonaws.com/transactional/quiniela_del_mundial/HisenseFifaQuiniela_CuponMailing_600px_footer.png" width="600px" alt="Logos Patrocinadores">
                                </td>
                              </tr>
                             
                              <tr>
                                <td valign="middle" align="center" bgcolor="#ffffff" style="background-color: #ffffff;padding:30px 20px;">
                                  <p style="background-color: #ffffff;padding:0;"><a style="color: #8e1e34;font-weight: 600;font-size: 14px;text-align: center;" href="https://www.quinielaoficialmundial.com/" target="_blank" rel="noopener noreferrer">www.quinielaoficialmundial.com</a></p>
                                </td>
                              </tr>
                            </tbody>
                          </table>
                    
                        </div>
                      </center>
                    </body>
                    
                    </html>';

                   // $plantilla = str_replace("{{NOMBRE}}",$data["inpNombre"], $plantilla);
                    $mail->MsgHTML(utf8_decode($plantilla));
                    //send the message, check for errors
                    if (!$mail->send()) {
                        #$response['code'] = 301;
                        #$response['msj'] = "No se envío el email".$mail->ErrorInfo;  
                        $response['code'] = 301;
                        $response['msj'] = "ERROR! ---- COD: CHMKKP::QDM::CFMTNTGS::SNDMSJTXT-02";     
                    } else {      
                        #echo "se envio";
                        $conexion = $General->getConexion(MOD_AMBIENT);
                        //$sql_registroEnvio = "INSERT INTO envios_mailing (id_cliente, id_mailing_template, fecha_envio, id_user_envio) VALUES(".$data["id_cliente"].", ".$data["inpIdMailing"]." , '".date("Y-m-d H:i:s")."', ".$info_session["idUser"].");";
                        $this->settoken($data["token"],$data["apikey"]);
                        $response['code'] = 200;
                        $response['msj'] = "El mensaje se ha enviado correctamente";
                    }


/*
                    if ($err3) {
                        
                    } 
                    if ($err2) {
                        $response['code'] = 301;
                        $response['msj'] = "ERROR! ---- COD: CHMKKP::QDM::CFMTNTGS::SNDMSJIMG-02";   
                    } 
                    else{
                       
                    }*/
                }
            }

        }
        else{
            $response['code'] = 301;
            $response['msj'] = "El token ya fue utilizado. Genera un nuevo token para continuar";  
        }

        echo json_encode($response);
        
    }
    

}
?>


