<?php
include 'admin-header.php';

$message = '';
// --- ACTION HANDLING (QUOTE/CANCEL/CONFIRM) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $booking_id = intval($_POST['booking_id']);

    // Handle "Save Quote" action
    if (isset($_POST['save_quote'])) {
        $total_price = floatval($_POST['total_price']);
        $admin_notes = trim($_POST['admin_notes']);
        if ($total_price > 0) {
            $stmt = $conn->prepare("UPDATE flight_bookings SET status = 'Quoted', total_price = ?, admin_notes = ? WHERE id = ?");
            $stmt->bind_param("dsi", $total_price, $admin_notes, $booking_id);
            $stmt->execute();
            $message = '<div class="alert alert-success">Quote sent for booking #'.$booking_id.'. The user can now proceed to payment.</div>';
        }
    }
    // Handle "Cancel Booking" action
    elseif (isset($_POST['cancel_booking'])) {
        $stmt = $conn->prepare("UPDATE flight_bookings SET status = 'Cancelled' WHERE id = ?");
        $stmt->bind_param("i", $booking_id);
        $stmt->execute();
        $message = '<div class="alert alert-warning">Booking #'.$booking_id.' has been cancelled.</div>';
    }
}

// --- DATA FETCHING ---
$current_status = $_GET['status'] ?? 'pending';
$search_term = $_GET['search'] ?? '';

// Build the WHERE clause based on status tab
$where_clause = "";
switch ($current_status) {
    case 'quoted': $where_clause = "WHERE fb.status = 'Quoted'"; break;
    case 'confirmed': $where_clause = "WHERE fb.status = 'Confirmed'"; break;
    case 'cancelled': $where_clause = "WHERE fb.status = 'Cancelled'"; break;
    default: $where_clause = "WHERE fb.status = 'Pending'"; break;
}

// Add search functionality
$search_params = [];
$param_types = '';
if (!empty($search_term)) {
    $where_clause .= " AND (u.full_name LIKE ? OR orig.city LIKE ? OR dest.city LIKE ? OR fb.id = ?)";
    $like_term = "%" . $search_term . "%";
    $search_params = [$like_term, $like_term, $like_term, $search_term];
    $param_types = 'sssi';
}

// Main SQL query
$sql = "SELECT fb.*, u.full_name, u.email, 
        orig.city as origin_city, orig.airport_code as origin_code, 
        dest.city as dest_city, dest.airport_code as dest_code 
        FROM flight_bookings fb 
        JOIN users u ON fb.user_id = u.id 
        JOIN airports orig ON fb.origin_id = orig.id 
        JOIN airports dest ON fb.destination_id = dest.id
        $where_clause 
        ORDER BY fb.created_at DESC";

$stmt = $conn->prepare($sql);
if (!empty($search_params)) {
    $stmt->bind_param($param_types, ...$search_params);
}
$stmt->execute();
$result = $stmt->get_result();

// Counts for badges
$pending_count = $conn->query("SELECT COUNT(*) as total FROM flight_bookings WHERE status = 'Pending'")->fetch_assoc()['total'];
$quoted_count = $conn->query("SELECT COUNT(*) as total FROM flight_bookings WHERE status = 'Quoted'")->fetch_assoc()['total'];
$confirmed_count = $conn->query("SELECT COUNT(*) as total FROM flight_bookings WHERE status = 'Confirmed'")->fetch_assoc()['total'];
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Flight Booking Requests</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
         <form method="GET" class="d-flex"><input type="hidden" name="status" value="<?php echo htmlspecialchars($current_status); ?>"><input class="form-control me-2" type="search" name="search" placeholder="Search..." value="<?php echo htmlspecialchars($search_term); ?>"><button class="btn btn-outline-success" type="submit">Search</button></form>
    </div>
</div>
<?php echo $message; ?>

<ul class="nav nav-tabs mb-3">
    <li class="nav-item"><a class="nav-link <?php echo $current_status == 'pending' ? 'active' : ''; ?>" href="?status=pending">Pending <span class="badge bg-danger"><?php echo $pending_count; ?></span></a></li>
    <li class="nav-item"><a class="nav-link <?php echo $current_status == 'quoted' ? 'active' : ''; ?>" href="?status=quoted">Quoted <span class="badge bg-warning text-dark"><?php echo $quoted_count; ?></span></a></li>
    <li class="nav-item"><a class="nav-link <?php echo $current_status == 'confirmed' ? 'active' : ''; ?>" href="?status=confirmed">Confirmed <span class="badge bg-success"><?php echo $confirmed_count; ?></span></a></li>
    <li class="nav-item"><a class="nav-link <?php echo $current_status == 'cancelled' ? 'active' : ''; ?>" href="?status=cancelled">Cancelled</a></li>
</ul>

<div class="table-responsive">
    <table class="table table-striped table-hover">
        <thead class="table-dark">
            <tr><th>Request ID</th><th>Customer</th><th>Itinerary</th><th>Passengers</th><th>Status</th><th>Action</th></tr>
        </thead>
        <tbody>
            <?php if ($result->num_rows > 0): while($booking = $result->fetch_assoc()): ?>
            <tr>
                <td><strong>#<?php echo $booking['id']; ?></strong><br><small class="text-muted"><?php echo date('M d, Y', strtotime($booking['created_at'])); ?></small></td>
                <td><strong><?php echo htmlspecialchars($booking['full_name']); ?></strong><br><small class="text-muted"><?php echo htmlspecialchars($booking['email']); ?></small></td>
                <td>
                    <strong><?php echo htmlspecialchars($booking['origin_code'] . ' → ' . $booking['dest_code']); ?></strong> (<?php echo htmlspecialchars($booking['trip_type']); ?>)<br>
                    <small>Depart: <?php echo date('M d, Y', strtotime($booking['departure_date'])); ?><?php if($booking['return_date']) echo ' | Return: ' . date('M d, Y', strtotime($booking['return_date'])); ?></small>
                </td>
                <td><?php echo $booking['num_adults'] + $booking['num_children'] + $booking['num_infants']; ?></td>
                <td>
                    <span class="badge bg-<?php echo $booking['status'] == 'Pending' ? 'danger' : 'info'; ?>"><?php echo $booking['status']; ?></span>
                    <?php if($booking['status'] == 'Quoted' || $booking['status'] == 'Confirmed'): ?>
                        <span class="badge bg-<?php echo $booking['payment_status'] == 'Paid' ? 'success' : 'secondary'; ?>"><?php echo $booking['payment_status']; ?></span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if($booking['status'] == 'Pending'): ?>
                        <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#quoteModal<?php echo $booking['id']; ?>">Provide Quote</button>
                    <?php elseif($booking['status'] == 'Quoted'): ?>
                        <button class="btn btn-sm btn-secondary" disabled>Awaiting Payment</button>
                    <?php else: ?>
                        <button class="btn btn-sm btn-light" disabled>No Action</button>
                    <?php endif; ?>
                </td>
            </tr>

            <div class="modal fade" id="quoteModal<?php echo $booking['id']; ?>" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <form method="POST">
                            <div class="modal-header">
                                <h5 class="modal-title">Provide Quote for Request #<?php echo $booking['id']; ?></h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" name="booking_id" value="<?php echo $booking['id']; ?>">
                                <div class="mb-3">
                                    <label class="form-label">Total Price (PHP)</label>
                                    <input type="number" name="total_price" class="form-control" step="0.01" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Flight Details & Itinerary</label>
                                    <textarea name="admin_notes" class="form-control" rows="6" placeholder="e.g., Airline: Cebu Pacific&#10;Flight: 5J 551&#10;MNL-CEB 08:00-09:30&#10;Return: 5J 552, CEB-MNL 18:00-19:30&#10;Baggage: 20kg Included"></textarea>
                                    <small class="text-muted">This information will be shown to the user.</small>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                <button type="submit" name="save_quote" class="btn btn-primary">Save Quote</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php endwhile; else: ?>
                <tr><td colspan="6" class="text-center">No flight requests found for this status.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

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