<?php
/*
JOHNN GUTIERREZ, 
FECHA DE CREACION   2022-09-20
ULTIMA MODIFICASION 2022-09-20
BUSCA SI EXISTE ALGUNA FACTURA VENCIDA DEL CLIENTE
*/
include '../conn_obj/utiles_pdo.php';
//include '../conn_obj/repo_func.php';
date_default_timezone_set("America/Panama");
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
#error_reporting(E_ALL);
session_start();
if ($_POST) {
    $_SESSION['Database'] = $_POST['Database'];
    $_SESSION['Cod_Cte'] = $_POST['Cod_Cte'];

    $cDb_Nam = $_SESSION['Database'];
    $pCod_Cte = $_SESSION['Cod_Cte'];

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

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

    $cSql_ln = "
    SELECT 
      IF(DATE(NOW())>=DATE(op_fechav2),'1','0') AS  vencido 
    FROM 
    (  SELECT 
    		op.c_id, 
    		ct.c_descripcion, 
    		ct.c_dias_credito, 
    		IF(ct.tipo_calculo=1, 'DIAS/CALE', 'MES/COMPL') AS TIPO_C, 
    		DATE(op.op_fechae) AS op_fechae, 
    		@venc_m0 := LAST_DAY(op.op_fechae) AS venc_m0, 
    		@calc_m  := FLOOR(ct.c_dias_credito/30) AS calc_me, 
    		@venc_m  := DATE_ADD(@venc_m0, INTERVAL @calc_m MONTH) AS venc_m, 
    		@venc_d  := DATE_ADD(DATE(op.op_fechae), INTERVAL ct.c_dias_credito DAY) AS venc_d, 
    		IF(((ct.tipo_calculo IS NULL) OR (ct.tipo_calculo=0) OR (ct.tipo_calculo=1)), @venc_d, @venc_m) AS op_fechav2 
      FROM $cDb_Nam.operacion_cxc op 
      INNER JOIN $cDb_Nam.clientes ct ON (op.c_id=ct.c_id) 
      WHERE (op.c_id='$pCod_Cte')
      AND   (op.id_tipo=2) 
      AND   (op.op_debito-op.op_abono)>0 
      ORDER BY op.c_id, op.op_fechae ASC 
    ) a LIMIT 1 ";
    
    $oResult = mysqli_query($connection, $cSql_ln); 
    $oRow = mysqli_fetch_array($oResult, MYSQLI_ASSOC);

    if (($oRow['vencido'] != '') && ($oRow['vencido'] != 'null') && ($oRow['vencido'] != 'NULL' > 0)) {
        $str_result = $oRow['vencido'];
    } else {
        $str_result = '0';
    }

    header('content-type: text/plain; charset=UTF-8');

    echo $str_result;
    $oRow = null;
    mysqli_free_result($oResult);
    mysqli_close($connection);
}
?>    