<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
include_once("utiles.php");

date_default_timezone_set("America/Panama");

if (!$connection = connectDb()) {
    die("err db");
} else {
    mysqli_query($connection, "SET NAMES 'utf8';");
}

session_start();
$_SESSION['database'] = $_POST['database'];
$_SESSION["suc_id"] = $_POST['suc_id'];
$_SESSION["est_id"] = $_POST['est_id'];
$_SESSION["cte_id"] = $_POST['cte_id'];
$_SESSION["num_pag"] = $_POST['num_pag'];
$_SESSION["mnt_pag"] = $_POST['mnt_pag'];
$_SESSION["sql_data"] = $_POST['sql_data'];
$_SESSION['jsn_data'] = $_POST['jsn_data'];
$_SESSION['log_save'] = $_POST['log_save'];

$cDb_Nam = $_SESSION["database"];
$cSuc_id = $_SESSION["suc_id"];
$cEst_id = $_SESSION["est_id"];
$cCte_id = $_SESSION["cte_id"];
$num_pag = $_SESSION['num_pag'];
$mnt_pag = $_SESSION['mnt_pag'];
$cJsn_Dt = $_SESSION["jsn_data"];
$cSql_Dt = $_SESSION["sql_data"];
$SaveLog = $_SESSION['log_save'];

$Saldo_Ant = 0.00;
$Monto_Abn = 0.00;
$Saldo_Act = 0.00;

$hoynow = getdate();
$timeStamp = $hoynow["year"] . "-" . $hoynow["mon"] . "-" . $hoynow["mday"];
$timeStamp = date("Y-m-d H:i:s");

if ($SaveLog == 1) {
    echo '++++++++++++++++++++++++++++++++++++++++++++++insert_json_op_gen.php++++++++++++++++++++++++++++++++++++++++++';
    echo 'database : ' . $cDb_Nam;
    echo 'Sucursal : ' . $cSuc_id;
    echo 'Estacion : ' . $cEst_id;
    echo 'Cliente  : ' . $cCte_id;
    echo 'Data_Sql : ' . $cSql_Dt;
    echo 'Data_Jsn : ' . $cJsn_Dt;
    echo '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++';
}
mysqli_select_db($connection, $cDb_Nam);
/*
$cSql_Cmd = "INSERT $cDb_Nam.INTO operacion_cxc_apl_json 
    (`c_id`,`op_ref,`op_valor`,`info_str`,`json_str`,`syncprocesing`,`usermodify`) VALUES
    ('$cCte_id','$Num_pag',$mnt_pag,?,?,0,0)";

$stmt = mysqli_prepare($connection, $cSql_Cmd);
mysqli_stmt_bind_param($stmt, "ss", $cSql_Dt, $cJsn_Dt);
mysqli_stmt_execute($stmt);
*/
try {
    $iCount = 0;
    $iIndex = 0;
    $aSql_Lines = explode(";", $cSql_Dt);

    $iCount = count($aSql_Lines);
    for ($iIndex = 0; $iIndex < $iCount; $iIndex++) {
        $cSql_Cmd = trim($aSql_Lines[$iIndex]);
        if (!($cSql_Cmd == '') || !($cSql_Cmd == ';')) {

            if ($SaveLog == 1)
                print_r($cSql_Cmd);
            else
                mysqli_query($connection, $cSql_Cmd);
        }
    }
    $iCount = 0;
    $iIndex = 0;
    $aJson = json_decode($cJsn_Dt);
    $iCount = count($aJson);
    for ($iIndex = 0; $iIndex < $iCount; $iIndex++) {

        $abn_cxc_aut = $aJson[$iIndex]->abn_cxc_aut;
        $abn_num_doc = $aJson[$iIndex]->abn_num_doc;
        $abn___monto = $aJson[$iIndex]->abn_monto;
        $fac_cxc_aut = $aJson[$iIndex]->fac_cxc_aut;
        $fac_num_doc = $aJson[$iIndex]->fac_num_doc;
        $fac_ope_ref = $aJson[$iIndex]->fac_ope_ref;
        $fac_mnt_ant = $aJson[$iIndex]->fac_mnt_ant;
        $fac_mnt_abn = $aJson[$iIndex]->fac_mnt_abn;
        $fac_mnt_act = $aJson[$iIndex]->fac_mnt_act;
        $abn_act_fec = $aJson[$iIndex]->abn_act_fec;
        $abn_act_usr = $aJson[$iIndex]->abn_act_usr;

        if ($aJson[$iIndex]->id_fact != '')
            $cxc_apl_id_fact = $aJson[$iIndex]->id_fact;
        else
            $cxc_apl_id_fact = '0';

        $cDet = "";
        $cDet = $cDet . "  FACTURA #[$fac_num_doc] " + chr(13);
        $cDet = $cDet . "->SALDO-ANT [$fac_mnt_ant] " + chr(13);
        $cDet = $cDet . "->PAGADO    [$fac_mnt_abn] " + chr(13);
        $cDet = $cDet . "->SALDO-ACT [$fac_mnt_act] " + chr(13);

        $cSql_Str = "INSERT IGNORE INTO `operacion_cxc_apl_det2`
            (`abn_num_refe`,`abn_num_doc`,`abn_monto`,`fact_cod_cte`,`fact_num_refe`,`fact_num_doc`,`fact_ope_ref`,`fact_saldo_ant`, `fact_abono`,`fact_saldo_act`,`ult_actu_usr`,`ult_actu_fch`) VALUES 
            ('$abn_cxc_aut','$abn_num_doc','$abn___monto','$cCte_id','$fac_cxc_aut','$fac_num_doc','$fac_ope_ref','$fac_mnt_ant','$fac_mnt_abn','$fac_mnt_act','$abn_act_usr','$abn_act_fec') 
            ON DUPLICATE KEY UPDATE 
            abn_num_refe    =VALUES(abn_num_refe) ,
            abn_num_doc     =VALUES(abn_num_doc),
            abn_monto       =VALUES(abn_monto),
            fact_cod_cte    =VALUES(fact_cod_cte),
            fact_num_refe   =VALUES(fact_num_refe),
            fact_num_doc    =VALUES(fact_num_doc),
            fact_ope_ref    =VALUES(fact_ope_ref),
            fact_saldo_ant  =VALUES(fact_saldo_ant),
            fact_abono      =VALUES(fact_abono),
            fact_saldo_act  =VALUES(fact_saldo_act),
            ult_actu_usr    =VALUES(ult_actu_usr),
            ult_actu_fch    =VALUES(ult_actu_fch)";
        mysqli_query($connection, $cSql_Str);

        //if (array_key_exists('id_fact', $aJson)==true) {
        if ($aJson[$iIndex]->id_fact != '') {
            $cSql_Str = "INSERT INTO $cDb_Nam.operacion_cxc_apl (id_fact, op_id, op_valor, op_ref, c_id) VALUES 
            ('$fac_cxc_aut','$fac_ope_ref','$fac_mnt_abn','$abn_cxc_aut','$cCte_id') 
            ON DUPLICATE KEY UPDATE 
            id_fact =VALUES(id_fact) ,
            op_id   =VALUES(op_id)   ,
            op_valor=VALUES(op_valor),
            op_ref  =VALUES(op_ref)  ,
            c_id    =VALUES(c_id)";
        } else {
            $cSql_Str = "INSERT INTO $cDb_Nam.operacion_cxc_apl (op_id, op_valor, op_ref, c_id) VALUES 
            ('$fac_ope_ref','$fac_mnt_abn','$abn_cxc_aut','$cCte_id')
            ON DUPLICATE KEY UPDATE 
            op_id   =VALUES(op_id)   ,
            op_valor=VALUES(op_valor),
            op_ref  =VALUES(op_ref)  ,
            c_id    =VALUES(c_id)";
        }
        if ($SaveLog == 1)
            print_r($cSql_Str);
        else
            mysqli_query($connection, $cSql_Str);

        $cSql_Str = "UPDATE $cDb_Nam.operacion_cxc SET 
                    op_abono  = (op_abono + $fac_mnt_abn) 
                WHERE (c_id  ='$cCte_id') 
                AND   (autoin='$fac_cxc_aut');";
        if ($SaveLog == 1)
            print_r($cSql_Str);
        else
            mysqli_query($connection, $cSql_Str);

        $cSql_Str = "UPDATE $cDb_Nam.operacion_cxc SET 
                    op_estado =IF( ((op_debito+op_credito)>op_abono),'Pendiente','Pagada'), 
                    op_canc   =IF( ((op_debito+op_credito)>op_abono),'false'    ,'true'  )  
                WHERE (c_id='$cCte_id') 
                AND   (autoin='$fac_cxc_aut');";
        if ($SaveLog == 1)
            print_r($cSql_Str);
        else
            mysqli_query($connection, $cSql_Str);

        $cSql_Str = "UPDATE $cDb_Nam.operacion_cxc SET 
                    op_ult_actu_usr='$abn_act_usr', 
                    op_ult_actu_fec='$abn_act_fec' 
                WHERE (c_id  ='$cCte_id') 
                AND   (autoin='$fac_cxc_aut');";
        if ($SaveLog == 1)
            print_r($cSql_Str);
        else
            mysqli_query($connection, $cSql_Str);

        $cSql_Str = "UPDATE $cDb_Nam.operacion_cxc SET 
                    op_ult_actu_usr='$abn_act_usr', 
                    op_ult_actu_fec='$abn_act_fec' 
                WHERE (c_id  ='$cCte_id') 
                AND   (autoin='$fac_cxc_aut');";
        if ($SaveLog == 1)
            print_r($cSql_Str);
        else
            mysqli_query($connection, $cSql_Str);

        $cSql_Str = "UPDATE $cDb_Nam.operacion_cxc SET usermodify=1 
                WHERE (c_id  ='$cCte_id') 
                AND   (autoin='$fac_cxc_aut');";
        if ($SaveLog == 1)
            print_r($cSql_Str);
        else
            mysqli_query($connection, $cSql_Str);
        $Saldo_Act = Get_Saldo_cxc($connection, $cDb_Nam, $cSuc_id, $cOp__id, $cOp_cxc, $SaveLog);
    }
} catch (exception $e) {
    $result = false;
    $msg = array(
        "success" => "false",
        "detalle" => $connection,
        "saldo_ant" => 0.00,
        "saldo_abn" => 0.00,
        "saldo_act" => 0.00
    );
    echo "<br>" . $connection->error;
} finally {
    $result = true;
    $msg = array(
        "success" => "true",
        "detalle" => "OK",
        "saldo_ant" => $Saldo_Ant,
        "saldo_abn" => $Monto_Abn,
        "saldo_act" => $Saldo_Act

    );
}

/*
if ($cCte_id == '')
    $rest1 = jsonmysql($connection, $cDb_Nam, $JsonDat, 'operacion_cxc', $SaveLog);
else
    $rest1 = jsonmysql($connection, $cDb_Nam, $JsonDat, 'operacion_cxc_apl', $SaveLog);
*/

if ($SaveLog == 1) {
    echo '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++';
    echo 'RESP: ' . ($result ? 'true' : 'false');
    echo '++++++++++++++++++++++++++++++++++++++++++++++insert_json_op_gen.php++++++++++++++++++++++++++++++++++++++++++';
}

$jsonData[] = $msg;

header('content-type: application/json');
echo json_encode($jsonData);

@mysqli_close($connection);

function Get_Saldo_cxc($poConn2, $cpDatab2, $cpCod_Cte)
{
    $Saldo_Cxc = '0.00';
    $records = 0;

    $sql = "SELECT
            SUM( IFNULL(op_debito,0)+ IFNULL(op_credito,0) )- SUM(IFNULL(op_abono,0)) AS pendiente
        FROM $cpDatab2.operacion_cxc
        WHERE (c_id='$cpCod_Cte')";

    $data = getRow($poConn2, $sql, $records, false);

    if ($records == 0) {
        $Saldo_Cxc = '0.00';
    } else {
        $Saldo_Cxc = ((($data['pendiente'] == '') or ($data['pendiente'] == null)) ? '0.00' : $data['pendiente']);
    }
    return $Saldo_Cxc;
}
// CREADO POR: JOHNN GUTIERREZ 
//FECHA DE CREACION: 2022-11-16 02:24pm
// FECHA DE ULTIMA MODIFICASION: 2022-11-16 02:24pm
// FECHA DE ULTIMA MODIFICASION: 2022-11-22 06:24pm