<?php 
$page_title = 'Search Flights';
require_once 'includes/header.php'; 

// --- Get search parameters from URL ---
$origin_id = filter_input(INPUT_GET, 'origin_id', FILTER_VALIDATE_INT);
$destination_id = filter_input(INPUT_GET, 'destination_id', FILTER_VALIDATE_INT);

// --- Get filter parameters from URL ---
$filter_airlines = $_GET['airlines'] ?? [];
$max_price = filter_input(INPUT_GET, 'max_price', FILTER_VALIDATE_INT);

// --- Build and execute the search query ---
$flights = [];
$available_airlines = [];
if ($origin_id && $destination_id) {
    // First, get available airlines for the filter UI for this route
    $stmt_airlines = $conn->prepare("SELECT DISTINCT airline_name FROM flight_routes WHERE origin_airport_id = ? AND destination_airport_id = ? ORDER BY airline_name ASC");
    $stmt_airlines->bind_param("ii", $origin_id, $destination_id);
    $stmt_airlines->execute();
    $available_airlines = $stmt_airlines->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_airlines->close();

    // Build the dynamic WHERE clause for the main query
    $where_clauses = ["fr.origin_airport_id = ?", "fr.destination_airport_id = ?"];
    $params = [$origin_id, $destination_id];
    $types = 'ii';

    if (!empty($filter_airlines) && is_array($filter_airlines)) {
        $placeholders = implode(',', array_fill(0, count($filter_airlines), '?'));
        $where_clauses[] = "fr.airline_name IN ($placeholders)";
        foreach ($filter_airlines as $airline) {
            $params[] = $airline;
            $types .= 's';
        }
    }
    if ($max_price > 0) {
        $where_clauses[] = "fr.price <= ?";
        $params[] = $max_price;
        $types .= 'd';
    }
    $where_sql = "WHERE " . implode(' AND ', $where_clauses);

    // Execute the main query
    $stmt = $conn->prepare("
        SELECT fr.*, orig.airport_code as origin_code, dest.airport_code as destination_code
        FROM flight_routes fr
        JOIN airports orig ON fr.origin_airport_id = orig.id
        JOIN airports dest ON fr.destination_airport_id = dest.id
        $where_sql
        ORDER BY fr.price ASC
    ");
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $flights = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}
?>

<div class="container my-5">
    <div class="row">
        <div class="col-lg-3">
            <form method="GET">
                <input type="hidden" name="origin_id" value="<?php echo htmlspecialchars($origin_id); ?>">
                <input type="hidden" name="destination_id" value="<?php echo htmlspecialchars($destination_id); ?>">

                <div class="card shadow-sm border-0">
                    <div class="card-header bg-light border-0"><h5 class="mb-0"><i class="bi bi-filter me-2"></i>Filter Results</h5></div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Max Price</label>
                            <input type="range" class="form-range" name="max_price" min="1000" max="10000" step="500" value="<?php echo htmlspecialchars($max_price ?? '10000'); ?>" oninput="this.nextElementSibling.value = this.value">
                            <output><?php echo htmlspecialchars($max_price ?? '10000'); ?></output>
                        </div>
                        <hr>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Airlines</label>
                            <?php if (empty($available_airlines)): ?>
                                <small class="text-muted">No airlines available for this route.</small>
                            <?php else: ?>
                                <?php foreach ($available_airlines as $airline): ?>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="airlines[]" value="<?php echo htmlspecialchars($airline['airline_name']); ?>" id="airline-<?php echo htmlspecialchars($airline['airline_name']); ?>" <?php if (in_array($airline['airline_name'], $filter_airlines)) echo 'checked'; ?>>
                                        <label class="form-check-label" for="airline-<?php echo htmlspecialchars($airline['airline_name']); ?>"><?php echo htmlspecialchars($airline['airline_name']); ?></label>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="card-footer bg-light border-0">
                        <button type="submit" class="btn btn-primary w-100">Apply Filters</button>
                    </div>
                </div>
            </form>
        </div>

        <div class="col-lg-9">
            <h2 class="mb-4">Available Flights</h2>
            <?php if (empty($flights)): ?>
                <div class="card card-body text-center"><p class="mb-0">No flights found matching your criteria. Try adjusting your filters.</p></div>
            <?php else: ?>
                <?php foreach ($flights as $flight): ?>
                <div class="card shadow-sm border-0 mb-3">
                    <div class="card-body"><div class="row align-items-center"><div class="col-md-2 text-center"><img src="<?php echo htmlspecialchars($flight['airline_logo_url']); ?>" alt="<?php echo htmlspecialchars($flight['airline_name']); ?>" style="max-height: 40px;"></div><div class="col-md-7"><div class="d-flex justify-content-between align-items-center"><div><strong class="fs-5"><?php echo date('h:i A', strtotime($flight['departure_time'])); ?></strong><div class="text-muted"><?php echo htmlspecialchars($flight['origin_code']); ?></div></div><div class="text-center text-muted small"><?php echo floor($flight['duration_minutes'] / 60); ?>h <?php echo $flight['duration_minutes'] % 60; ?>m<br><hr class="my-1"><span class="badge bg-success">Direct</span></div><div><strong class="fs-5"><?php echo date('h:i A', strtotime($flight['arrival_time'])); ?></strong><div class="text-muted"><?php echo htmlspecialchars($flight['destination_code']); ?></div></div></div></div><div class="col-md-3 text-center text-md-end mt-3 mt-md-0"><h4 class="fw-bold mb-1 text-primary"><?php echo format_price($flight['price']); ?></h4><div class="d-grid"><a href="#" class="btn btn-primary">Select Flight</a></div></div></div></div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php 
require_once 'includes/footer.php'; 
?>
