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

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

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

// --- Build and execute the search query ---
$ferries = [];
$available_companies = [];
if ($origin_port_id && $destination_port_id) {
    // First, get available companies for this route
    $stmt_companies = $conn->prepare("SELECT DISTINCT ferry_company FROM ferry_routes WHERE origin_port_id = ? AND destination_port_id = ? ORDER BY ferry_company ASC");
    $stmt_companies->bind_param("ii", $origin_port_id, $destination_port_id);
    $stmt_companies->execute();
    $available_companies = $stmt_companies->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_companies->close();

    // Build the dynamic WHERE clause
    $where_clauses = ["fr.origin_port_id = ?", "fr.destination_port_id = ?", "fr.is_published = 1"];
    $params = [$origin_port_id, $destination_port_id];
    $types = 'ii';

    if (!empty($filter_companies) && is_array($filter_companies)) {
        $placeholders = implode(',', array_fill(0, count($filter_companies), '?'));
        $where_clauses[] = "fr.ferry_company IN ($placeholders)";
        foreach ($filter_companies as $company) {
            $params[] = $company;
            $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.name as origin_name, dest.name as destination_name
        FROM ferry_routes fr
        JOIN ferry_ports orig ON fr.origin_port_id = orig.id
        JOIN ferry_ports dest ON fr.destination_port_id = dest.id
        $where_sql
        ORDER BY fr.price ASC
    ");
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $ferries = $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_port_id" value="<?php echo htmlspecialchars($origin_port_id); ?>">
                <input type="hidden" name="destination_port_id" value="<?php echo htmlspecialchars($destination_port_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="500" max="5000" step="100" value="<?php echo htmlspecialchars($max_price ?? '5000'); ?>" oninput="this.nextElementSibling.value = this.value">
                            <output><?php echo htmlspecialchars($max_price ?? '5000'); ?></output>
                        </div>
                        <hr>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Ferry Company</label>
                             <?php if (empty($available_companies)): ?>
                                <small class="text-muted">No companies available for this route.</small>
                            <?php else: ?>
                                <?php foreach ($available_companies as $company): ?>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="companies[]" value="<?php echo htmlspecialchars($company['ferry_company']); ?>" id="company-<?php echo htmlspecialchars($company['ferry_company']); ?>" <?php if (in_array($company['ferry_company'], $filter_companies)) echo 'checked'; ?>>
                                        <label class="form-check-label" for="company-<?php echo htmlspecialchars($company['ferry_company']); ?>"><?php echo htmlspecialchars($company['ferry_company']); ?></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 Ferry Trips</h2>
            <?php if (empty($ferries)): ?>
                <div class="card card-body text-center"><p class="mb-0">No ferry trips found matching your criteria. Try adjusting your filters.</p></div>
            <?php else: ?>
                <?php foreach ($ferries as $ferry): ?>
                <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"><i class="bi bi-tsunami fs-2 text-primary"></i><div class="fw-bold small mt-1"><?php echo htmlspecialchars($ferry['ferry_company']); ?></div></div><div class="col-md-7"><div class="d-flex justify-content-between align-items-center"><div><strong class="fs-5"><?php echo htmlspecialchars($ferry['origin_name']); ?></strong></div><div class="text-center text-muted small"><?php echo htmlspecialchars($ferry['duration_hours']); ?> hours<hr class="my-1"></div><div><strong class="fs-5"><?php echo htmlspecialchars($ferry['destination_name']); ?></strong></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($ferry['price']); ?></h4><div class="d-grid"><a href="#" class="btn btn-primary">Select Ferry</a></div></div></div></div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

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