<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';

// --- Page-Specific Logic Starts Here ---

// INITIAL SETUP & PAGINATION
$records_per_page = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

// BUILD DYNAMIC WHERE CLAUSE FOR FILTERING & SEARCHING
$where_clauses = [];
$params = [];
$types = '';

// Search term
$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    $where_clauses[] = "(fb.booking_ref LIKE ? OR u.full_name LIKE ? OR orig.name LIKE ? OR dest.name LIKE ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $like_term, $like_term, $like_term);
    $types .= 'ssss';
}

// Filter by booking status
$status_filter = $_GET['status'] ?? '';
if (!empty($status_filter)) {
    $where_clauses[] = "fb.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

// Filter by payment status
$payment_filter = $_GET['payment_status'] ?? '';
if (!empty($payment_filter)) {
    $where_clauses[] = "fb.payment_status = ?";
    $params[] = $payment_filter;
    $types .= 's';
}

$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(' AND ', $where_clauses) : '';

// DATABASE QUERIES
$base_query = "FROM flight_bookings fb
               JOIN users u ON fb.user_id = u.id
               LEFT JOIN airports orig ON fb.origin_airport_id = orig.id
               LEFT JOIN airports dest ON fb.destination_airport_id = dest.id
               $where_sql";

$count_sql = "SELECT COUNT(fb.id) as total $base_query";
$stmt_count = $conn->prepare($count_sql);
if (count($params) > 0) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$stmt_count->close();

// Fetch bookings for display
$fetch_sql = "SELECT fb.*, u.full_name,
              orig.name as origin_city, orig.airport_code as origin_code,
              dest.name as dest_city, dest.airport_code as dest_code
              $base_query
              ORDER BY fb.created_at DESC
              LIMIT ? OFFSET ?";

$params[] = $records_per_page;
$params[] = $offset;
$types .= 'ii';

$stmt_fetch = $conn->prepare($fetch_sql);
if (count($params) > 0) { $stmt_fetch->bind_param($types, ...$params); }
$stmt_fetch->execute();
$bookings_result = $stmt_fetch->get_result();


// 3. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>


<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-filter me-1"></i> Filter & Search Flights</div>
    <div class="card-body">
        <form action="flight-bookings.php" method="GET" class="row g-3 align-items-center">
            <div class="col-md-5">
                <input type="text" name="search" class="form-control" placeholder="Search by Ref #, Customer, or City..." value="<?php echo htmlspecialchars($search_term); ?>">
            </div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <option value="">All Booking Statuses</option>
                    <option value="Pending" <?php if($status_filter == 'Pending') echo 'selected'; ?>>Pending</option>
                    <option value="Quoted" <?php if($status_filter == 'Quoted') echo 'selected'; ?>>Quoted</option>
                    <option value="Confirmed" <?php if($status_filter == 'Confirmed') echo 'selected'; ?>>Confirmed</option>
                    <option value="Cancelled" <?php if($status_filter == 'Cancelled') echo 'selected'; ?>>Cancelled</option>
                </select>
            </div>
            <div class="col-md-2">
                 <select name="payment_status" class="form-select">
                    <option value="">All Payment Statuses</option>
                    <option value="Paid" <?php if($payment_filter == 'Paid') echo 'selected'; ?>>Paid</option>
                    <option value="Unpaid" <?php if($payment_filter == 'Unpaid') echo 'selected'; ?>>Unpaid</option>
                </select>
            </div>
            <div class="col-md-2 d-grid d-md-flex gap-2">
                <button type="submit" class="btn btn-primary flex-grow-1">Filter</button>
                <a href="flight-bookings.php" class="btn btn-secondary flex-grow-1">Clear</a>
            </div>
        </form>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-striped table-hover">
        <thead class="table-dark align-middle">
            <tr>
                <th>Reference #</th>
                <th>Customer</th>
                <th>Route</th>
                <th>Departure</th>
                <th>Payment</th>
                <th>Status</th>
                <th class="text-end">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($bookings_result->num_rows > 0): ?>
                <?php while ($booking = $bookings_result->fetch_assoc()): ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($booking['booking_ref']); ?></strong></td>
                        <td><?php echo htmlspecialchars($booking['full_name']); ?></td>
                        <td>
                            <div class="fw-bold"><?php echo htmlspecialchars($booking['origin_city'] . ' (' . $booking['origin_code'] . ')'); ?></div>
                            <div class="text-muted"><i class="bi bi-arrow-right"></i> <?php echo htmlspecialchars($booking['dest_city'] . ' (' . $booking['dest_code'] . ')'); ?></div>
                        </td>
                        <td><?php echo date('M d, Y', strtotime($booking['departure_date'])); ?></td>
                        <td>
                            <span class="badge bg-<?php echo ($booking['payment_status'] == 'Paid') ? 'success' : 'warning'; ?>"><?php echo htmlspecialchars($booking['payment_status']); ?></span>
                        </td>
                        <td>
                             <?php
                                $status_badge = ['Pending' => 'secondary', 'Quoted' => 'info', 'Confirmed' => 'primary', 'Cancelled' => 'danger'];
                            ?>
                            <span class="badge bg-<?php echo $status_badge[$booking['status']] ?? 'light'; ?>"><?php echo htmlspecialchars($booking['status']); ?></span>
                        </td>
                        <td class="text-end">
                            <a href="edit-boarding-pass.php?type=flight&booking_ref=<?php echo $booking['booking_ref']; ?>" class="btn btn-sm btn-success" title="Edit Boarding Pass"><i class="bi bi-ticket-perforated-fill"></i></a>
                            <button type="button" class="btn btn-sm btn-warning" title="Update Status"><i class="bi bi-pencil-fill"></i></button>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="7" class="text-center p-4">No flight bookings found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if($total_pages > 1): ?>
<nav><ul class="pagination justify-content-center mt-4">
    <?php $query_params = $_GET; for ($i = 1; $i <= $total_pages; $i++): $query_params['page'] = $i; ?>
        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query($query_params); ?>"><?php echo $i; ?></a></li>
    <?php endfor; ?>
</ul></nav>
<?php endif; ?>

<?php include 'admin-footer.php'; ?>
