<?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");
include_once("apt_funciones.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["pag_auto"] = $_POST['pag_auto'];
$_SESSION["pag_mont"] = $_POST['pag_mont'];
$_SESSION["jsn_abon"] = $_POST['jsn_abon'];
$_SESSION['jsn_fact'] = $_POST['jsn_fact'];
$_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['pag_auto'];
$mnt_pag = $_SESSION['pag_mont'];
$cJsn_Ab = $_SESSION["jsn_abon"];
$cJsn_Fa = $_SESSION["jsn_fact"];
$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++++++++++++++++++++++++++++++++++++++++++' . chr(13);
    echo 'database : ' . $cDb_Nam . chr(13);
    echo 'Sucursal : ' . $cSuc_id . chr(13);
    echo 'Estacion : ' . $cEst_id . chr(13);
    echo 'Cliente  : ' . $cCte_id . chr(13);
    echo 'Pago_Jsn : ' . $cJsn_Ab . chr(13);
    echo 'Fact_Jsn : ' . $cJsn_Fa . chr(13);
    echo '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' . chr(13);
}
mysqli_select_db($connection, $cDb_Nam);

/*----------------- SE PROCESA EL REGISTRO DEL PAGO QUE VIENE DEL POS (JSON)-----------*/
if (!empty($cJsn_Ab)) {
    $reg1 = json_decode($cJsn_Ab, TRUE);
    $TablaCx = $reg1['operacion_cxc'];
    $reg_cx = $reg1['regs_cx'];
    $Sql_Ins_Abn = jsonmysql2($TablaCx, $reg_cx, 'operacion_cxc', $connection, $cDb_Nam, $SaveLog);
}
/* ------------------------------------------------------------------------------------*/

if ($SaveLog == 1)
    print_r($Sql_Ins_Abn);

try {
    $iCount = 0;
    $iIndex = 0;
    /*---------- SE PROCESA EL REGISTRO DE LAS FACTURAS PAGADAS QUE VIENEN DEL POS (JSON)--------*/

    if (!empty($cJsn_Fa)) {
        $aJson = json_decode($cJsn_Fa);
        $iCount = count($aJson);
        for ($iIndex = 0; $iIndex < $iCount; $iIndex++) {

            if ($aJson[$iIndex]->id_fact != '')
                $cxc_apl_id_fact = $aJson[$iIndex]->id_fact;
            else
                $cxc_apl_id_fact = '0';
            $abn_cxc_fec = $aJson[$iIndex]->abn_fecha;
            $abn_num_ref = $aJson[$iIndex]->abn_num_refe;
            $abn_num_doc = $aJson[$iIndex]->abn_num_doc;
            $abn___monto = $aJson[$iIndex]->abn_monto;
            $fact_codcte = $aJson[$iIndex]->fact_cod_cte;
            $fact_num_re = $aJson[$iIndex]->fact_num_refe;
            $fac_num_doc = $aJson[$iIndex]->fact_num_doc;
            $fac_ope_ref = $aJson[$iIndex]->fact_ope_ref;
            $fac_mnt_ant = $aJson[$iIndex]->fact_saldo_ant;
            $fac_mnt_abn = $aJson[$iIndex]->fact_abono;
            $fac_mnt_act = $aJson[$iIndex]->fact_saldo_act;
            //      $fact_detall = $aJson[$iIndex]->fact_detalle;
            $abn_act_fec = $aJson[$iIndex]->ult_actu_fch;
            $abn_act_usr = $aJson[$iIndex]->ult_actu_usr;
            $fact_aplica = $aJson[$iIndex]->fact_aplicado;

            $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 INTO $cDb_Nam.`operacion_cxc_apl_det2`
                (`abn_fecha`,`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`,`fact_detalle`,`ult_actu_usr`,`ult_actu_fch`,`fact_aplicado`) VALUES 
                ('$abn_cxc_fec','$abn_num_ref','$abn_num_doc',$abn___monto,'$fact_codcte','$fact_num_re','$fac_num_doc','$fac_ope_ref',$fac_mnt_ant,$fac_mnt_abn,$fac_mnt_act,'$cDet','$abn_act_usr','$abn_act_fec','$fact_aplica') 
                ON DUPLICATE KEY UPDATE 
                abn_fecha       =VALUES(abn_fecha) ,
                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);" .  chr(13);
    */
            $cSql_Str = "INSERT INTO $cDb_Nam.`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`,`fact_detalle`,`ult_actu_usr`,`ult_actu_fch`) VALUES 
                            ('$abn_num_ref','$abn_num_doc',$abn___monto,'$fact_codcte','$fact_num_re','$fac_num_doc','$fac_ope_ref',$fac_mnt_ant,$fac_mnt_abn,$fac_mnt_act,'$cDet','$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);" .  chr(13);

            if ($SaveLog == 1)
                print_r($cSql_Str);
            else
                mysqli_query($connection, $cSql_Str);

            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 
                                ('$cxc_apl_id_fact','$fac_ope_ref','$fac_mnt_abn','$abn_num_ref','$fact_codcte') 
                            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);" .  chr(13);
            } 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);" .  chr(13);
            }
            if ($SaveLog == 1)
                print_r($cSql_Str);
            else
                mysqli_query($connection, $cSql_Str);

            /*------------RECALCULA EL SALDO ACTUAL DE LAS OPERACIONES ENTRANTES----------------------------------------------------*/
            $cSql_Str = "UPDATE operacion_cxc c
                        INNER JOIN operacion_cxc_apl_det2 d ON (c.c_id = d.fact_cod_cte) AND (c.autoin = d.fact_num_refe) AND (d.abn_num_refe='$num_pag')
                            SET c.op_saldo= ((c.op_debito+ c.op_credito)- c.op_abono)
                        WHERE ((c.c_id='$cCte_id') AND (c.autoin ='$fact_num_re')); ";
            if ($SaveLog == 1)
                print_r($cSql_Str);
            else
                mysqli_query($connection, $cSql_Str);

            /*------------APLICA DESDE operacion_cxc_apl_det2 LOS SALDOS DE LAS FACTURAS CON LOS PAGOS ENTRANTES--------------------*/
            $cSql_Str = "UPDATE operacion_cxc c
                        INNER JOIN operacion_cxc_apl_det2 d ON (c.c_id = d.fact_cod_cte) AND (c.autoin = d.fact_num_refe) AND (d.abn_num_refe='$num_pag') AND (c.op_saldo = d.fact_saldo_ant)
                            SET 
                            c.op_abono = (c.op_abono + d.fact_abono)
                        WHERE ((d.fact_cod_cte='$cCte_id') AND (c.autoin ='$fact_num_re'));";
            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='$fact_num_re');" .  chr(13);
            if ($SaveLog == 1)
                print_r($cSql_Str);
            else
                mysqli_query($connection, $cSql_Str);
*/
            $cSql_Str = "UPDATE $cDb_Nam.operacion_cxc SET 
                    op_saldo        = (op_debito + op_credito) - op_abono,  
                    op_estado       = IF( ((op_debito+op_credito)>op_abono),'Pendiente','Pagada'), 
                    op_canc         = IF( ((op_debito+op_credito)>op_abono),'false'    ,'true'  ),
                    op_ult_actu_usr = '$abn_act_usr',
                    op_ult_actu_fec = '$abn_act_fec',
                    usermodify      =1  
                WHERE ((c_id='$cCte_id') AND (autoin='$fact_num_re'));" .  chr(13);
            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 ($SaveLog == 1) {
    echo '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' . chr(13);
    echo 'RESP: ' . ($result ? 'true' : 'false') . chr(13);
    echo '++++++++++++++++++++++++++++++++++++++++++++++insert_json_op_gen.php++++++++++++++++++++++++++++++++++++++++++' . chr(13);
}

$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