<?php
//  app/api/payments/pagomovil/getvalidationcode.php
    header("Content-Type:application/json");
    include("../../../../settings/dbconn.php");
    include("../../../../settings/utils.php");
    require '../../../hooks/PHPMailer5/PHPMailerAutoload.php';
    date_default_timezone_set('Etc/UTC');
    
    // parametros obligatorios
    $parmsob = array("sessionid", "paymentid");
    if (!parametrosValidos($_POST, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por GET
    $out = new stdClass();
    $sessionid = $_POST["sessionid"];
    $paymentid = $_POST["paymentid"];
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Validamos que existe
    $sql = "SELECT COUNT(payments_pagomovil.id) AS qty ".
    "       FROM payments_pagomovil ".
    "       JOIN accounts ON accounts.userid = ".$userid.
    "           AND accounts.id = payments_pagomovil.accountid ".
    "       WHERE payments_pagomovil.status = 1".
    "       ".($paymentid == 0 ? "" : "AND payments_pagomovil.id = ".$paymentid);
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    if($row['qty'] == 0){
        badEnd("402", array("msg"=>determinateMsgFail(array(
            "esp"=>"Pago no registrado",
            "eng"=>"Payment not registered"), $lang, "Pago no registrado")));
    }
    
    // Si existe, vemos que status posee
    $sql = "SELECT payments_pagomovil.* ".
    "       FROM payments_pagomovil ".
    "       JOIN accounts ON accounts.userid = ".$userid.
    "           AND accounts.id = payments_pagomovil.accountid ".
    "       WHERE payments_pagomovil.status = 1".
    "       ".($paymentid == 0 ? "" : "AND payments_pagomovil.id = ".$paymentid);
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    // Si es 1 podemos continuar, si no, no se puede obtener
    if($row['status'] != 1){
        badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"No se puede obtener",
            "eng"=>"Cannot get code"), $lang, "No se puede obtener")));
    }
    
    //Obtenemos el nivel de usuario para determinar su fee
    $sql = "SELECT * FROM users WHERE id = ".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Guardamos la data de la cuenta
    $userdata = $rs->fetch_assoc();
    
    // Recalculamos el code
    $validator = getValidator(8);
    $validatorMd5 = md5($validator);
    
    // Si llegamos hasta aqui, podemos actualizar
    $sql = "UPDATE payments_pagomovil SET ".
    "       validationcode = '".$validatorMd5."'".
    "       WHERE accountid = ".$row['accountid'].
    "       AND status = 1".
    "       ".($paymentid == 0 ? "" : " AND id = ".$paymentid);
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $email = $userdata["usr"];
    $subject = "Código para Cripto Pago ".$shortname;
    $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
    $styleTag = 
        "<style rel='stylesheet' type='text/css'>".
        "           .emailBox {".
        "               background-color: #F8F8FA;".
        "               padding: 20px;".
        "           }".
        "           .copy {".
        "               font-family: 'Roboto', sans-serif;".
        "               font-weight: 400;".
        "               font-size: 12px;".
        "               margin-top:40px;".
        "               color: #767E93;".
        "               text-align:center;".
        "           }".
        "           .mainBox {".
        "               margin: auto;".
        "               display: block;".
        "               background-color: #FFF;".
        "               border-radius: 22px;".
        "               width: 60%;".
        "               padding:30px;".
        "           }".
        "           .msg { ".
        "               font-size: 18px;".
        "               color: #474C58;".
        "               text-align:center;".
        "               margin-bottom:30px;".
        "               margin-left:20px;".
        "               margin-right:20px;".
        "           }".
        "           .titleEmail {".
        "               color:#474C58;".
        "               text-align:center;".
        "               font-size: 20px;".
        "               font-weight: bold;".
        "               margin-left:20px;".
        "               margin-right:20px;".
        "           }".
        "           .note {".
        "               text-align:center;".
        "               font-size:12px;".
        "               color: #474C58;".
        "           }".
        "           .code {".
        "               margin: auto;".
        "               display: block;".
        "               color: #FFF;".
        "               font-size: 18px;".
        "               text-align:center;".
        "               line-height: 58px;".
        "               font-weight:bold;".
        "               letter-spacing: 10px;".
        "           }".
        "           .validatorBox {".
        "               margin: auto;".
        "               display: block;".
        "               background-color: #4287CE;".
        "               border-radius: 8px;".
        "               width: 200px;".
        "               height: 57px;".
        "               text-align:center;".
        "           }".
        "           @media (max-width: 450px) {".
        "               .mainBox {".
        "                   width: 95% !important;".
        "                   padding: 25px 0px;".
        "               }".
        "               .emailBox {".
        "                   padding: 0px;".
        "               }".
        "               .titleEmail {".
        "                   font-size: 18px;".
        "               }".
        "               .msg, .code {".
        "                   font-size: 14px;".
        "               }".
        "           }".
        "</style>";
        $body = 
            "<div class='emailBox'>".
            "   <img style='margin: auto; display: block;margin-bottom:10px;' width='110' height='110' src='".$homeurl."./settings/img/logo-email.png'/>".
            "   <div class='mainBox'>".
            "       <img style='margin: auto; display: block;margin-bottom:20px;' width='160' height='130' src='".$homeurl."/img/img_transfer.png'/>".
            "       <h1 class='titleEmail'>Hola ".strtolower($email)."</h1>".
            "       <p class='msg'>".
            "           Para completar el Cripto Pago, ingrese el c&oacute;digo a continuaci&oacute;n".
            "       </p>".
            "       <div class='validatorBox'>".
            "           <p class='code'>".$validator."</p>".
            "       </div>".
            "   </div>".
            "   <p class='copy'>".$footerEmails."</p>".
            "</div>";
            
    $body = templateEmail($body, $styleTag);
        
    enviarCorreo2($fromeMail, strtolower($email), $subject, $body);
        
    $msg = 'Para completar el Cripto Pago, ingrese el código a continuación: '.$validator;
    enviarSMS($userdata['paymobilephone'], $msg); //Cambiado "phone" que no se obtiene del users por paymobilephone
    
    $out->id = (int)$paymentid;
    
    header("HTTP/1.1 200");
    echo(json_encode($out));
    die();
    
?>