<?php
// 1. INCLUDE THE UNIFIED HEADER
// FIXED: The path must go up one directory (..) to find the includes folder.
include '../includes/header.php';

// --- Page-Specific Logic Starts Here ---
// The $user_id and $user_data variables are available from header.php

// 2. FETCH ALL BOOKING TYPES for the user in a single, efficient query
$stmt_all = $conn->prepare("
    (SELECT 'Flight' as booking_type, fb.id, fb.booking_ref, fb.status, fb.payment_status, fb.departure_date as main_date, fb.total_price, 
     CONCAT(orig.name, ' to ', dest.name) as title
     FROM flight_bookings fb 
     JOIN airports orig ON fb.origin_airport_id = orig.id 
     JOIN airports dest ON fb.destination_airport_id = dest.id
     WHERE fb.user_id = ?)
    UNION ALL
    (SELECT 'Ferry' as booking_type, frb.id, frb.booking_ref, frb.status, frb.payment_status, frb.departure_date as main_date, frb.total_price, 
     CONCAT(orig.location, ' to ', dest.location) as title
     FROM ferry_bookings frb 
     JOIN ferry_ports orig ON frb.origin_port_id = orig.id 
     JOIN ferry_ports dest ON frb.destination_port_id = dest.id
     WHERE frb.user_id = ?)
    UNION ALL
    (SELECT 'Hotel' as booking_type, hb.id, hb.booking_ref, hb.status, hb.payment_status, hb.check_in_date as main_date, hb.total_price, h.name as title
     FROM hotel_bookings hb JOIN hotels h ON hb.hotel_id = h.id
     WHERE hb.user_id = ?)
    UNION ALL
    (SELECT t.category as booking_type, b.id, b.booking_ref, b.status, b.payment_status, b.booking_date as main_date, b.total_price, t.title as title
     FROM bookings b JOIN tours t ON b.tour_id = t.id
     WHERE b.user_id = ?)
    ORDER BY main_date DESC
");
$stmt_all->bind_param("iiii", $user_id, $user_id, $user_id, $user_id);
$stmt_all->execute();
$all_bookings_result = $stmt_all->get_result();
$all_bookings = $all_bookings_result->fetch_all(MYSQLI_ASSOC);
$stmt_all->close();

// Sort bookings into categories using PHP
$upcoming_bookings = [];
$completed_bookings = [];
$cancelled_bookings = [];
$today = new DateTime('today', new DateTimeZone('Asia/Manila'));

foreach ($all_bookings as $booking) {
    if (in_array($booking['status'], ['Cancelled', 'Rejected'])) {
        $cancelled_bookings[] = $booking;
    } else {
        $booking_date = new DateTime($booking['main_date'], new DateTimeZone('Asia/Manila'));
        if ($booking_date >= $today) {
            $upcoming_bookings[] = $booking;
        } else {
            $completed_bookings[] = $booking;
        }
    }
}

$booking_icons = ['Flight' => 'bi-airplane-fill', 'Hotel' => 'bi-building', 'Tour' => 'bi-compass-fill', 'Service' => 'bi-tools', 'Ferry' => 'bi-tsunami'];

function get_booking_link($booking) {
    $type = strtolower($booking['booking_type']);
    if ($type === 'flight' || $type === 'ferry') {
        return "view-pass.php?type={$type}&ref=" . urlencode($booking['booking_ref']);
    } else {
        return "view-booking-details.php?type={$type}&ref=" . urlencode($booking['booking_ref']);
    }
}
?>

<div class="container my-5">
    <div class="dashboard-content">
        <h1 class="h2 mb-4">My Bookings</h1>

        <ul class="nav nav-tabs mb-4" id="bookingTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="upcoming-tab" data-bs-toggle="tab" data-bs-target="#upcoming" type="button" role="tab">
                    Upcoming <span class="badge bg-primary ms-1"><?php echo count($upcoming_bookings); ?></span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="completed-tab" data-bs-toggle="tab" data-bs-target="#completed" type="button" role="tab">
                    Completed <span class="badge bg-light text-dark ms-1"><?php echo count($completed_bookings); ?></span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="cancelled-tab" data-bs-toggle="tab" data-bs-target="#cancelled" type="button" role="tab">
                    Cancelled <span class="badge bg-light text-dark ms-1"><?php echo count($cancelled_bookings); ?></span>
                </button>
            </li>
        </ul>

        <div class="tab-content" id="bookingTabsContent">
            <div class="tab-pane fade show active" id="upcoming" role="tabpanel">
                <?php if (!empty($upcoming_bookings)): ?>
                    <?php foreach ($upcoming_bookings as $booking): ?>
                        <div class="card shadow-sm mb-3">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-md-1 text-center d-none d-md-block"><i class="bi <?php echo $booking_icons[$booking['booking_type']] ?? 'bi-geo-alt'; ?> fs-2 text-primary"></i></div>
                                    <div class="col-md-5"><h6 class="mb-0"><?php echo htmlspecialchars($booking['title']); ?></h6><small class="text-muted">Ref: <?php echo htmlspecialchars($booking['booking_ref']); ?></small></div>
                                    <div class="col-md-3"><small class="text-muted d-block"><?php echo htmlspecialchars($booking['booking_type']); ?> Date</small><strong><?php echo date('M d, Y', strtotime($booking['main_date'])); ?></strong></div>
                                    <div class="col-md-3 text-md-end mt-3 mt-md-0"><a href="<?php echo get_booking_link($booking); ?>" class="btn btn-primary btn-sm">View Details</a></div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="text-center p-5 border rounded"><p class="text-muted mb-0">You have no upcoming bookings.</p></div>
                <?php endif; ?>
            </div>
            
            <div class="tab-pane fade" id="completed" role="tabpanel">
                 <?php if (!empty($completed_bookings)): ?>
                    <?php foreach ($completed_bookings as $booking): ?>
                        <div class="card shadow-sm mb-3">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-md-1 text-center d-none d-md-block"><i class="bi <?php echo $booking_icons[$booking['booking_type']] ?? 'bi-geo-alt'; ?> fs-2 text-muted"></i></div>
                                    <div class="col-md-5"><h6 class="mb-0 text-muted"><?php echo htmlspecialchars($booking['title']); ?></h6><small class="text-muted">Ref: <?php echo htmlspecialchars($booking['booking_ref']); ?></small></div>
                                    <div class="col-md-3"><small class="text-muted d-block">Date</small><strong><?php echo date('M d, Y', strtotime($booking['main_date'])); ?></strong></div>
                                    <div class="col-md-3 text-md-end mt-3 mt-md-0"><a href="<?php echo get_booking_link($booking); ?>" class="btn btn-secondary btn-sm">View Details</a></div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="text-center p-5 border rounded"><p class="text-muted mb-0">You have no past bookings.</p></div>
                <?php endif; ?>
            </div>
            
            <div class="tab-pane fade" id="cancelled" role="tabpanel">
                 <?php if (!empty($cancelled_bookings)): ?>
                    <?php foreach ($cancelled_bookings as $booking): ?>
                        <div class="card shadow-sm mb-3 bg-light">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-md-1 text-center d-none d-md-block"><i class="bi <?php echo $booking_icons[$booking['booking_type']] ?? 'bi-geo-alt'; ?> fs-2 text-muted"></i></div>
                                    <div class="col-md-5"><h6 class="mb-0 text-muted text-decoration-line-through"><?php echo htmlspecialchars($booking['title']); ?></h6><small class="text-muted">Ref: <?php echo htmlspecialchars($booking['booking_ref']); ?></small></div>
                                    <div class="col-md-3"><small class="text-muted d-block">Date</small><strong class="text-decoration-line-through"><?php echo date('M d, Y', strtotime($booking['main_date'])); ?></strong></div>
                                    <div class="col-md-3 text-md-end mt-3 mt-md-0"><a href="<?php echo get_booking_link($booking); ?>" class="btn btn-secondary btn-sm">View Details</a></div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="text-center p-5 border rounded"><p class="text-muted mb-0">You have no cancelled bookings.</p></div>
                <?php endif; ?>
            </div>
        </div>

    </div>
</div>

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