Files

102 lines
3.2 KiB
PHP

<?php
// Bufferizziamo da subito così la risposta resta JSON puro
// (headscript.php può emettere HTML).
ob_start();
require_once('include/headscript.php');
/**
* get_user_orders.php
* --------------------------------------------------------------------------
* Restituisce gli ordini ATTIVI (non scaduti) di un utente, con il numero
* di ticket residui, per popolare il modale "Aggiungi partecipante"
* nell'adminpanel.
*
* Pattern: webapp (sessione + PDO), come searchemail.php.
* Metodo: GET o POST
* Param: userid (int)
*
* Residui = nticket - (prenotazioni non cancellate e NON omaggio)
* -> is_gift = 'N' esclude gli omaggi dal consumo.
* --------------------------------------------------------------------------
*/
$pdo = DBHandlerSelect::getInstance()->getConnection();
function jsonOut(array $payload): void
{
if (ob_get_length() !== false) {
ob_end_clean();
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($payload, JSON_UNESCAPED_UNICODE);
exit;
}
$userid = isset($_REQUEST['userid']) ? (int) $_REQUEST['userid'] : 0;
if ($userid <= 0) {
jsonOut(['error' => 'Utente non valido', 'orders' => []]);
}
try {
$today = date('Y-m-d');
// Ordini dell'utente NON scaduti
$sql = "SELECT ob.idorderbook, ob.idservice, ob.nticket, ob.quantityclass,
ob.expireon, ob.maxreschedule, ob.reprogrammed,
s.servicename
FROM orderbook ob
LEFT JOIN service s ON ob.idservice = s.idservice
WHERE ob.iduser = :uid
AND (ob.expireon IS NULL OR ob.expireon >= :today)
ORDER BY ob.idorderbook DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute([':uid' => $userid, ':today' => $today]);
$rows = $stmt->fetchAll();
// Prepared per contare le prenotazioni che consumano ticket
// (non cancellate e non omaggio)
$usedStmt = $pdo->prepare(
"SELECT COUNT(*) AS n
FROM bookingclass
WHERE idorder = :oid
AND status != 'cancelled'
AND is_gift = 'N'"
);
$orders = [];
foreach ($rows as $o) {
$orderId = (int) $o['idorderbook'];
// tickets totali: quantityclass se valorizzato, altrimenti nticket
$tickets = (int) (($o['quantityclass'] !== null && $o['quantityclass'] !== '')
? $o['quantityclass']
: ($o['nticket'] ?? 0));
$usedStmt->execute([':oid' => $orderId]);
$used = (int) ($usedStmt->fetch()['n'] ?? 0);
$remaining = $tickets - $used;
if ($remaining < 0) {
$remaining = 0;
}
$orders[] = [
'idorderbook' => $orderId,
'service_name' => (string) ($o['servicename'] ?? ''),
'tickets' => $tickets,
'used' => $used,
'remaining' => $remaining,
'expireon' => $o['expireon'] ?? null,
'maxreschedule' => (int) ($o['maxreschedule'] ?? 0),
'reprogrammed' => (int) ($o['reprogrammed'] ?? 0),
];
}
jsonOut(['orders' => $orders]);
} catch (Throwable $ex) {
error_log('get_user_orders error: ' . $ex->getMessage());
jsonOut(['error' => 'Errore durante il recupero degli ordini.', 'orders' => []]);
}