<?php 
include 'includes/header.php'; 

// 1. GET AND VALIDATE PARAMS
$booking_ref = trim($_GET['ref'] ?? '');
$booking_type = trim($_GET['type'] ?? '');

if (empty($booking_ref) || !in_array($booking_type, ['flight', 'ferry'])) {
    echo "<div class='container my-5'><div class='alert alert-danger'>Invalid booking reference provided.</div></div>";
    include 'includes/footer.php';
    exit();
}

// 2. SET DYNAMIC CONFIGURATION
if ($booking_type === 'flight') {
    $config = [
        'booking_table' => 'flight_bookings', 'pass_table' => 'flight_boarding_passes',
        'origin_join_table' => 'airports', 'dest_join_table' => 'airports',
        'origin_id_col' => 'origin_airport_id', 'dest_id_col' => 'destination_airport_id',
        'icon' => 'bi-airplane-fill', 'travel_type' => 'Flight'
    ];
} else { // ferry
    $config = [
        'booking_table' => 'ferry_bookings', 'pass_table' => 'ferry_boarding_passes',
        'origin_join_table' => 'ferry_ports', 'dest_join_table' => 'ferry_ports',
        'origin_id_col' => 'origin_port_id', 'dest_id_col' => 'destination_port_id',
        'icon' => 'bi-tsunami', 'travel_type' => 'Vessel'
    ];
}

// 3. FETCH ALL DATA for the specific booking type
$origin_code_col = ($booking_type === 'flight') ? 'orig.airport_code as origin_code' : "'' as origin_code";
$dest_code_col = ($booking_type === 'flight') ? 'dest.airport_code as dest_code' : "'' as dest_code";

$stmt = $conn->prepare("
    SELECT b.*, u.full_name,
        bp.passenger_name, bp.pnr_code, bp.carrier_name, bp.travel_number, bp.seat_number, bp.gate,
        bp.boarding_datetime, bp.departure_datetime, bp.arrival_datetime,
        bp.status as pass_status,
        orig.name as origin_city, dest.name as dest_city, 
        $origin_code_col, $dest_code_col
    FROM {$config['booking_table']} b
    JOIN users u ON b.user_id = u.id
    LEFT JOIN {$config['pass_table']} bp ON b.id = bp.booking_id
    LEFT JOIN {$config['origin_join_table']} orig ON b.{$config['origin_id_col']} = orig.id
    LEFT JOIN {$config['dest_join_table']} dest ON b.{$config['dest_id_col']} = dest.id
    WHERE b.booking_ref = ?
");
$stmt->bind_param("s", $booking_ref);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$data) {
    echo "<div class='container my-5'><div class='alert alert-danger'>Booking not found.</div></div>";
    include 'includes/footer.php';
    exit();
}

// 4. THE RULE LOGIC
$show_boarding_pass = false;
if (isset($data['pass_status']) && $data['pass_status'] === 'Finalized' && !empty($data['departure_datetime'])) {
    $now = new DateTime("now", new DateTimeZone('Asia/Manila'));
    $departure = new DateTime($data['departure_datetime'], new DateTimeZone('Asia/Manila'));
    if ($now >= $departure->modify('-24 hours') && $now < $departure->modify('+24 hours')) {
        $show_boarding_pass = true;
    }
}
?>

<style>
    .pass-container { max-width: 450px; margin: auto; }
    .ticket { background: #fff; border-radius: 15px; box-shadow: 0 5px 25px rgba(0,0,0,0.1); }
    .ticket-header { background: #0d6efd; color: #fff; border-radius: 15px 15px 0 0; }
    .ticket-label { font-size: 0.7rem; color: #6c757d; font-weight: bold; letter-spacing: 0.5px; }
    .ticket-data { font-size: 1.25rem; font-weight: bold; line-height: 1.2; }
    .ticket-data-lg { font-size: 2.5rem; }
    .ticket-divider { border-top: 2px dashed #dee2e6; }
</style>

<div class="container my-5">
    <div class="pass-container">

        <?php if ($show_boarding_pass): ?>
            <div class="ticket">
                <div class="ticket-header p-3 d-flex justify-content-between align-items-center">
                    <div><h5 class="mb-0"><?php echo htmlspecialchars($data['carrier_name'] ?? 'Your Carrier'); ?></h5><small>Boarding Pass</small></div>
                    <i class="bi <?php echo $config['icon']; ?> fs-2"></i>
                </div>
                <div class="p-3">
                    <div class="row mb-3">
                        <div class="col"><span class="ticket-label">From</span><div class="ticket-data"><?php echo htmlspecialchars($data['origin_city']); ?></div></div>
                        <div class="col text-end"><span class="ticket-label">To</span><div class="ticket-data"><?php echo htmlspecialchars($data['dest_city']); ?></div></div>
                    </div>
                    <div class="mb-3"><span class="ticket-label">Passenger</span><div class="ticket-data"><?php echo htmlspecialchars($data['passenger_name']); ?></div></div>
                    <div class="row mb-3 text-center ticket-divider pt-3">
                        <div class="col-4"><span class="ticket-label"><?php echo $config['travel_type']; ?></span><div class="ticket-data"><?php echo htmlspecialchars($data['travel_number']); ?></div></div>
                        <div class="col-4"><span class="ticket-label">Gate/Pier</span><div class="ticket-data ticket-data-lg"><?php echo htmlspecialchars($data['gate']); ?></div></div>
                        <div class="col-4"><span class="ticket-label">Seat</span><div class="ticket-data"><?php echo htmlspecialchars($data['seat_number']); ?></div></div>
                    </div>
                    <div class="row text-center">
                        <div class="col-6"><span class="ticket-label">Boarding Time</span><div class="ticket-data"><?php echo date('h:i A', strtotime($data['boarding_datetime'])); ?></div></div>
                        <div class="col-6"><span class="ticket-label">Departure</span><div class="ticket-data"><?php echo date('h:i A', strtotime($data['departure_datetime'])); ?></div></div>
                    </div>
                </div>
                <div class="p-3 text-center ticket-divider">
                    <img src="https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=<?php echo urlencode($data['pnr_code']); ?>" alt="QR Code">
                    <p class="mb-0 small mt-1">PNR: <?php echo htmlspecialchars($data['pnr_code']); ?></p>
                </div>
            </div>

        <?php else: ?>
            <div class="ticket">
                <div class="ticket-header p-3">
                    <h5 class="mb-0 text-white">Your Itinerary</h5>
                    <small class="text-white-50">Booking Ref: <?php echo htmlspecialchars($data['booking_ref']); ?></small>
                </div>
                <div class="p-3">
                     <div class="mb-3"><span class="ticket-label">Passenger</span><div class="ticket-data"><?php echo htmlspecialchars($data['full_name']); ?></div></div>
                     <div class="row mb-3">
                        <div class="col"><span class="ticket-label">From</span><div class="ticket-data"><?php echo htmlspecialchars($data['origin_city']); ?></div></div>
                        <div class="col text-end"><span class="ticket-label">To</span><div class="ticket-data"><?php echo htmlspecialchars($data['dest_city']); ?></div></div>
                    </div>
                    <div class="row ticket-divider pt-3">
                        <div class="col-6"><span class="ticket-label">Departure Date</span><div class="ticket-data"><?php echo date('M d, Y', strtotime($data['departure_date'])); ?></div></div>
                        <div class="col-6"><span class="ticket-label">Status</span><div class="ticket-data text-primary"><?php echo htmlspecialchars($data['status']); ?></div></div>
                    </div>
                </div>
                <div class="card-footer bg-light text-center">
                    <p class="mb-0 small text-muted">Your boarding pass with gate and seat information will be available here 24 hours before your departure time.</p>
                </div>
            </div>
        <?php endif; ?>

    </div>
</div>

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