<?php
ini_set('display_errors', 1);
ini_set('memory_limit', '4096M');
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
#error_reporting(E_ALL);
date_default_timezone_set("America/Panama");

include "../conn_obj/conn_param.php";

if ($conn = @mysqli_connect($Srv_Info['hostname'], $Srv_Info['username'], $Srv_Info['password'])) {
    mysqli_select_db($conn, $Srv_Info['dbname']);
    mysqli_query($conn, "SET NAMES 'utf8'");
} else
    die("err db");

header('content-type: application/json');

session_start();
$_SESSION['pDb_Name'] = $_POST['pDb_Name'];
$_SESSION['pCod_Cte'] = $_POST['pCod_Cte'];
$_SESSION['pCod_Usu'] = $_POST['pCod_Usu'];
$_SESSION['pMnt_Cte'] = $_POST['pMnt_Cte'];
$_SESSION['pSuc_Pag'] = $_POST['pSuc_Pag'];
$_SESSION['pRetArray'] = $_POST['pRetArray'];
$_SESSION['pDebuger'] = $_POST['pDebuger'];
$_SESSION['pAutoriza'] = $_POST['pAutoriza'];

$cDb_Name = $_SESSION['pDb_Name'];
$cCod_Cte = $_SESSION['pCod_Cte'];
$cCod_Usu = $_SESSION['pCod_Usu'];
$fCte_Pago = $_SESSION['pMnt_Cte'];
$cSuc_Pago = $_SESSION['pSuc_Pag'];
$cRetArray = isset($_SESSION['pRetArray']) ? $_SESSION['pRetArray'] : 0;
$iDebuger = isset($_SESSION['pDebuger']) ? $_SESSION['pDebuger'] : 0;
$cAutoriza = isset($_SESSION['pAutoriza']) ? $_SESSION['pAutoriza'] : 0;

$cNip_Cte = '';
$cDb_NameC = "`$cDb_Name`";
$now = new DateTime();

$cDateTime = $now->format('Y-m-d H:i:s');
$cDate = $now->format('Y-m-d');

$iAuto_Pag = CXC_Get_Save_Next_ID($conn, $cDb_NameC);
$cNDoc_Pag = CXC_Get_Save_Next_Doc($conn, $cDb_NameC, 'no_pagoacxc', true);
$cDeta_Pag = 'PAGO/ABONOS A FACTURAS VARIAS ' . $cAutoriza;
$iOpId_Pag = 'PA' . str_pad(trim($cNDoc_Pag), 6, '0', STR_PAD_LEFT);
$cCmd_Debug = "";
$cSql_Log1 = "";
$cSql_LogC = "";
$LimitDoc = 100;
$CountDoc = 1;
$RestaDoc = 0;

if ($iDebuger == 1) {
    $cCmd_Debug .= "/*" . chr(13);
    $cCmd_Debug .= "Parametros de entrada: " . chr(13);
    $cCmd_Debug .= "pDb_Name = $cDb_Name" . chr(13);
    $cCmd_Debug .= "pCod_Cte = $cCod_Cte" . chr(13);
    $cCmd_Debug .= "pCod_Usu = $cCod_Usu" . chr(13);
    $cCmd_Debug .= "pMnt_Cte = $fCte_Pago" . chr(13);
    $cCmd_Debug .= "pSuc_Pag = $cSuc_Pago" . chr(13);
    $cCmd_Debug .= "pDebuger = $iDebuger" . chr(13);

    $cCmd_Debug .= "Variables adicionales: " . chr(13);
    $cCmd_Debug .= "iAuto_Pag=$iAuto_Pag" . chr(13);
    $cCmd_Debug .= "cNDoc_Pag=$cNDoc_Pag" . chr(13);
    $cCmd_Debug .= "iOpId_Pag=$iOpId_Pag" . chr(13);
    $cCmd_Debug .= "cDeta_Pag=$cDeta_Pag" . chr(13);
    $cCmd_Debug .= "*/" . chr(13);
}

mysqli_select_db($conn, $cDb_Name);

$cSql_Str = "
    CREATE TABLE IF NOT EXISTS $cDb_NameC.`operacion_cxc_mas_log` (
        `autoin` BIGINT(20) NOT NULL AUTO_INCREMENT,
        `fecha` DATETIME NULL DEFAULT NULL,
        `cod_usu` VARCHAR(20) NULL DEFAULT '' COLLATE 'utf8_general_ci',
        `cod_cte` VARCHAR(20) NULL DEFAULT '' COLLATE 'utf8_general_ci',
        `mnt_cte` DECIMAL(12,2) NULL DEFAULT '0.00',
        `auto_pag` VARCHAR(20) NULL DEFAULT '' COLLATE 'utf8_general_ci',
        `ndoc_pag` VARCHAR(20) NULL DEFAULT '' COLLATE 'utf8_general_ci',
        `opId_pag` VARCHAR(20) NULL DEFAULT '' COLLATE 'utf8_general_ci',
        `deta_pag` VARCHAR(120) NULL DEFAULT '' COLLATE 'utf8_general_ci',
        `sql_cmd` TEXT NULL DEFAULT NULL COLLATE 'utf8mb3_general_ci',
        PRIMARY KEY (`autoin`) USING BTREE
    )
    COLLATE='utf8_general_ci'
    ENGINE=InnoDB;
    ";
mysqli_query($conn, $cSql_Str);

#mysqli_begin_transaction($conn);
$bErrors = 0;
$oQry_Resp = null;
try {
    //Inserta el pago.
    if ($iDebuger == 1) {
        $cCmd_Debug .= "/*INSERTA EL PAGO*/" . chr(13);
    }
    $cSql_Str = "
    INSERT IGNORE INTO $cDb_NameC.`operacion_cxc` (
        `autoin`,`op_fechae`,`id_tipo`,`op_id`,`c_id`,`cxc_detalle`,`op_fechav`,`op_debito`,`op_credito`,`op_saldo`,`op_abono`,`op_canc`,`op_apagar`,`op_estado`,`op_tipodoc`,`u_id`,`op_sec_id`,`activado`,`autoinc_banco`,`op_neto`,
        `suc_id`,`conc_id`,`op_signo`,`op_fechac`,`op_contab`,`op_base`,`op_itbms`,`pers_id`,`op_orig`,`op_rel`,`op_num_doc`,`op_num_fact`,`op_fecha_capt`,`op_num_docfis`,`op_recarg`,`mon_op`,
        `mon_taza_op`,`op_retenc`,`id_retenc`,`mon_id1`,`mon_taza_v1`,`mon_taza_c1`,`mon_id2`,`mon_taza_v2`,`mon_taza_c2`,`mon_id3`,`mon_taza_v3`,`mon_taza_c3`,`op_info`,`op_aptdo`,`op_visible`,`syncprocesing`,`usermodify`,`useroption`,
        `contab_emp_ids`,`es_corre`,`c_nip`) 
    VALUES ($iAuto_Pag, '$cDateTime', 20, '$iOpId_Pag', '$cCod_Cte', '$cDeta_Pag', '$cDateTime', 0.00, $fCte_Pago, 0.00, $fCte_Pago, 'false', 0.00, 'Pendiente', 'PA', '$cCod_Usu', '', 0, 0, $fCte_Pago,
            $cSuc_Pago, 0, -1, '$cDateTime', 0, $fCte_Pago, 0.00, 0, $cSuc_Pago, '', '$iOpId_Pag', '$iOpId_Pag', '$cDateTime', '', 0.00, '01',
            1, 0.00, 0, '01', 0.00, 0.00, '01', 0.00, 0.00, '01', 0.00, 0.00, '', 0, 1, 0, 0,0,     
            '', '', '$cNip_Cte');";
    $cSql_Log1 .= $cSql_Str . chr(13);
    if ($iDebuger == 1)
        $cCmd_Debug .= $cSql_Str . chr(13);
    else
        mysqli_query($conn, $cSql_Str);

    $cSql_Str = "SET @saldo:=0.00;";
    if ($iDebuger == 1)
        $cCmd_Debug .= $cSql_Str . chr(13);
    mysqli_query($conn, $cSql_Str);

    $cSql_Str = "SET @mnt_pag:=$fCte_Pago;";
    if ($iDebuger == 1)
        $cCmd_Debug .= $cSql_Str . chr(13);
    mysqli_query($conn, $cSql_Str);

    $cSql_Str = "SET @Pagad_N:=00000000.00;";
    if ($iDebuger == 1)
        $cCmd_Debug .= $cSql_Str . chr(13);
    mysqli_query($conn, $cSql_Str);

    if ($iDebuger == 1)
        $cCmd_Debug .= "/*BUSCA TODAS LAS FACTURAS PENDIENTES DE ESE CLIENTE POR PAGAR*/" . chr(13);

    $cSql_Str = "
    SELECT *
    FROM (
        SELECT 
            c.id_reg,
            c.autoin                    AS Auto_id,
            c.op_fechae    	            AS Fecha,
            c.op_fechav	   	            AS FechaVenc,
            c.id_tipo	   	            AS nCod_Tp,
            c.op_tipodoc   	            AS cCod_Tp,
            c.op_id		   	            AS Cod_Cxc,
            c.c_id		   	            AS Cod_Cte,
            c.cxc_detalle  	            AS Detalle ,
            @saldo   := (c.op_debito + c.op_credito)-c.op_abono AS Saldo_Ant,
            @Pagad_N := ROUND($cDb_NameC.cxc_pagos_pag(@mnt_pag,@saldo),2) AS Pagad_Nuev,
            ROUND(@mnt_pag,2)           AS BALANCE, 
            ROUND(@saldo-@Pagad_N,2)    AS Saldo_Nuev,
            o.op_total			        AS Mont_Doc_Op,
            c.op_sec_id			        AS Op_id,	
            c.op_rel			        AS NumDocRel,
            c.op_num_doc	            AS NumDoc,
            c.op_num_fact	            AS NumFac,
            c.op_num_docfis	            AS NumFacFis
        FROM $cDb_NameC.operacion_cxc c
        LEFT JOIN $cDb_NameC.operacion o ON c.op_sec_id=o.op_id 
        WHERE (c.c_id = '$cCod_Cte')
        AND   ( (id_tipo = 2) OR (id_tipo = 22) ) 
        AND   ((ROUND(c.op_debito,2)+ROUND(c.op_credito,2)-ROUND(c.op_abono,2))>0)
        ORDER BY c.op_fechae ASC) a
    WHERE (a.Pagad_Nuev>0); ";

    if ($iDebuger == 1) {
        $cCmd_Debug .= $cSql_Str . chr(13);
    }
    $cSql_LogC .= $cSql_Log1;
    //save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  $cSql_Log1);
    $oQry_Resp = mysqli_query($conn, $cSql_Str);
} catch (Exception  $e) {
    save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  $cSql_LogC);
    save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  "/*" . $e->getMessage() . "*/");
    $bErrors = 1;
}
$oData = [];
if ($bErrors == 0) {
    if (!empty($oQry_Resp) and mysqli_num_rows($oQry_Resp) > 0) {
        $Registers = mysqli_num_rows($oQry_Resp);
        save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  "Facturas a procesar->: $Registers");
        $RestaDoc = $Registers;
        /*
        $rows = mysqli_fetch_assoc($oQry_Resp);
        $Json_Data = json_encode($rows, JSON_PRETTY_PRINT);
        $cSql_Log1 = $Json_Data . chr(13);
        save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  $cSql_Log1);
        $Json_Data = null;
        $rows = null;
        */

        try {
            if ($fCte_Pago > 0) {
                $oData = [];
                $iNumDocProc = 0;
                $cDet = "";

                $oFactPagadas = array();
                $oLstFactPaga = array();

                if ($iDebuger == 1)
                    $cCmd_Debug .= "/*PROCESO DE PAGO Y RESGISTRO DE TODAS LAS FACTURAS POSIBLES CON ESE PAGO*/" . chr(13);
                $CountDoc = 1;
                $MemoLn = "";
                while ($oData = mysqli_fetch_assoc($oQry_Resp)) {
                    $cSql_Log1 = "";
                    $cNum_DocF = $oData['NumFacFis'];
                    $cNum_Fact = $oData['NumFac'];
                    $cNum_Corr = $oData['NumDoc'];
                    $cNum_Rela = $oData['NumDocRel'];

                    $fMont_Doc = number_format($oData['Saldo_Ant'], 2);
                    $fMont_Pag = number_format($oData['Pagad_Nuev'], 2);
                    $fSald_Act = number_format($oData['Saldo_Nuev'], 2);
                    $cFechaDoc = $oData['Fecha'];
                    $iAuto_Fac = $oData['Auto_id'];
                    $iOpId_Fac = $oData['Op_id'];

                    //$iAuto_Pag = $oData['autoin'];
                    //$iOpId_Pag = $oData['op_id'];

                    $oFactPagada["fac_auto"] = $iAuto_Fac;
                    $oFactPagada["fac_nocor"] = $cNum_Corr;
                    $oFactPagada["fac_nofac"] = $cNum_Fact;
                    $oFactPagada["fac_nofacF"] = $cNum_DocF;
                    $oFactPagada["fac_op_id"] = $iOpId_Fac;
                    $oFactPagada["fac_op_re"] = $cNum_Rela;
                    $oFactPagada["referencia"] = "FACTURA   #: " . ($cNum_DocF == '' ? $cNum_Fact : $cNum_DocF);
                    $oFactPagada["saldo_ant"] = $fMont_Doc;
                    $oFactPagada["monto_pag"] = $fMont_Pag;
                    $oFactPagada["saldo_act"] = $fSald_Act;

                    if ($cRetArray == 1) {
                        array_push($oLstFactPaga, $oFactPagada);
                    }
                    $MemoLn = str_repeat('-', 28) . chr(13);
                    $MemoLn .= "FACTURA   #: " . ($cNum_DocF == '' ? $cNum_Fact : $cNum_DocF) . chr(13);
                    $MemoLn .= sprintf("->SALDO-ANT: %12.2f", $fMont_Doc) . chr(13);
                    $MemoLn .= sprintf("->PAGADO   : %12.2f", $fMont_Pag) . chr(13);
                    $MemoLn .= sprintf("->SALDO-ACT: %12.2f", $fSald_Act) . chr(13);

                    $cDet .= $MemoLn;

                    $cSql_Str = "
                        INSERT INTO $cDb_NameC.`operacion_cxc_apl_det2` 
                            (`abn_fecha`,`abn_num_refe`,`abn_num_doc`,`abn_monto`,`fact_cod_cte`,`fact_num_doc`,`fact_num_refe`,`fact_saldo_ant`,`fact_abono`,`fact_saldo_act`,`fact_detalle`,`fact_aplicado`,`syncprocesing`,`usermodify`) VALUES 
                            ('$cFechaDoc', $iAuto_Pag, '$iOpId_Pag', $fCte_Pago, '$cCod_Cte', '$cNum_Fact', $iAuto_Fac, $fMont_Doc, $fMont_Pag, $fSald_Act, '$MemoLn', 0, 0, 1);";
                    $cSql_Log1 .= $cSql_Str . chr(13);
                    if ($iDebuger == 1)
                        $cCmd_Debug .= $cSql_Str . chr(13);
                    else
                        mysqli_query($conn, $cSql_Str);

                    $cSql_Str = "";
                    if (FieldExists($conn, $cDb_NameC, 'id_fact', $cDb_Name . '.operacion_cxc_apl') == true) {
                        $cSql_Str = "
                        INSERT IGNORE INTO $cDb_NameC.`operacion_cxc_apl`
                            (id_fact, op_id, op_valor, op_ref, c_id, syncprocesing, usermodify) VALUES 
                            ($iAuto_Fac, '$iOpId_Fac', $fCte_Pago, $iAuto_Pag, '$cCod_Cte',0,0);";
                    } else {
                        $cSql_Str = "
                        INSERT IGNORE INTO $cDb_NameC.`operacion_cxc_apl`
                            (op_id, op_valor, op_ref, c_id, syncprocesing, usermodify) VALUES 
                            ('$iOpId_Fac', $fCte_Pago, $iAuto_Pag, '$cCod_Cte', 0, 0);";
                    };
                    $cSql_Log1 .= $cSql_Str . chr(13);
                    if ($iDebuger == 1)
                        $cCmd_Debug .= $cSql_Str . chr(13);
                    else
                        mysqli_query($conn, $cSql_Str);

                    //Facturas
                    $cSql_Str = "
                    UPDATE $cDb_NameC.`operacion_cxc` SET 
                        op_abono        = (op_abono+ $fMont_Pag), 
                        op_ult_actu_usr = '$cCod_Usu', 
                        op_ult_actu_fec =NOW()  
                    WHERE (c_id  ='$cCod_Cte') 
                    AND   (autoin= $iAuto_Fac);";
                    $cSql_Log1 .= $cSql_Str . chr(13);
                    if ($iDebuger == 1)
                        $cCmd_Debug .= $cSql_Str . chr(13);
                    else
                        mysqli_query($conn, $cSql_Str);

                    $cSql_Str = "
                    UPDATE $cDb_NameC.`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'  ), 
                        usermodify=1 
                    WHERE (c_id  ='$cCod_Cte') 
                    AND   (autoin= $iAuto_Fac);";
                    $cSql_Log1 .= $cSql_Str . chr(13);
                    if ($iDebuger == 1)
                        $cCmd_Debug .= $cSql_Str . chr(13);
                    else
                        mysqli_query($conn, $cSql_Str);

                    //Pagos
                    $cSql_Str = "
                    UPDATE $cDb_NameC.`operacion_cxc` SET 
                        op_estado ='Aplicado', 
                        op_canc   ='true'  
                    WHERE (c_id  ='$cCod_Cte')
                    AND   (autoin= $iAuto_Pag);";
                    $cSql_Log1 .= $cSql_Str . chr(13);
                    if ($iDebuger == 1)
                        $cCmd_Debug .= $cSql_Str . chr(13);
                    mysqli_query($conn, $cSql_Str);

                    /*
                    $cSql_Str = "
                        INSERT INTO $cDb_NameC.operacion_cxc (
                            `autoin`,`op_fechae`,`id_tipo`,`op_id`,`c_id`,`cxc_detalle`,`op_fechav`,`op_debito`,`op_credito`,`op_saldo`,`op_abono`,`op_canc`,`op_apagar`,`op_estado`,`op_tipodoc`,`u_id`,`op_sec_id`,`activado`,`autoinc_banco`,`op_neto`,
                            `suc_id`,`conc_id`,`op_signo`,`op_fechac`,`op_contab`,`op_base`,`op_itbms`,`pers_id`,`op_orig`,`op_rel`,`op_num_doc`,`op_num_fact`,`op_fecha_capt`,`op_num_docfis`,`op_recarg`,`mon_op`,
                            `mon_taza_op`,`op_retenc`,`id_retenc`,`mon_id1`,`mon_taza_v1`,`mon_taza_c1`,`mon_id2`,`mon_taza_v2`,`mon_taza_c2`,`mon_id3`,`mon_taza_v3`,`mon_taza_c3`,`op_info`,`op_aptdo`,`op_visible`,`syncprocesing`,`usermodify`,`useroption`,
                            `contab_emp_ids`,`es_corre`,`c_nip`) 
                        SELECT 
                            `autoin`,`op_fechae`,`id_tipo`,`op_id`,`c_id`,`cxc_detalle`,`op_fechav`,`op_debito`,`op_credito`,`op_saldo`,`op_abono`,`op_canc`,`op_apagar`,`op_estado`,`op_tipodoc`,`u_id`,`op_sec_id`,`activado`,`autoinc_banco`,`op_neto`,
                            `suc_id`,`conc_id`,`op_signo`,`op_fechac`,`op_contab`,`op_base`,`op_itbms`,`pers_id`,`op_orig`,`op_rel`,`op_num_doc`,`op_num_fact`,`op_fecha_capt`,`op_num_docfis`,`op_recarg`,`mon_op`,
                            `mon_taza_op`,`op_retenc`,`id_retenc`,`mon_id1`,`mon_taza_v1`,`mon_taza_c1`,`mon_id2`,`mon_taza_v2`,`mon_taza_c2`,`mon_id3`,`mon_taza_v3`,`mon_taza_c3`,`op_info`,`op_aptdo`,`op_visible`,`syncprocesing`,`usermodify`,`useroption`,
                            `contab_emp_ids`,`es_corre`,`c_nip` 
                        FROM $cDb_NameC.operacion_cxc 
                        WHERE (c_id  ='$cCod_Cte') 
                        AND   (autoin= $iAuto_Fac) 
                        ON DUPLICATE KEY UPDATE 
                            op_abono        = VALUES(op_abono)    ,
                            op_saldo        = VALUES(op_saldo)    ,
                            op_estado       = VALUES(op_estado)   ,
                            op_canc         = VALUES(op_canc)     ,
                            op_apagar       = VALUES(op_apagar)   ,
                            usermodify      = VALUES(usermodify)  ,
                            op_ult_actu_usr = VALUES(op_ult_actu_usr),
                            op_ult_actu_fec = VALUES(op_ult_actu_fec);";
                    save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  $cSql_Str);
                    if ($iDebuger == 1)
                        $cCmd_Debug .= $cSql_Str . chr(13);
                    else
                        mysqli_query($conn, $cSql_Str);
                    */

                    $cSql_LogC .= $cSql_Log1;

                    if ($CountDoc >= $LimitDoc) {
                        save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  $cSql_LogC);
                        $cSql_LogC = "";
                        $CountDoc = 1;
                        $RestaDoc = $RestaDoc - $LimitDoc;
                    } else {
                        ++$CountDoc;
                        if ($CountDoc >= $RestaDoc) {
                            save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  $cSql_LogC);
                        }
                    }

                    //save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  $cSql_Log1);
                    ++$iNumDocProc;
                }
                if ($iDebuger == 1)
                    $cCmd_Debug .= "/*FIN DE PAGOS DE DOCUMENTOS*/" . chr(13);

                $cDet .= str_repeat('-', 28) . chr(13);
                $cDet .= sprintf("DOCUMENTOS PROCESADOR: %4.0f", $iNumDocProc) . chr(13);
                //save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  "/*" . $cDet . "*/");
                if ($oData != null)
                    $oData = null;
            }
            if ($iDebuger == 0) {
                #mysqli_commit($conn);
            }
            //save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  $cSql_LogC);
            save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  "success=true");
            $msg = array("success" => "true", "pag_auto" => $iAuto_Pag, "pag_ndoc" => $cNDoc_Pag, "pag_opid" => $iOpId_Pag, "detalle" => "OK ($iNumDocProc) facturas procesadas.", "data" => ($cRetArray == 1 ? $oLstFactPaga : $cDet));
        } catch (Exception  $e) {
            $cCmd_Debug = "";
            save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  $cSql_LogC);
            save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  "/*" . $e->getMessage() . "*/");
            $msg = array("success" => "false", "pag_auto" => -1, "pag_ndoc" => -1, "pag_opid" => -1, "detalle" => "ERROR AL PROCESAR EL LOTE DE FACTURAS: " . $e->getMessage());
        }
    } else {
        $cCmd_Debug = "";
        $msg = array("success" => "false", "pag_auto" => -1, "pag_ndoc" => -1, "pag_opid" => -1, "detalle" => "No se encontraton facturas que correspondan a al cliente -> '$cCod_Cte'", "data" => "");
        save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  $cSql_LogC);
        save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag,  "success=false");
    }
} else {
    if ($iDebuger == 0) {
        #mysqli_rollback($conn);
    }
    $cCmd_Debug = "";
    $msg = array("success" => "false", "pag_auto" => -1, "pag_ndoc" => -1, "pag_opid" => -1, "detalle" => $conn, "data" => "");
    save_log_cxc($cDb_Name, $conn, $cCod_Usu, $cCod_Cte,  $fCte_Pago, $iAuto_Pag, $cNDoc_Pag, $iOpId_Pag, $cDeta_Pag, "success=false");
}
if ($iDebuger == 0)
    echo ($cCmd_Debug);

print_r(json_encode($msg));

@mysqli_close($conn);
session_unset();
session_destroy();

function CXC_Get_Save_Next_ID($pConn, $pDatabase)
{
    $ID_OPLEN = 7;
    $cOp_ID_R = '';
    $oQry_Res = null;
    $oRow_Res = null;

    $cSql_Cmd = "
        UPDATE $pDatabase.`conf_sistema` SET 
            no_cxc_id2 = no_cxc_id2+1
        WHERE (suc_id      =1)
        AND   (no_estacion =1)";
    mysqli_query($pConn, $cSql_Cmd);

    $cSql_Cmd = "
    SELECT 
        CONVERT(	CONCAT( IFNULL(suc_id,'1'),LPAD(IFNULL(no_estacion,'0'),3,'0'),LPAD( (IFNULL(no_cxc_id2,'0') + 1),$ID_OPLEN,'0') ) , CHAR CHARACTER SET utf8) AS CorOper 
    FROM $pDatabase.`conf_sistema` 
    WHERE (suc_id      =1) 
    AND   (no_estacion =1) 
    ORDER BY `autoinc` ASC LIMIT 1";
    $oQry_Res = mysqli_query($pConn, $cSql_Cmd);
    $oRow_Res = mysqli_fetch_row($oQry_Res);
    $cOp_ID_R = $oRow_Res[0];
    mysqli_free_result($oQry_Res);
    $oRow_Res = null;

    return $cOp_ID_R;
};

function CXC_Save_Next_ID($pConn, $pDatabase)
{
    $cSql_Cmd = "
        UPDATE $pDatabase.`conf_sistema` SET 
            no_cxc_id2 = no_cxc_id2+1
        WHERE (suc_id      =1)
        AND   (no_estacion =1)";
    mysqli_query($pConn, $cSql_Cmd);
}

function CXC_Get_Save_Next_Doc($pConn, $pDatabase, $pCampo, $pUpdateVal)
{
    $pCampo = trim($pCampo);

    $cSql_Cmd = "
        SELECT 
            IFNULL($pCampo,0) + 1 AS corre 
        FROM $pDatabase.`conf_sistema` 
        WHERE suc_id      =1 
        AND   no_estacion =1 
        ORDER BY `autoinc` ASC LIMIT 1";

    $oRespX = mysqli_query($pConn, $cSql_Cmd);
    $oRowRX = mysqli_fetch_row($oRespX);
    $cCorrX = $oRowRX[0];

    if (($cCorrX == '') || ($cCorrX == null)) {
        return 0;
    } else {
        if ($pUpdateVal == true) {
            $cSql_Cmd = "
                UPDATE $pDatabase.`conf_sistema` SET  $pCampo = ($pCampo + 1) 
                WHERE suc_id      =1
                AND   no_estacion =1";
            mysqli_query($pConn, $cSql_Cmd);
        }
        return $cCorrX;
    }
}

function save_log_cxc($pDatabase, $pConn, $pcCod_Usu, $pCod_Cte,  $pCte_Pago, $pAuto_Pag, $pNDoc_Pag, $pOpId_Pag, $pDeta_Pag,  $pSql_cmd)
{
    $cSql_Cmd = "
    INSERT INTO $pDatabase.`operacion_cxc_mas_log` 
    (`fecha`, `cod_usu`    , `cod_cte`   , `mnt_cte`   , `auto_pag`, `ndoc_pag`, `opId_pag`, `deta_pag`, `sql_cmd`) VALUES
    (NOW()  ,  '$pcCod_Usu', '$pCod_Cte' , $pCte_Pago  , '$pAuto_Pag', '$pNDoc_Pag', '$pOpId_Pag', '$pDeta_Pag', ?)";
    try {

        if ($stmt = mysqli_prepare($pConn, $cSql_Cmd)) {
            mysqli_stmt_bind_param($stmt, "s", $pSql_cmd);
            mysqli_stmt_execute($stmt);
        }
    } catch (Exception $e) {
        echo "Error al guardar el LOG." . $e->getMessage();
    }
};

function FieldExists($pConn, $pfield, $pFull_DB_Table_Name)
{
    $cSql_Cmd = "SHOW COLUMNS FROM $pFull_DB_Table_Name WHERE UCASE(field)=UCASE('" . trim($pfield) . "') ";
    $oRespX = mysqli_query($pConn, $cSql_Cmd);
    if (!empty($oRespX) and mysqli_num_rows($oRespX) > 0)
        return true;
    else
        return false;
};
/*
JOHNN GUTIERREZ
jg_gutierrez@yahoo.es
2024-01-23
*/
