<?php
include_once ("utiles.php");
include_once ("apt_funciones.php");

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

error_reporting(E_ALL & ~ E_NOTICE & ~ E_WARNING);

date_default_timezone_set("America/Panama");

session_start();
$_SESSION['database'] = $_POST['database'];
$_SESSION["suc_id"] = $_POST['suc_id'];
$_SESSION['id_cte'] = $_POST['id_cte'];
$_SESSION['swsavelog'] = $_POST['swsavelog'];

$cDb_Nam = $_SESSION['database'];
$cSuc_id = $_SESSION["suc_id"];
$cCod_Ct = $_SESSION['id_cte'];
$SaveLog = $_SESSION['swsavelog'];

$hoynow = getdate();
$timeStamp = $hoynow["year"] . "-" . $hoynow["mon"] . "-" . $hoynow["mday"];
$uniqueFleName = random_string(8);

$cSql = 'CALL ' . $cDb_Nam . '.ecxc00001("' . $cCod_Ct . '","' . $uniqueFleName . '")';

$resp1 = update_Sql($connection, $cSql);

if ($SaveLog == '1') {
    logs2('', false);
    logs2('SQL 1: ' . $cSql);
    logs2('RESP1: ' . ($resp1 ? 'true' : 'false'));
    logs2('', false);
    logs2('', false);
}
;

if ($resp1 == true) {
    $resp2 = false;
    $Json = '';
    
    
    $cSql = 'SELECT 
    IFNULL(id_reg,0) AS id_reg,
    IFNULL(autoin,0)            AS autoin,
    IFNULL(op_fechae,"2000-01-01 01:00:00")        AS op_fechae,
    IFNULL(op_fechav,"2000-01-01 01:00:00")        AS op_fechav,
    IFNULL(id_tipo,"")          AS id_tipo,
    IFNULL(estado,"")           AS estado,
    IFNULL(op_id,"")            AS op_id,
    IFNULL(cxc_detalle,"")      AS cxc_detalle,
    IFNULL(op_debito ,000000000000.00) AS op_debito,
    IFNULL(op_credito,000000000000.00) AS op_credito,
    IFNULL(op_saldo  ,000000000000.00) AS op_saldo,
    IFNULL(op_signo,1)          AS op_signo,
    IFNULL(op_fechac ,"2000-01-01 01:00:00")        AS op_fechac,
    IFNULL(op_num_doc,"")       AS op_num_doc,
    IFNULL(op_num_fact,"")      AS op_num_fact,
    IFNULL(op_num_docfis,"")    AS op_num_docfis,
    IFNULL(op_aptdo,"")         AS op_aptdo
FROM tmp.' . $uniqueFleName . ' ORDER BY c_id,op_fecha_capt,op_num_fact';
    
    $Json = getRowAll($connection, $cSql, $recount, true);
    
    if ($recount > 0) {
        $resp2 = true;
    }
    
    if ($SaveLog == '1') {
        logs2('', false);
        logs2('SQL 2: ' . $cSql);
        logs2('RESP2: ' . ($resp2 ? 'true' : 'false'));
        logs2('', false);
        logs2('', false);
    }
}

if (($resp1 == true) and ($resp2 == true)) {
    $msg = utf8_encode($Json);
    echo $Json;
} else {
    $msg = '';
    echo "Error: " . "<br>" . $connection->error;
}

print_r($msg);

@mysqli_close($connection);

function random_string($length)
{
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));
    
    for ($i = 0; $i < $length; $i ++) {
        $key .= $keys[array_rand($keys)];
    }
    
    return $key;
}

?>
