<?php 
include 'config.php'; 
if(!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

$agency_id = $_SESSION['agency_id'];
$search = $_GET['search'] ?? '';

// 1. FETCH USAGE LIMITS
$usage = $conn->query("SELECT tickets_used, max_tickets FROM agencies WHERE id = $agency_id")->fetch_assoc();
$vouchers_left = $usage['max_tickets'] - $usage['tickets_used'];

// 2. HANDLE DELETE
if (isset($_GET['action']) && $_GET['action'] == 'delete') {
    $vid = (int)$_GET['id'];
    $check = $conn->query("SELECT id FROM ticket_vouchers WHERE id = $vid AND agency_id = $agency_id");
    if ($check->num_rows > 0) {
        $conn->query("DELETE FROM ticket_vouchers WHERE id = $vid");
        header("Location: ticket_vouchers.php?msg=deleted"); exit();
    }
}

// 3. FETCH TICKETS
$sql = "SELECT v.*, c.name as db_client_name FROM ticket_vouchers v LEFT JOIN clients c ON v.client_id = c.id WHERE v.agency_id = $agency_id";
if ($search) $sql .= " AND (c.name LIKE '%$search%' OR v.voucher_data LIKE '%$search%')";
$sql .= " ORDER BY v.id DESC";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ticket Vouchers | Travel SaaS</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #4e73df; --secondary: #1e293b; --bg: #f8f9fc; --sidebar-width: 260px; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg); display: flex; }
        
        /* Sidebar */
        .sidebar { width: var(--sidebar-width); background: var(--secondary); height: 100vh; position: fixed; color: #fff; padding: 20px 0; }
        .nav-link { display: flex; align-items: center; padding: 12px 15px; color: rgba(255,255,255,0.7); text-decoration: none; border-radius: 8px; margin: 5px 20px; transition: 0.3s; }
        .nav-link:hover, .active { background: rgba(255,255,255,0.1); color: #fff; }
        .nav-link i { width: 25px; }

        /* Main Content */
        .main-content { margin-left: var(--sidebar-width); width: calc(100% - var(--sidebar-width)); padding: 40px; }
        .card { background: #fff; padding: 25px; border-radius: 15px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); }
        .usage-tracker { background: #fff; padding: 15px 25px; border-radius: 12px; margin-bottom: 25px; display: flex; justify-content: space-between; align-items: center; border-left: 5px solid var(--primary); box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .usage-info h4 { margin: 0; color: #64748b; font-size: 11px; text-transform: uppercase; }
        .usage-info b { font-size: 18px; color: var(--secondary); }
        
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th { text-align: left; padding: 15px; background: #f8f9fc; color: #64748b; font-size: 11px; text-transform: uppercase; border-bottom: 1px solid #eee; }
        td { padding: 15px; border-bottom: 1px solid #f1f5f9; font-size: 14px; vertical-align: middle; }
        .btn-action { padding: 8px 12px; border-radius: 8px; text-decoration: none; font-size: 12px; font-weight: 600; display: inline-flex; align-items: center; gap: 5px; }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div style="padding: 0 25px 30px; font-weight: 600; font-size: 18px;"><i class="fas fa-plane-departure text-primary"></i> TRAVEL SAAS</div>
        <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        <a href="clients.php" class="nav-link"><i class="fas fa-users"></i> My Clients</a>
        <a href="queries.php" class="nav-link"><i class="fas fa-question-circle"></i> Enquiries</a>
        <a href="marketplace.php" class="nav-link"><i class="fas fa-shopping-cart"></i> B2B Marketplace</a>
        <a href="umrah_vouchers.php" class="nav-link"><i class="fas fa-kaaba"></i> Umrah Vouchers</a>
        <a href="ticket_vouchers.php" class="nav-link active"><i class="fas fa-ticket-alt"></i> Ticket Vouchers</a>
        <a href="posters.php" class="nav-link"><i class="fas fa-image"></i> Poster Maker</a>
        <a href="ledger.php" class="nav-link"><i class="fas fa-wallet"></i> My Accounts</a>
        <?php if($_SESSION['user_role'] == 'AgencyOwner'): ?>
            <a href="staff.php" class="nav-link"><i class="fas fa-user-tie"></i> Manage Staff</a>
            <a href="agency_profile.php" class="nav-link"><i class="fas fa-cog"></i> Settings</a>
        <?php endif; ?>
        <div style="position: absolute; bottom: 20px; width: 100%;">
            <a href="logout.php" class="nav-link" style="color: #ff7675;"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>

    <div class="main-content">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:25px;">
            <h1 style="font-weight: 700;">Ticket Vouchers</h1>
            <a href="create_ticket_voucher.php" class="btn-action" style="background:var(--primary); color:white; padding:12px 20px; font-size:14px;">+ Create New</a>
        </div>

        <div class="usage-tracker">
            <div class="usage-info">
                <h4>Monthly Plan Usage</h4>
                <b><?php echo $usage['tickets_used']; ?> / <?php echo $usage['max_tickets']; ?></b> <small>Quotes Created</small>
            </div>
            <div style="text-align:right;">
                <span style="font-size: 14px; color: <?php echo ($vouchers_left <= 5 ? 'red' : 'var(--primary)'); ?>; font-weight: 700;">
                    <i class="fas fa-ticket-alt"></i> <?php echo ($vouchers_left < 0 ? 0 : $vouchers_left); ?> Tickets Left
                </span>
            </div>
        </div>

        <div class="card">
            <form method="GET" style="display:flex; gap:10px; margin-bottom: 20px;">
                <input type="text" name="search" placeholder="Search client name..." value="<?php echo htmlspecialchars($search); ?>" style="flex:1; padding:12px; border:1px solid #e2e8f0; border-radius:10px; outline:none;">
                <button type="submit" class="btn-action" style="background:var(--secondary); color:white; padding:0 25px;">Filter</button>
            </form>

            <table>
                <thead>
                    <tr><th>ID</th><th>Client</th><th>Route</th><th>Airline</th><th>Price</th><th style="text-align:right;">Action</th></tr>
                </thead>
                <tbody>
                    <?php while($row = $result->fetch_assoc()): 
                        $data = json_decode($row['voucher_data'], true);
                        $client_name = $data['client_display_name'] ?? $row['db_client_name'] ?? 'Guest';
                        $opt = $data['flight_options'][0] ?? null;
                        $seg = $opt['segments'][0] ?? null;
                    ?>
                    <tr>
                        <td><small style="color:#94a3b8;">#TK-<?php echo str_pad($row['id'], 4, '0', STR_PAD_LEFT); ?></small></td>
                        <td><b><?php echo $client_name; ?></b></td>
                        <td><b><?php echo $seg ? $seg['from']." → ".$seg['to'] : 'N/A'; ?></b></td>
                        <td><?php echo $seg['airline'] ?? 'N/A'; ?></td>
                        <td style="color:var(--primary); font-weight:700;">PKR <?php echo number_format((float)($opt['price'] ?? 0)); ?></td>
                        <td style="text-align:right;">
                            <a href="view_ticket_voucher.php?id=<?php echo $row['id']; ?>" class="btn-action" style="background:#e0f2fe; color:#0369a1;"><i class="fas fa-eye"></i> View</a>
                            <a href="?action=delete&id=<?php echo $row['id']; ?>" class="btn-action" style="background:#fee2e2; color:#b91c1c;" onclick="return confirm('Delete permanently?')"><i class="fas fa-trash"></i></a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>