<?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++) {
        $cAutoinc_Factur = $aJson[$iIndex]->autoin;
        $op_abono_Factur = $aJson[$iIndex]->op_abono;
        $op_ult_actu_fec = $aJson[$iIndex]->op_ult_actu_fec;
        $op_ult_actu_usr = $aJson[$iIndex]->op_ult_actu_usr;
        $audit_monto_ant = $aJson[$iIndex]->audit_monto_ant;
        $audit_monto_abn = $aJson[$iIndex]->audit_monto_abn;
        $audit_monto_act = $aJson[$iIndex]->audit_monto_act;

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

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

        $cSql_Str = "UPDATE $cDb_Nam.operacion_cxc SET 
                    op_estado ='Pendiente', 
                    op_canc   ='true' 
                WHERE (op_debito<op_abono) 
                AND   (c_id='$cCte_id') 
                AND   (autoin='$cAutoinc_Factur');";
        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='$op_ult_actu_usr', 
                    op_ult_actu_fec='$op_ult_actu_fec' 
                WHERE (c_id  ='$cCte_id') 
                AND   (autoin='$cAutoinc_Factur');";
        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='$op_ult_actu_usr', 
                    op_ult_actu_fec='$op_ult_actu_fec' 
                WHERE (c_id  ='$cCte_id') 
                AND   (autoin='$cAutoinc_Factur');";
        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='$cAutoinc_Factur');";
        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
