<?php
//  app/api/c2p/insert
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid",'bankid','phone','amount','token','currencyid');
    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"];
    $bankid = $_POST['bankid'];
    $phone = $_POST['phone'];
    $amount = $_POST['amount'];
    $token = $_POST['token'];
    $currencyid = $_POST['currencyid'];
    $ci = '';
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Validamos el si el usuario puede hacer operaciones
    isLevelValid($db, $userid);
    
    // Obtenemos primero que datos debemos consultas
    $sql = "SELECT type FROM users ".
    "       WHERE id = ".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $uservalid = $rs->fetch_assoc();
    
    // Validamos que usuario es para ver que tabla se consulta
    if(intval($uservalid['type']) == 1){
        // Consultamos persona natural
        $sql = "SELECT * FROM userpersons WHERE usrid = ".$userid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userinfo = $rs->fetch_assoc();
        
        // Validamos el tipo de documento, si es cedula podemos seguir
        if(intval($userinfo['doctype']) == 1){
                
            //Aqui nos toca validar la cedula, si tiene la v o no o si esta separa por un guion
            $ci = strtoupper($userinfo['doc']);
            
            // Obtenemos los NUMEROS DE LA CEDULA POR QUE RECUEDA EL CAMPO DICE SOLO NUMEROS 
            $cinumbers = preg_replace('/\D/', '', $ci);
            
            // Obtenemos las letras del CAMPO QUE ES EL N U M E R O
            $ciletters = preg_replace("/[^A-Za-z]/","",$ci);
            
            // Validamos si tenia numero o no pues a ver que paso en el campo NUMERICO
            
            if(intval($cinumber) < 30000000){
                if(strlen($ciletters) == 0){
                    $ci = "V".$cinumbers;
                }else if(strlen($ciletters) == 1){
                    $ci = $ciletters.$cinumbers;
                }else{
                    $ci = "V".$cinumbers;
                }
            }else if(intval($cinumber) > 80000000){
                if(strlen($ciletters) == 0){
                    $ci = "E".$cinumbers;
                }else if(strlen($ciletters) == 1){
                    $ci = $ciletters.$cinumbers;
                }else{
                    $ci = "E".$cinumbers;
                }
            }else{
                if(strlen($ciletters) == 0){
                    $ci = "V".$cinumbers;
                }else if(strlen($ciletters) == 1){
                    $ci = $ciletters.$cinumbers;
                }else{
                    $ci = "V".$cinumbers;
                }
            }
                
        }else if(intval($userinfo['doctype']) == 2){
            
            $ci = "P".strtoupper($userinfo['doc']);
            
        }else{
            
            badEnd("407",array("msg"=>determinateMsgFail(array(
                "esp"=>"Documento no es tipo cédula",
                "eng"=>"Identification is not kind identification card"), $lang, "Documento no es tipo cédula")));
                
        }
        
    }else if(intval($uservalid['type']) == 2){
        $sql = "SELECT * FROM usercompanies WHERE usrid = ".$userid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userinfo = $rs->fetch_assoc();
                
        //Aqui nos toca validar la cedula, si tiene la v o no o si esta separa por un guion
        $ci = strtoupper($userinfo['doc']);
            
        // Obtenemos los NUMEROS DE LA CEDULA POR QUE RECUEDA EL CAMPO DICE SOLO NUMEROS
        $cinumbers = preg_replace('/\D/', '', $ci);
            
        // Obtenemos las letras del CAMPO
        $ciletters = preg_replace("/[^A-Za-z]/","",$ci);
            
        // Validamos si tenia numero o no pues a ver que paso en el campo NUMERICO
        if(strlen($ciletters) == 0){
            $ci = "J".$cinumbers;
        }else if(strlen($ciletters) == 1){
            $ci = $ciletters.$cinumbers;
        }else{
            $ci = "J".$cinumbers;
        }
            
    }else{
        badEnd("500",array('msg'=>'No se pudo obtener su identificación'));
    }
    
    
    // Validamos el length ci
    if(strlen($ci) < 1 && strlen($ci) > 12){
        badEnd("408",array("msg"=>determinateMsgFail(array(
            "esp"=>"Cédula invalida",
            "eng"=>"Invalid identification card"), $lang, "Cédula invalida")));
    }
    
    // formateamos el telefono para quitarle el zero
    $phone = preg_replace('/^0?/', '', $phone);
    
    // Validamos que el interface de la moneda sea Bs
    $sql = "SELECT * ".
    "       FROM currencies ".
    "       WHERE id = ".$currencyid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $currency = $rs->fetch_assoc();
    
    $amount = (float)number_format($amount, $currency['decimals'], '.', '');
    
    // Si la interface es distinta a 1, no podemos hacer el pago
    if($currency['interface'] != 1){
        badEnd("500", array("msg"=>"La moneda debe ser Bs/VES"));
    }
    
    // Obtenemos la cuenta AFX del usuario
    $sql = "SELECT id FROM accounts  ".
    "       WHERE currencyid = ".$currencyid.
    "       AND paymentmethodid = -1 " .
    "       AND accounts.entityusrid = -1 ".
    "       AND userid=".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $account = $rs->fetch_assoc();
    
    //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();
    
    $level = 1;
    if($userdata["level"] == 0){
        $level = 1;
    }else{
        $level = $userdata["level"];
    }
    
    //Consultamos la cuenta que tiene la moneda del retiro de AFX
    $sql = "SELECT * FROM accounts WHERE userid = -1".
    "       AND currencyid = ".$currency["id"].
    "       AND paymentmethodid = -3";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Guardamos la data de la cuenta AFX
    $afxdata = $rs->fetch_assoc();
    
    //Obtenemos el fee de cada operacion por la moneda de la cuenta
    $sql = "SELECT * FROM cmspreffees WHERE currencyid = ".$currency["id"].
    "       AND levelid = ".$level.
    "       AND usertype = ".$userdata["type"];
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Guardamos la data de la cuenta
    $fee = $rs->fetch_assoc();
    
    //Validamos que el monto sea mas que el minimo aceptado
    if(validateMin($currency["id"],$userdata["type"], 1, $db, $amount)){
        badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Monto mínimo autorizado: ".numberFormatt($fee['mindeposit'], $currency['decimals']),
            "eng"=>"Minimum authorized amount: ".numberFormatt($fee['mindeposit'], $currency['decimals'])), $lang, "Monto mínimo autorizado: ".numberFormatt($fee['mindeposit'], $currency['decimals']))));
    }
    
    //Calculamos el monto real quitandole la comision
    if($fee["pctfeedeposits"] != null || $fee["nmlfeedeposits"] != null ){
        if($fee["pctfeedeposits"] == null){
            
            // Obtenemos el exonerado para depositos si podee
            $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
            "       WHERE currencyid = ".$currency["id"].
            "       AND userid = ".$userid.
            "       AND preffeesfield = 'nmlfeedeposits'";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $userExg = $res->fetch_assoc();
            
            $realfee = number_format($amount - ($amount - ($fee["nmlfeedeposits"] - ($fee["nmlfeedeposits"]/100 * $userExg['exonerated']) )), $currency['decimals'], '.', '');
            $realamount = number_format($amount - $realfee, $currency['decimals'], '.', '');
            
            if($realfee >= $realamount){
                badEnd("403", array("msg"=>determinateMsgFail(array(
                    "esp"=>"Monto es menor a comisión",
                    "eng"=>"Amount is less than commission"), $lang, "Monto es menor a comisión")));
            }
            
        }else{
            
            $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
            "       WHERE currencyid = ".$currency["id"].
            "       AND userid = ".$userid.
            "       AND preffeesfield = 'pctfeedeposits'";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $userExg = $res->fetch_assoc();
            
            $realfee = number_format((($fee["pctfeedeposits"] - ($fee["pctfeedeposits"]/100 * $userExg['exonerated']) )*$amount)/100, $currency['decimals'], '.', '');
            $realamount = number_format($amount - $realfee, $currency['decimals'], '.', '');
        }
    }else{
        $realfee = 0;
        $realamount = number_format($amount - $realfee, $currency['decimals'], '.', '');
    }
    
    validateOperations($db, $account['id'], $userid, $amount, 1);
    
    // Obtenemos la interfaz del banco
    $bankinterface = getActiveBank($db, 1, 1);
    
    $db->autocommit(FALSE);
    
    // Inicializamos la referencia
    $referencia = '';
    
    // Traemos el listado de los bancos
    switch($bankinterface){
        case 1:
            $nonce = generateNonce();
    
            // Llamamos a la api primerito
            $request = array(
                'telefonoCobrador'=>$phoneAFX,
                'banco'=>$bankid,
                'id'=>$ci,
                'telefonoPagador'=>$phone,
                'monto'=>(float)number_format($amount, $currency['decimals'], '.', ''),
                'token'=>$token,
                'motivo'=>'Depósito AFX',
                'origen'=>'12'
            );
            
            $headers = array('Content-Type:application/json', 
                "api-key: $BP_C2P_KEY", 
                "api-signature: ".
                (
                    generateApiSignature("/".$BP_VERSION."/pagos/c2p".$nonce.json_encode($request),$BP_C2P_KEY_SECRET)
                ),
                "nonce: ".$nonce,
            );
            
            // obtenemos respuesta
            $rest = queryApiBP($BP_URL_QA, "pagos/c2p", $BP_VERSION, "POST", $headers, $request);
            
            if(($rest['bodyres']->referencia == null || $rest['bodyres']->referencia == '') && $rest['httpres'] != 200 && $rest['httpres'] != 201){
                $msg_esp = "";
                $msg_eng = "";
                
                switch($rest['headerres']['codigorespuesta']){
                    case 'E028':
                        $msg_esp = "El código de operaciones ingresado es inválido. Por favor intente de nuevo";
                        $msg_eng = "The operations code is invalid. Please try again";
                        break;
                    case 'E010':
                        $msg_esp = "Monto no válido";
                        $msg_eng = "Invalid amount";
                        break;
                    case 'E012':
                        $msg_esp = "Teléfono no habilitado para pagar";
                        $msg_eng = "Phone not enabled to pay";
                        break;
                    case 'E013':
                        $msg_esp = "Excede cantidad de pagos diarios";
                        $msg_eng = "Exceeds amount of daily payments";
                        break;
                    case 'E014':
                        $msg_esp = "Excede monto total de pagos diarios";
                        $msg_eng = "Exceeds total amount of daily payments";
                        break;
                    case 'E015':
                        $msg_esp = "Excede monto máximo para un pago";
                        $msg_eng = "Exceeds maximum amount for a payment";
                        break;
                    case 'E016':
                        $msg_esp = "Excede cantidad de pagos diarios";
                        $msg_eng = "Exceeds amount of daily payments";
                        break;
                    case 'E017':
                        $msg_esp = "Excede monto total de pagos diarios";
                        $msg_eng = "Exceeds total amount of daily payments";
                        break;
                    case 'E018':
                        $msg_esp = "Error en número de banco";
                        $msg_eng = "Bank number error";
                        break;
                    case 'E021':
                        $msg_esp = "Teléfono receptor no registrado";
                        $msg_eng = "Receiving phone not registered";
                        break;
                    case 'E022':
                        $msg_esp = "Teléfono receptor no acepta pagos";
                        $msg_eng = "Receiving phone does not accept payments";
                        break;
                    case 'E023':
                        $msg_esp = "Identificación del beneficiario no coincide";
                        $msg_eng = "Beneficiary ID does not match";
                        break;
                    case 'E024':
                        $msg_esp = "Cliente bloqueado";
                        $msg_eng = "Client blocked";
                        break;
                    case 'E030':
                        $msg_esp = "Banco no activo en pago móvil";
                        $msg_eng = "Bank not active in mobile payment";
                        break;
                    case 'A001':
                        $msg_esp = "Firma digital inválida";
                        $msg_eng = "Invalid digital signature";
                        break;
                    default:
                        $msg_esp = $rest['headerres']['descripcioncliente'];
                        $msg_eng = $rest['headerres']['descripcioncliente'];
                }
                $msg_esp = $msg_esp." Codigo: ".$rest['headerres']['codigorespuesta'];
                $msg_eng = $msg_eng." Codigo: ".$rest['headerres']['codigorespuesta'];

                $db->rollback();
                $db->close();
                badEnd("500", array("msg"=>determinateMsgFail(array(
                    "esp"=>$msg_esp,
                "eng"=>$msg_eng), $lang, $msg_esp)/*, 'headers'=>$headers, 'request'=>$request, 'respuesta'=>$rest*/));
            }
            
            $referencia = $rest['bodyres']->referencia;
            break;
        case 2:
            
            // Llamamos a la api
            $request = array(
                'usuario'=>$rifafxAPI, // Usuario
                'rif_comercio'=>$rifafxAPI,
                'telefono_comercio'=>intval("58".$BA_phoneAFX),
                'bco_pago'=>$bankid,
                'cedula_pago'=>$ci,
                'telefono_pago'=>intval("58".$phone),
                'monto'=>number_format($amount, $currency['decimals'], ',', ''),
                'otp'=>$token,
                'motivo'=>'Depósito AFX',
                'area_origen'=>'01'
            );
            
            // Consultamos la api de banco activo
            $headers = array('Content-Type:application/json','apikey: '.$BA_API_KEY);
            $rest = queryApiBA($BA_URL_QA."cobro/c2p/1.0.0/c2p", "POST", $headers, $request);
            
            if(($rest['bodyres']->nroReferencia == null || $rest['bodyres']->nroReferencia == '') && $rest['httpres'] != 200 && $rest['httpres'] != 201){
                $msgs = validateErrorBancoActivo($rest['bodyres']->code, $rest['bodyres']->descripcion, $rest['bodyres']->descripcion);
                $msg_esp = $msgs->msg_esp;
                $msg_eng = $msgs->msg_eng;
                                
                $db->rollback();
                $db->close();
                badEnd("500", array("msg"=>determinateMsgFail(array(
                    "esp"=>$msg_esp,
                "eng"=>$msg_eng), $lang, $msg_esp)));
            }
            
            $referencia = $rest['bodyres']->nroReferencia;
            
            break;
    }
    
    
    
    //insertamos la trasaccion del deposito
    $sql = "INSERT INTO transactions".
    "       (".
    "       datecreated, ".
    "       dsc, ".
    "       amountghost, ".
    "       amount, ".
    "       accountid, ".
    "       orderid, ".
    "       txid, ".
    "       accountorigin, ".
    "       accountdestination".
    "       )".
    "       VALUES(".
    "       NOW(), ".
    "       'Depósito', ".
    "       0, ".
    "       ".$amount.", ".
    "       ".$account['id'].", ".
    "       NULL, ".
    "       NULL, ".
    "       NULL, ".
    "      ".$account["id"].//$paymentaccountid.
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //Guardamos el id de la transaccion de deposito
    $txid = (int)$db->insert_id;
    $out->id = $txid;
    
    //Le colocamos a la primera transferencia el txid
    $sql = "UPDATE transactions SET".
    "       txid = ".$txid.
    "       WHERE id = ".$txid;
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //insertamos la comision del deposito
    $sql = "INSERT INTO transactions".
    "       (".
    "       datecreated, ".
    "       dsc, ".
    "       amountghost, ".
    "       amount, ".
    "       accountid, ".
    "       orderid, ".
    "       txid, ".
    "       accountorigin, ".
    "       accountdestination".
    "       )".
    "       VALUES(".
    "       NOW(), ".
    "       'Comisión de Depósito', ".
    "       0, ".
    "       -".$realfee.", ".
    "       ".$account['id'].", ".
    "       NULL, ".
    "       ".$txid.", ".
    "       NULL, ".
    "      ".$afxdata["id"].//$paymentaccountid.
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //insertamos la comision del deposito
    $sql = "INSERT INTO transactions".
    "       (".
    "       datecreated, ".
    "       dsc, ".
    "       amountghost, ".
    "       amount, ".
    "       accountid, ".
    "       orderid, ".
    "       txid, ".
    "       accountorigin, ".
    "       accountdestination".
    "       )".
    "       VALUES(".
    "       NOW(), ".
    "       'Comisión de Depósito', ".
    "       0, ".
    "       ".$realfee.", ".
    "       ".$afxdata["id"].", ".//$paymentaccountid.", ".
    "       NULL, ".
    "       ".$txid.", ".
    "       NULL, ".
    "       ".$afxdata["id"].//$paymentaccountid.
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    //insertamos la comision del deposito
    $sql = "INSERT INTO deposits".
    "       (".
    "       paymentref, ".
    "       paymentaccountid, ".
    "       paymentdate, ".
    "       createddate, ".
    "       fee, ".
    "       transactionid, ".
    "       valid, ".
    "       pagomovilbankid,".
    "       amount ".
    "       )".
    "       VALUES(".
    "       '".$referencia."', ".
    //ERROR PONERSELA A LA COMISION DE AFX"       ".$afxdata["id"]/*$paymentaccountid*/.", ".
    "       ".$account["id"].", ".//Se le asigna a la cuenta del usuario
    "       NOW(), ".
    "       NOW(), ".
    "       ".$realfee.", ".
    "       ".$txid.", ".
    "       NOW(), ".
    "       ".$bankinterface.", ".
    "       ".$amount." ".
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    // Obtenemos el nombre del usuario
    $sql = "SELECT users.usr AS email, IF(userpersons.fname IS NULL, usercompanies.name, CONCAT(userpersons.fname,' ',userpersons.flastname)) AS name ".
    "       FROM users ".
    "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
    "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
    "       WHERE sessionid = '".$sessionid."'";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $userdataaudit = $res->fetch_assoc();
        
    $ipaddress = getRealIP();
    //auditoria
    setAudit($db, "OPERACIONES", $sessionid, "APP", "Se registró un depósito por ".$amount." (".$out->id.") en ".$currency['name'].", del usuario ".$userdataaudit['name'], $ipaddress);
    
    $db->commit();
    $db->close();
    
    header("HTTP/1.1 200");
    echo(json_encode($out));
    die();
    
?>