<?php
// cms/api/operations/accept

    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($_POST, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
        
    $paymentfile = $_FILES["paymentfile"];
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass();
    $sessionid = mysqli_real_escape_string($db, $_POST["sessionid"]);//Estaba en get corregido cambio a post
    $id = mysqli_real_escape_string($db, $_POST["id"]);
    $paymentdate = "";
    $paymentref = "";
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //En caso de que el paymentdate sea enviado, se construye el query
    if(isset($_POST["paymentdate"]) && $_POST["paymentdate"] != ""){
        $paymentdate = " paymentdate = '".mysqli_real_escape_string($db, $_POST["paymentdate"])."', ";
    }
    
    //En caso de que el paymentref sea enviado, se construye el query
    if(isset($_POST["paymentref"]) && $_POST["paymentref"] != ""){
        $paymentref = " paymentref = '".mysqli_real_escape_string($db, $_POST["paymentref"])."', ";
    }
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 31))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
        
    //Validamos que exista el registro
    $sql =  "SELECT txid AS id FROM transactions ".//WHERE id = ".$id
            "INNER JOIN accounts ON accounts.id = transactions.accountid " .
            "INNER JOIN currencies ON accounts.currencyid = currencies.id " .
            "WHERE transactions.id = ".$id. " AND currencies.interface = 1 AND transactions.paypending <> -1";
    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){
        badEnd("404", array("msg"=>"No se encuentra el registro"));
    }
    
    $db->autocommit(FALSE);
    
    //Actualizamos la transaccion
    $sql = "UPDATE transactions SET".
    "       amount = amount + amountghost, ".
    "       amountghost = 0 ".
    "       WHERE txid = ".$id;
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    if($paymentfile["name"] != null){
        //Obtenemos la extension de la imagen
        $ext = pathinfo($paymentfile['name'], PATHINFO_EXTENSION);
        //Creamos la direccion del folder
        $urlfolder = "../../../uploads/payments/";
        
        //Movemos el FILE del directorio temporal al del sistema para su uso
        if(!move_uploaded_file($paymentfile["tmp_name"], $urlfolder . "/" . $id . "." . $ext)){
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>"Error guardando la imagen"));
        }
        
        // Y le agregamos la marca de agua
        $file = "uploads/payments/" . $id . "." . $ext;
        $zona = new DateTimeZone('America/Caracas'); 
        $fecha = microtime(true)+$zona->getOffset(new DateTime());
        $dateW = date("d/m/Y",$fecha)." - ".date("h:i:s a",$fecha);
        $watermark = $dateW. " ".$weblink." #".$id;
        $save = $urlfolder . "/" . $id . "." . $ext;
        addTextWatermark($file,$watermark,$save, "../../../");
    }
    
    //Colocamos la fecha de validacion del retiro
    $sql = "UPDATE withdrawals SET".
    "       ".$paymentref.
    "       ".$paymentdate.
    "       ".($paymentfile["name"] != null ? "filetype = '".$paymentfile["type"]."', " : "").
    "       valid = 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".
    "       valid = 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();
    
    // 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.$sql));
    }
    
    $userdata = $res->fetch_assoc();
    
    //auditoria
    setAudit($db, "OPERACIONES", $sessionid, "CMS", "Se aprobó el ".(intval($txdataaudit['isDeposit']) == 1 ? 'depósito' : 'retiro')." ".$out->id, $ipaddress);
    
    $db->commit();
    
    $db->autocommit(true);
    
    // Obtenemos los datos de la moneda
    // Obtenemos los datos del usuario para el correo
    $sql = "SELECT users.usr AS email,  currencies.name AS name, currencies.symbol AS symbol ".
    "       FROM accounts, users, currencies, transactions ".
    "       WHERE  transactions.id = ".$id.
    "       AND accounts.userid = users.id".
    "       AND transactions.accountid = accounts.id ".
    "       AND accounts.currencyid = currencies.id";
    if (!$res=$db->query($sql)){
        badEnd("500", array("msg"=>determinateDBError($db)));
    }
    
    $currency = $res->fetch_assoc();
    
    // Consultamos los datos del mensaje
    $sql = "SELECT * FROM cmsmessages WHERE id = ".(intval($txdataaudit['isDeposit']) == 1 ? 6 : 8);
    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'>".
            "                   ".( $userdata['lang'] == 'esp' ? 
                                    (intval($txdataaudit['isDeposit']) == 1 ?
                                        (str_replace('<ref>', $txdataaudit['ref'],$data['dsc_esp'])) :
                                        (str_replace('<currency_name>', $currency['symbol'],$data['dsc_esp']))) : 
                                    (intval($txdataaudit['isDeposit']) == 1 ?
                                        (str_replace('<ref>', $txdataaudit['ref'],$data['dsc_eng'])) :
                                        (str_replace('<currency_name>', $currency['symbol'],$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 = ( $userdata['lang'] == 'esp' ? 
                    (intval($txdataaudit['isDeposit']) == 1 ? (str_replace('<ref>', $txdataaudit['ref'],$data['sms_esp'])) : (str_replace('<currency_name>', $currency['symbol'],$data['sms_esp']))) : 
                    (intval($txdataaudit['isDeposit']) == 1 ? (str_replace('<ref>', $txdataaudit['ref'],$data['sms_eng'])) : (str_replace('<currency_name>', $currency['symbol'],$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 = ( $userdata['lang'] == 'esp' ? 
                    (intval($txdataaudit['isDeposit']) == 1 ? (str_replace('<ref>', $txdataaudit['ref'],$data['sms_esp'])) : (str_replace('<currency_name>', $currency['symbol'],$data['sms_esp']))) : 
                    (intval($txdataaudit['isDeposit']) == 1 ? (str_replace('<ref>', $txdataaudit['ref'],$data['sms_eng'])) : (str_replace('<currency_name>', $currency['symbol'],$data['sms_eng'])))
                );
            saveInternalMsg($db, $msg, $userdata['userid'], $email, $sms);
        }
    
    $db->close();
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
