* Residui = ticket - (prenotazioni non cancellate e NON omaggio). * -------------------------------------------------------------------------- */ require_once __DIR__ . '/_bootstrap.php'; // Gate staff $roleId = (int) $user->role_id; if (!in_array($roleId, [1, 3], true)) { http_response_code(403); echo json_encode(['success' => false, 'message' => 'Forbidden']); exit; } $userId = isset($_GET['user_id']) ? (int) $_GET['user_id'] : 0; if ($userId <= 0) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Utente non valido', 'orders' => []]); exit; } try { $today = date('Y-m-d'); $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 = $db->prepare($sql); $stmt->execute([':uid' => $userId, ':today' => $today]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // conta le prenotazioni che consumano ticket (non cancellate, non omaggio) $usedStmt = $db->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 = (int) (($o['quantityclass'] !== null && $o['quantityclass'] !== '') ? $o['quantityclass'] : ($o['nticket'] ?? 0)); $usedStmt->execute([':oid' => $orderId]); $used = (int) ($usedStmt->fetch(PDO::FETCH_ASSOC)['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), ]; } echo json_encode(['success' => true, 'orders' => $orders], JSON_UNESCAPED_UNICODE); } catch (Throwable $ex) { error_log('api_teacher_user_orders error: ' . $ex->getMessage()); http_response_code(500); echo json_encode(['success' => false, 'message' => 'Errore ordini: ' . $ex->getMessage(), 'orders' => []]); }