<?php
include_once ("conn.php");
include_once ("funciones.php");
include_once ("utiles.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['suc_id'] = $_POST['suc_id'];
$_SESSION['datab_name'] = $_POST['datab_name'];
$_SESSION['num_accion'] = $_POST['num_accion'];
$_SESSION["num_contra"] = $_POST['num_contra'];
$_SESSION['swsavelog'] = $_POST['swsavelog'];

$cNum_SucSel = $_SESSION["suc_id"];
$cDatab_name = $_SESSION['datab_name'];
$cNum_accion = $_SESSION['num_accion'];
$cNum_contra = $_SESSION['num_contra'];
$SaveLog = $_SESSION['swsavelog'];

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

$where_1 = ($cNum_contra!='' ? ' AND cn.num_contr  ="'.$cNum_contra.'"' : ' ');
$where_2 = ($cNum_accion!='' ? ' AND cn.num_jugado ="'.$cNum_accion.'"' : ' ');

$cSql ='
SELECT 
	cr.num_accion 		 AS Num_Acc, 
	COUNT(cn.num_jugado) AS vendido,
	cr.limit_accion		 AS Restric,
	CASE
    WHEN cr.limit_accion=0 THEN 99
    WHEN cr.limit_accion>0 THEN if( (cr.limit_accion - COUNT(cn.num_jugado))<0,0, (cr.limit_accion - COUNT(cn.num_jugado))) 
	END  AS 	Disp
FROM '.$cDatab_name.'.club_accion_restric cr 
LEFT JOIN '.$cDatab_name.'.club_contratos cn ON (cn.num_jugado = cr.num_accion)
WHERE (cn.tipo_status=1 or cn.tipo_status=10) AND (cn.monto_pag>0) 
'.$where_1.'
'.$where_2.'
AND cr.suc_id    ="'.$cNum_SucSel.'"
GROUP BY cn.num_jugado
ORDER BY cn.num_jugado';

$Json = getRowAll($connection, $cSql, $recount, true);
    echo $Json;
    
if ($recount > 0) {
	$resp1 = true;
} 
else{
	$resp1 = false;
}	  

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

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

@mysqli_close($connection);
?>
