<?php
// cms/api/operations/reject

    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)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass();
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    $id = mysqli_real_escape_string($db, $_GET["id"]);
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 32))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    //Validamos que exista el registro
    $sql =  "SELECT * FROM transactions ".
            "INNER JOIN accounts ON accounts.id = transactions.accountid " .
            "INNER JOIN currencies ON accounts.currencyid = currencies.id " .
            "WHERE transactions.txid = ".$id. " AND currencies.interface = 1 AND transactions.paypending <> -1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
       
    $txdata = $rs->fetch_assoc();
      
    if($txdata["id"] == null){
        badEnd("404", array("msg"=>"No encontrado"));
    }
    
    $db->autocommit(FALSE);

    $sql = "UPDATE transactions SET".
    "       amountghost = amount + amountghost, ".
    "       amount = 0".
    "       WHERE txid = ".$id;
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
        
    //Colocamos la fecha de validacion del retiro
    $sql = "UPDATE withdrawals SET".
    "       rejected = NOW() ".
    "       WHERE transactionid = ".$id;
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    
    //Colocamos la fecha de validacion del deposito
    $sql = "UPDATE deposits SET".
    "       rejected = NOW() ".
    "       WHERE transactionid = ".$id;
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    $out->id = (int)$id;
    
    $ipaddress = getRealIP();
    
    //Obtenemos si es deposito o retiro
    $sql = "SELECT IF(deposits.transactionid IS NULL, 0, 1) AS isDeposit, ".
    "       IF(deposits.paymentref IS NULL, withdrawals.paymentref,deposits.paymentref) AS ref,".
    "       IF(withdrawals.transactionid IS NULL, 0, 1) AS isWithdraw".
    "       FROM transactions ".
    "       LEFT JOIN deposits ON deposits.transactionid = transactions.id ".
    "       LEFT JOIN withdrawals ON withdrawals.transactionid = transactions.id".
    "       WHERE id = ".$id;
    if (!$res=$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
            
    $txdataaudit = $res->fetch_assoc();
    
    //auditoria
    setAudit($db, "OPERACIONES", $sessionid, "CMS", "Se rechazó el ".(intval($txdataaudit['isDeposit']) == 1 ? 'depósito' : 'retiro')." ".$out->id, $ipaddress);
    
    $db->commit();
    
    $db->autocommit(TRUE);
    
    // Obtenemos los datos del usuario para el correo
    $sql = "SELECT users.usr AS email,  users.lang AS lang, users.id AS userid, ".
    "       IF(userpersons.fname IS NULL, usercompanies.name, CONCAT(userpersons.fname,' ',userpersons.flastname)) AS name, ".
    "       IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone " .
    "       FROM transactions, accounts, users ".
    "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
    "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
    "       WHERE transactions.id = ".$id.
    "       AND transactions.accountid = accounts.id ".
    "       AND accounts.userid = users.id";
    if (!$res=$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    $userdata = $res->fetch_assoc();
    
    // Consultamos los datos del mensaje
    $sql = "SELECT * FROM cmsmessages WHERE id = ".(intval($txdataaudit['isDeposit']) == 1 ? 9 : 10);
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $data = $rs->fetch_assoc();
    
    // Validamos que el usuario tenga las notificaciones activas
    $sql = "SELECT * FROM usermessages ".
    "       WHERE categoryid = ".$data['category'].
    "       AND usrid = ".$userdata['userid'];
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $userPref = $rs->fetch_assoc();
    
    if($userPref['email'] == null || $userPref['email'] == 1){
        $subject = $userdata['lang'] == 'esp' ? $data['name_esp'] : $data['name_eng'];
        $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
        $body = "<div class='emailBox'>".
            "           <img class='afxLogo' src='".$homeurlCMS."./settings/img/logo-email.png'/>".
            "           <div class='mainBox'>".
            "               <h1 class='titleEmail'>".
            "                   ".($userdata['lang'] == "esp" ? "Hola" : "Hello")." ".$userdata['name'].
            "               </h1>".
            "               <p class='msgEmail'>".
            "                   ".(
                                    intval($txdataaudit['isDeposit']) == 1 ? 
                                    (str_replace("<ref>", $txdataaudit['ref'],( $userdata['lang'] == 'esp' ? $data['dsc_esp'] :  $data['dsc_eng']))) : 
                                    (str_replace("<id>", $id,( $userdata['lang'] == 'esp' ? $data['dsc_esp'] : $data['dsc_eng'])))
                                ).
            "               </p>".
            "           </div>".
            "           <p class='copy'>".$footerEmails."</p>".
            "       </div>";
            
            $body = templateEmail($body, $STANDAR_STYLE_EMAIL);
                
        enviarCorreo2($fromeMail, strtolower($userdata['email']), $subject, $body);
    }
    // Se valida la preferenca del mensaje y se env赤a seg迆n el idioma
    if($userPref['sms'] == null || $userPref['sms'] == 1){
        $msg = (intval($txdataaudit['isDeposit']) == 1 ? 
                    (str_replace("<ref>", $txdataaudit['ref'],( $userdata['lang'] == 'esp' ? $data['sms_esp'] :  $data['sms_eng']))) : 
                    (str_replace("<id>", $id,( $userdata['lang'] == 'esp' ? $data['sms_esp'] : $data['sms_eng']))));
        enviarSMS($userdata['phone'], $msg);
    }
    
    if($userPref['system'] == null || $userPref['system'] == 1){
            
        $email = '';
        $sms = '';
        
        // Si se envia por correo obtenemos el correo del usuario
        if($userPref['email'] == null || $userPref['email'] == 1){
            $sql = "SELECT usr ".
            "       FROM users ".
            "       WHERE id = ".$userdata['userid'];
            if (!$resPref=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                    
            $rowPrefCom = $resPref->fetch_assoc();
            
            $email = $rowPrefCom['usr'];
        }
        
        // SI se envia por sms, obtenemos el numero del usuario
        if($userPref['sms'] == null || $userPref['sms'] == 1){
            $sql = "SELECT IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone ".
            "       FROM users ".
            "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
            "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
            "       WHERE users.id = ".$userdata['userid'];
            if (!$resPref=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $rowPrefCom = $resPref->fetch_assoc();
            
            $sms = $rowPrefCom['phone'];
            
        }
                    
        // Enviamos el mensaje por la mensajeria interna
        $msg = (
            intval($txdataaudit['isDeposit']) == 1 ? 
                (str_replace("<ref>", $txdataaudit['ref'],( $userdata['lang'] == 'esp' ? $data['dsc_esp'] :  $data['dsc_eng']))) : 
                (str_replace("<id>", $id,( $userdata['lang'] == 'esp' ? $data['dsc_esp'] : $data['dsc_eng']))));
        saveInternalMsg($db, $msg, $userdata['userid'], $email, $sms);
    }
    
    $db->close();
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
