<?php 
include 'config.php'; 
if(!isset($_SESSION['user_role']) || $_SESSION['user_role'] != 'SuperAdmin') {
    header("Location: dashboard.php"); exit();
}

$ticket_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// 1. Fetch Deal Info (JOIN with airlines to fix the "airline" key warning)
$deal_query = $conn->query("SELECT g.*, a.name as airline_name, a.logo_path 
                            FROM group_tickets g 
                            JOIN airlines a ON g.airline_id = a.id 
                            WHERE g.id = $ticket_id");

if($deal_query->num_rows == 0) die("Group Deal not found.");
$deal = $deal_query->fetch_assoc();

// 2. Handle Approval/Rejection Logic
if(isset($_GET['action'])) {
    $req_id = (int)$_GET['req_id'];
    $action = $_GET['action']; // Approved or Rejected
    $qty = (int)$_GET['qty'];

    if($action == 'Approved') {
        if($deal['available_seats'] >= $qty) {
            $conn->query("UPDATE group_requests SET status = 'Approved' WHERE id = $req_id");
            $conn->query("UPDATE group_tickets SET available_seats = available_seats - $qty WHERE id = $ticket_id");
            header("Location: view_group_requests.php?id=$ticket_id&msg=approved");
            exit();
        } else {
            header("Location: view_group_requests.php?id=$ticket_id&error=not_enough_seats");
            exit();
        }
    } elseif($action == 'Rejected') {
        $conn->query("UPDATE group_requests SET status = 'Rejected' WHERE id = $req_id");
        header("Location: view_group_requests.php?id=$ticket_id&msg=rejected");
        exit();
    }
}

// 3. Fetch Requests (SaaS FEATURE: Auto-hide Rejected requests older than 24 hours)
$req_sql = "SELECT r.*, a.agency_name, a.phone as agency_phone, a.owner_name 
            FROM group_requests r 
            JOIN agencies a ON r.agency_id = a.id 
            WHERE r.ticket_id = $ticket_id 
            AND (r.status != 'Rejected' OR (r.status = 'Rejected' AND r.created_at > NOW() - INTERVAL 1 DAY))
            ORDER BY r.id DESC";
$requests = $conn->query($req_sql);

// 4. Calculate Stats for the top row
$total_req_count = $requests->num_rows;
$seats_requested = $conn->query("SELECT SUM(requested_seats) as total FROM group_requests WHERE ticket_id = $ticket_id AND status = 'Approved'")->fetch_assoc()['total'] ?? 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Booking Requests | Super Admin</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; --success: #1cc88a; --danger: #e74a3b; --secondary: #1e293b; --bg: #f8f9fc; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg); padding: 40px; }
        .container { max-width: 1100px; margin: auto; }
        
        /* Header Card */
        .deal-header { background: white; padding: 30px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); display: flex; align-items: center; justify-content: space-between; margin-bottom: 30px; border-left: 8px solid var(--primary); }
        .deal-header img { height: 60px; object-fit: contain; }
        
        /* Summary Stats */
        .stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 30px; }
        .stat-box { background: white; padding: 20px; border-radius: 12px; text-align: center; box-shadow: 0 2px 10px rgba(0,0,0,0.02); }
        .stat-box h2 { color: var(--secondary); font-size: 24px; }
        .stat-box small { color: #64748b; text-transform: uppercase; font-size: 11px; letter-spacing: 1px; }

        /* Table Styling */
        .card { background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        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: 2px solid #edf2f7; }
        td { padding: 18px 15px; border-bottom: 1px solid #f1f5f9; font-size: 14px; }
        
        .badge { padding: 5px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; text-transform: uppercase; }
        .badge-pending { background: #fef3c7; color: #92400e; }
        .badge-approved { background: #dcfce7; color: #166534; }
        .badge-rejected { background: #fee2e2; color: #991b1b; }
        
        .btn { padding: 8px 15px; border-radius: 8px; text-decoration: none; font-size: 12px; font-weight: 600; color: white; border: none; cursor: pointer; transition: 0.3s; }
        .btn-approve { background: var(--success); }
        .btn-approve:hover { background: #169b6b; box-shadow: 0 4px 10px rgba(28, 200, 138, 0.3); }
        .btn-reject { background: var(--danger); }
        .btn-reject:hover { background: #be281a; box-shadow: 0 4px 10px rgba(231, 74, 59, 0.3); }
        
        .timer-info { font-size: 10px; color: #94a3b8; display: block; margin-top: 4px; }
    </style>
</head>
<body>

<div class="container">
    <a href="admin_group_tickets.php" style="text-decoration:none; color:var(--primary); font-weight:600; margin-bottom:20px; display:inline-block;"><i class="fas fa-arrow-left"></i> Back to Inventory</a>

    <div class="deal-header">
        <div>
            <img src="<?php echo $deal['logo_path']; ?>" alt="Airline">
            <h1 style="margin-top:10px;"><?php echo $deal['route']; ?></h1>
            <p style="color:#64748b; font-size:14px;">
                <i class="fas fa-calendar"></i> <?php echo date('d M Y', strtotime($deal['travel_date'])); ?> 
                | <b><?php echo $deal['trip_type']; ?></b>
            </p>
        </div>
        <div style="text-align: right;">
            <small style="color:#64748b;">Current Price</small>
            <h2 style="color:var(--success);">PKR <?php echo number_format($deal['price_per_seat']); ?></h2>
            <span style="background: #f1f5f9; padding: 5px 10px; border-radius: 5px; font-size: 12px;">Dep Baggage: <?php echo $deal['dep_baggage']; ?></span>
        </div>
    </div>

    <div class="stats-grid">
        <div class="stat-box">
            <small>Active Requests</small>
            <h2><?php echo $total_req_count; ?></h2>
        </div>
        <div class="stat-box">
            <small>Total Approved Seats</small>
            <h2 style="color:var(--primary);"><?php echo $seats_requested; ?></h2>
        </div>
        <div class="stat-box">
            <small>Available Inventory</small>
            <h2 style="color:<?php echo ($deal['available_seats'] < 5 ? 'var(--danger)' : 'var(--success)'); ?>;">
                <?php echo $deal['available_seats']; ?> / <?php echo $deal['total_seats']; ?>
            </h2>
        </div>
    </div>

    <div class="card">
        <h3><i class="fas fa-list-ul"></i> Agency Request Queue</h3>
        <table>
            <thead>
                <tr>
                    <th>Request Time</th>
                    <th>Agency Details</th>
                    <th>Seats</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while($row = $requests->fetch_assoc()): 
                    $status_class = 'badge-pending';
                    if($row['status'] == 'Approved') $status_class = 'badge-approved';
                    if($row['status'] == 'Rejected') $status_class = 'badge-rejected';
                ?>
                <tr>
                    <td>
                        <b><?php echo date('h:i A', strtotime($row['created_at'])); ?></b><br>
                        <small style="color:#94a3b8;"><?php echo date('d M Y', strtotime($row['created_at'])); ?></small>
                    </td>
                    <td>
                        <b><?php echo $row['agency_name']; ?></b><br>
                        <small><i class="fas fa-phone"></i> <?php echo $row['agency_phone']; ?></small>
                    </td>
                    <td>
                        <b style="font-size: 16px; color: var(--secondary);"><?php echo $row['requested_seats']; ?></b>
                    </td>
                    <td>
                        <span class="badge <?php echo $status_class; ?>"><?php echo $row['status']; ?></span>
                        <?php if($row['status'] == 'Rejected'): ?>
                            <span class="timer-info"><i class="fas fa-clock"></i> Clears in 24h</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if($row['status'] == 'Pending'): ?>
                            <a href="?id=<?php echo $ticket_id; ?>&req_id=<?php echo $row['id']; ?>&qty=<?php echo $row['requested_seats']; ?>&action=Approved" class="btn btn-approve" onclick="return confirm('Confirm seat booking?')">Approve</a>
                            <a href="?id=<?php echo $ticket_id; ?>&req_id=<?php echo $row['id']; ?>&qty=0&action=Rejected" class="btn btn-reject" onclick="return confirm('Reject this request?')">Reject</a>
                        <?php else: ?>
                            <span style="color:#cbd5e1; font-style: italic; font-size: 12px;">No actions</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endwhile; ?>
                <?php if($requests->num_rows == 0) echo "<tr><td colspan='5' style='text-align:center; padding:50px; color:#94a3b8;'><i class='fas fa-inbox' style='font-size:30px;'></i><br>No recent requests found for this deal.</td></tr>"; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>