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

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

date_default_timezone_set("America/Panama");
error_reporting(E_ALL & ~ E_NOTICE & ~ E_WARNING);

session_start();

$_SESSION['database'] = $_POST['database'];
$_SESSION["suc_id"] = $_POST['suc_id'];
$_SESSION["op__id"] = $_POST['op__id'];
$_SESSION["id_cte"] = $_POST['id_cte'];
$_SESSION["id_stat"] = $_POST['id_stat'];
$_SESSION["memo_det"] = $_POST['memo_det'];
$_SESSION['swsavelog'] = $_POST['swsavelog'];

$cDb_Nam = $_SESSION["database"];
$cSuc_id = $_SESSION["suc_id"];
$cOp__id = $_SESSION["op__id"];
$cCod_Ct = $_SESSION["id_cte"];
$cId_Stat = $_SESSION["id_stat"];
$cpDetalle = $_SESSION['memo_det'];
$SaveLog = $_SESSION['swsavelog'];

/*
 * $cDb_Nam = '699_bayshoreaptos';
 * $cSuc_id = '2';
 * $cOp__id = '220000001';
 * $cCod_Ct= '8';
 * $cpDetalle= 'hola';
 * $cId_Stat = '3';
 * $SaveLog = 1;
 */

$hoynow = getdate();
$timeStamp = $hoynow["year"] . "-" . $hoynow["mon"] . "-" . $hoynow["mday"];
$timeStamp = date("Y-m-d H:i:s");
try {
    
    if ($SaveLog == '1') {
        logs2('', false);
        logs2('++++++++++++++++++++++++++++++++++++++++++++++apt_liberar.php+++++++++++++++++++++++++++++++++++++++++++++++++');
        logs2('database : ' . $cDb_Nam);
        logs2('Sucursal : ' . $cSuc_id);
        logs2('Op__id   : ' . $cOp__id);
        logs2('Cte_Id   : ' . $cCod_Ct);
        logs2('Detalle  : ' . $cpDetalle);
        logs2('Stat_id  : ' . $cId_Stat);
        logs2('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++');
        logs2('', false);
    }
    ;
    
    $resp1 = false;
    $cSql = '
        SELECT op.* 
        FROM ' . $cDb_Nam . '.operacion op 
        WHERE op.op_id         = "' . $cOp__id . '" 
        AND   op.op_id_cliente = "' . $cCod_Ct . '" 
        AND   op.op_tipo       = 3 
        AND   op.suc_id        = "' . $cSuc_id . '" ';
    $rec_apt = getRowAll($connection, $cSql, $recount, false);
    
    if ($SaveLog == '1') {
        logs2('', false);
        logs2('SQL : ' . $cSql);
        logs2('REGS: ' . $recount);
        logs2('', false);
        logs2('', false);
    }
    
    if ($recount > 0) {
        $resp1 = true;
        
        $DateOrig1 = $rec_apt['op_fecha'];
        $DateOrig2 = $rec_apt['op_fechav'];
        
        $cString = clean($cpDetalle) . ', ';
        $cString = $cString . 'Fecha de Apartado: ' . $DateOrig1 . ', ';
        $cString = $cString . 'Fecha de Vencimiento: ' . $DateOrig2 . ', ';
        $cString = $cString . 'Fecha de Cancelacion: ' . $timeStamp . ', ';
        $cString2 = utf8_encode($cString);
        
        Actualiza_Exist_Apdo($connection, $cDb_Nam, $cSuc_id, $cOp__id, $SaveLog);
        
        /* Quita los productos pendientes de los apartados. */
       $cSql_Up = '
            UPDATE ' . $cDb_Nam . '.operacion SET 
                op_observ       = CONCAT(op_observ ,"' . $cString2 . '")
            WHERE op_id         = "' . $cOp__id . '" 
            AND   op_id_cliente = "' . $cCod_Ct . '"
            AND   op_tipo       = "3"
            AND   suc_id        = "' . $cSuc_id . '"';
        $resp2 = update_Sql($connection, $cSql_Up);

		$cSql_Up = '
            UPDATE ' . $cDb_Nam . '.operacion SET 
                id_status       = "1", 
                op_aptdo_status = "' . $cId_Stat . '",
                op_aptdo_cancel = "' . $timeStamp . '",
                usermodify      = "1"
            WHERE op_id         = "' . $cOp__id . '" 
            AND   op_id_cliente = "' . $cCod_Ct . '"
            AND   op_tipo       = "3"
            AND   suc_id        = "' . $cSuc_id . '"';
        $resp2 = update_Sql($connection, $cSql_Up);
        
 
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 2: ' . $cSql_Up);
            logs2('RESP2: ' . ($resp2 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        
        /* Resguarda los valores de la cantidad original. */
        $cSql_Po = '
            UPDATE ' . $cDb_Nam . '.producto_op po 
            INNER JOIN ' . $cDb_Nam . '.operacion op ON po.po_op_id = op.op_id SET 
                po.pr_condiciones = po.po_cant 
            WHERE op.op_id         = "' . $cOp__id . '" 
            AND   op.op_id_cliente = "' . $cCod_Ct . '"
            AND   op.op_tipo       = "3"
            AND   op.suc_id        = "' . $cSuc_id . '"';
        $resp3 = update_Sql($connection, $cSql_Po);
        
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 3: ' . $cSql_Po);
            logs2('RESP3: ' . ($resp3 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        
        /* Quita los productos pendientes de los apartados. */
        $cSql_Po = '
            UPDATE ' . $cDb_Nam . '.producto_op po 
            INNER JOIN ' . $cDb_Nam . '.operacion op ON po.po_op_id = op.op_id SET 
        	   po.po_cant_pend = "0", 
        	   po.po_cant      = "0", 
                po.usermodify   = "1"  
        	WHERE op.op_id         = "' . $cOp__id . '"
        	AND   op.op_id_cliente = "' . $cCod_Ct . '"
            AND   op.op_tipo       = "3"
            AND   op.suc_id        = "' . $cSuc_id . '"';
        $resp4 = update_Sql($connection, $cSql_Po);
        
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 4: ' . $cSql_Po);
            logs2('RESP4: ' . ($resp4 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        
        $cSql_Del = '
            DELETE FROM ' . $cDb_Nam . '.entradas_salidas_desg
            WHERE op_id ="' . $cOp__id . '"
            AND suc_id  ="' . $cSuc_id . '"';
        $resp5 = update_Sql($connection, $cSql_Del);
        
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 5: ' . $cSql_Del);
            logs2('RESP5: ' . ($resp5 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        
        $cSql_Del = '
            DELETE FROM ' . $cDb_Nam . '.entradas_salidas_det_pago
            WHERE op_id ="' . $cOp__id . '"
            AND suc_id  ="' . $cSuc_id . '"';
        $resp6 = update_Sql($connection, $cSql_Del);
        
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 6: ' . $cSql_Del);
            logs2('RESP6: ' . ($resp6 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        
        $cSql_Del = '
            DELETE FROM ' . $cDb_Nam . '.operacion_det_pago
            WHERE op_id ="' . $cOp__id . '"
            AND suc_id ="' . $cSuc_id . '"';
        $resp7 = update_Sql($connection, $cSql_Del);
        
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 7: ' . $cSql_Del);
            logs2('RESP7: ' . ($resp7 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        $cSql_Del = '
            DELETE FROM ' . $cDb_Nam . '.operacion_det_pago2
            WHERE op_id ="' . $cOp__id . '"
            AND suc_id ="' . $cSuc_id . '"';
        $resp8 = update_Sql($connection, $cSql_Del);
        
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 8: ' . $cSql_Del);
            logs2('RESP8: ' . ($resp8 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        
        $cSql_Del = '
            DELETE FROM ' . $cDb_Nam . '.operacion_det_pago_dif
            WHERE op_id ="' . $cOp__id . '"';
        $resp9 = update_Sql($connection, $cSql_Del);
        
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 9: ' . $cSql_Del);
            logs2('RESP9: ' . ($resp9 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        
        $cSql_Del = '
            DELETE FROM ' . $cDb_Nam . '.operacion_det_pago_mm
            WHERE op_id ="' . $cOp__id . '"';
        $resp10 = update_Sql($connection, $cSql_Del);
        
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 10: ' . $cSql_Del);
            logs2('RESP10: ' . ($resp10 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        
        $cSql_Del = '
            DELETE FROM ' . $cDb_Nam . '.operacion_det_pago_mm2
            WHERE op_id ="' . $cOp__id . '"';
        $resp11 = update_Sql($connection, $cSql_Del);
        
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 11: ' . $cSql_Del);
            logs2('RESP11: ' . ($resp11 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        
        $var1 = $cSuc_id;
        $var2 = '%';
        
        $cSql = 'CALL ' . $cDb_Nam . '.prod_existencia_check("' . $var1 . '","' . $var2 . '")';
        $resp12 = update_Sql($connection, $cSql);
        
        if ($SaveLog == '1') {
            logs2('', false);
            logs2('SQL 12: ' . $cSql);
            logs2('RESP12: ' . ($resp12 ? 'true' : 'false'));
            logs2('', false);
            logs2('', false);
        }
        ;
        
        $resp13 = Actualiza_Exist_Online($connection, $cDb_Nam, $cSuc_id, '3', $cOp__id, '-1', true, '', false, $SaveLog);
        
        $resp = 'true';
        $msg = array(
            "success" => "true",
            "detalle" => "OK"
        );
    } else {
        $resp = 'false';
        $msg = array(
            "success" => "false",
            "detalle" => "NO SE ENCONTRARON DATOS DEL APARTADO #[" . $cOp__id . "]"
        );
    }
} catch (Exception $e) {
    $resp = 'false';
    $msg = array(
        "success" => "false",
        "detalle" => $connection
    );
    echo "<br>" . $connection->error;
}
;

if ($SaveLog == '1') {
    logs2('', false);
    logs2('RESULT:', $resp);
    logs2('FIN+++++++++++++++++++++++++++++++++++++++++++apt_liberar.php+++++++++++++++++++++++++++++++++++++++++++++++++');
    logs2('', false);
}
;

$jsonData[] = $msg;

header('content-type: application/json');
echo json_encode($jsonData);

@mysqli_close($connection);
?>