<?php
// app/api/transactions/validation

    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","id");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Declaracion de variables
    $out = new stdClass;
    $sessionid = $_GET["sessionid"];
    $id = $_GET["id"];
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    //Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Validamos que exista el registro
    $sql = "SELECT t.id AS id, CASE ".
    "           WHEN t.dsc LIKE '%comis%' THEN 'Comisión' ".
    "           WHEN (SELECT COUNT(tx.id) FROM transactions tx WHERE tx.txid = t.txid) = 1 THEN 'Ajuste' ".
    "           WHEN (SELECT COUNT(tx.id) FROM transactions tx WHERE tx.txid = t.txid) = 8 THEN 'Intercambio' ".
    "           WHEN (SELECT COUNT(de.transactionid) FROM deposits de WHERE de.transactionid = t.txid) = 1 THEN 'Depósito' ".
    "           WHEN (SELECT COUNT(withdraw.transactionid) FROM withdrawals withdraw WHERE withdraw.transactionid = t.txid AND t.amount = 0 AND t.amountghost <> 0 AND withdraw.valid IS NULL AND withdraw.rejected IS NULL) = 1 THEN 'Retiro' ".
    "           WHEN (SELECT COUNT(tx.id) FROM transactions tx WHERE tx.txid = t.txid AND tx.amount = 0 AND tx.amountghost <> 0) = 4 THEN 'Transferencia' END AS type ".
    "       FROM transactions t WHERE t.id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
            
    $row = $rs->fetch_assoc();
        
    // Retornamos 404 cuando la busqueda no obtiene resutados
    if($row["id"] == null || $row["type"] == null){
        badEnd("404", array("msg"=>determinateMsgFail(array(
            "esp"=>"No se encuentra el registro",
            "eng"=>"Cannot find the record"), $lang, "No se encuentra el registro")));
    }
    
    //Creamos el validador
    $validator = getValidator(8);
    
    //Actualizamos el validator
    $sql = "UPDATE transactions SET".
    "       validthru = DATE_ADD(NOW(), INTERVAL 10 MINUTE), ".
    "       validator = ".$validator.
    "       WHERE txid = ".$id;
    if (!$db->query($sql)){
        badEnd("500", array("msg"=>determinateDBError($db)));
    }
    
    //Retornamos 304 si no se elimino ningun registro
    if ($db->affected_rows == 0){
        badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"No se pudo modificar",
            "eng"=>"Cannot modify"), $lang, "No se pudo modificar")));
    }
    
    $out->id = (int)$id;
    
    //Obtenemos el correo del usuario para envio de codigo
    $sql = "SELECT * FROM users WHERE sessionid = '".$sessionid."'";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Guardamos la data de la cuenta
    $userdata = $rs->fetch_assoc();
    
    $email = $userdata["usr"];
    $subject = ($row['type'] == 'Retiro' ? ($userdata['lang'] == 'esp' ? "Código de retiro ".$shortname : 'Withdrawal code '.$shortname) : ($userdata['lang'] == 'esp' ? "Código de Transferencia ".$shortname."" : 'Transfer Code '.$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'>".($userdata['lang'] == "esp" ? "Hola" : "Hello")." ".strtolower($email)."</h1>".
            "       <p class='msg'>".
            "           ".($userdata['lang'] == "esp" ? 
                            "Para completar ".($row['type'] == 'Retiro' ? 'el retiro' : 'la transferencia')." de fondos ingrese el c&oacute;digo a continuaci&oacute;n" : 
                            "To complete the ".($row['type'] == 'Retiro' ? 'withdrawal' : 'transfer')." of funds enter the code below").
            "       </p>".
            "       <div class='validatorBox'>".
            "           <p class='code'>".$validator."</p>".
            "       </div>".
            "       <p class='note'>".
            "           ".($lang == "esp" ? "Este c&oacute;digo expirar&aacute; en 10 minutos" : "This code will expire in 10 minutes").
            "       .</p>".
            "   </div>".
            "   <p class='copy'>".$footerEmails."</p>".
            "</div>";
            
    $body = templateEmail($body, $styleTag);
            
    enviarCorreo2($fromeMail, strtolower($email), $subject, $body);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>