<?php
include 'conn.php';
include 'utiles.php';
date_default_timezone_set("America/Panama");
session_start();
error_reporting(E_ALL);

$_SESSION['database'] = $_POST['database'];
$_SESSION['c_id'] = $_POST['c_id'];
$_SESSION['op_id'] = $_POST['op_id'];
$_SESSION['op_tipo'] = $_POST['op_tipo'];
$_SESSION['puntos'] = $_POST['puntos'];
$_SESSION['acum'] = $_POST['acum'];
$_SESSION['show_disp'] = $_POST['show_disp'];

$cDb_Nam = $_SESSION["database"];
$cCte_id = $_SESSION["c_id"];
$cOp__id = $_SESSION["op_id"];
$cOp_Tip = $_SESSION["op_tipo"];
$cPuntos = $_SESSION["puntos"];
$cAcumul = $_SESSION["acum"];
$cShowdi = $_SESSION['show_disp'];

echo $cPuntos;


$hoynow = getdate();
# -----*INSERTA EL REGISTRO DEL CLIENTE, SI NO EXISTE*----#
$Sql_Cmd = "INSERT IGNORE INTO $cDb_Nam.puntos_clientes (p_cod_cte, p_acumulados, p_utilizados, p_disponibles, p_redimidos) VALUES ('$cCte_id',0,0,0,0,0)";
$connection->query($Sql_Cmd);

$Sql_Cmd = "INSERT IGNORE INTO  $cDb_Nam.puntos_detalle (c_id, op_id, op_tipo, puntos, acum, syncprocesing, usermodify, useroption) VALUES ('$cCte_id', $cOp__id, $cOp_Tip, $cPuntos, $cAcumul, 0, 0, 0)";
echo $Sql_Cmd;
$InsPtosOk = $connection->query($Sql_Cmd);

$Sql_Cmd = "SELECT SUM(puntos) AS Tot_Ptos FROM $cDb_Nam.puntos_detalle WHERE (acum=1) and (c_id='$cCte_id') GROUP BY c_id,acum";
$records = 0;
$result = getRow($connection, $Sql_Cmd, $records, false);
if (($result['Tot_Ptos'] != '') && ($result['Tot_Ptos'] != 'null') && ($result['Tot_Ptos'] != 'NULL')) {
    $Ptos_Acu = (int) ($result['Tot_Ptos']);
} else {
    $Ptos_Acu = 0;
}

$Sql_Cmd = "SELECT SUM(puntos) AS Tot_Ptos FROM $cDb_Nam.puntos_detalle WHERE (acum=0) and (c_id='$cCte_id') GROUP BY c_id,acum";
$records = 0;
$result = getRow($connection, $Sql_Cmd, $records, false);
if (($result['Tot_Ptos'] != '') && ($result['Tot_Ptos'] != 'null') && ($result['Tot_Ptos'] != 'NULL')) {
    $Ptos_Usa = (int) ($result['Tot_Ptos']);
} else {
    $Ptos_Usa = 0;
}

$Ptos_Dis = ($Ptos_Acu - $Ptos_Usa);

$Sql_Cmd = "UPDATE $cDb_Nam.puntos_clientes SET p_acumulados=$Ptos_Acu, p_utilizados=$Ptos_Usa, p_disponibles=$Ptos_Dis WHERE (p_cod_cte='$cCte_id'); ";
$connection->query($Sql_Cmd);

$Sql_Cmd = "CALL $cDb_Nam.puntos_recalcula('$cCte_id')";
$connection->query($Sql_Cmd);

if ($InsPtosOk == true) {
    if ($cShowdi == 1) {
        $JsonResp->success = "true";
        $JsonResp->disponible = $Ptos_Dis;
        $JsonResp->detalle = "ok";
    } else {
        $JsonResp->success = "true";
        $JsonResp->disponible = -999;
        $JsonResp->detalle = "ok";
    }
} else {
    $JsonResp->success = "false";
    $JsonResp->disponible = -999;
    $JsonResp->detalle = $connection;
}
$jsonData = json_encode($JsonResp);

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

@mysqli_close($connection);
#JOHNN GUTIERREZ
#ULTMA MODIFICASION 2021-07-29
#ULTMA MODIFICASION 2021-08-02
?>