<?php
// 1. INCLUDE THE DASHBOARD HEADER
include 'header.php';

// --- Page-Specific Logic Starts Here ---
$page_error = '';
$booking = null;

// 2. VALIDATE URL PARAMETERS
$booking_ref = trim($_GET['ref'] ?? '');
$booking_type = strtolower(trim($_GET['type'] ?? ''));

if (empty($booking_ref) || empty($booking_type)) {
    $page_error = "No booking reference was provided.";
} else {
    // 3. FETCH BOOKING DETAILS BASED ON TYPE
    // This uses different queries for different booking types to get all necessary details
    
    if ($booking_type === 'hotel') {
        $stmt = $conn->prepare("
            SELECT hb.*, u.full_name, u.email, h.name as item_name, hr.room_type_name, hrr.price_per_night
            FROM hotel_bookings hb
            JOIN users u ON hb.user_id = u.id
            JOIN hotels h ON hb.hotel_id = h.id
            JOIN hotel_rooms hr ON hb.room_id = hr.id
            JOIN hotel_room_rates hrr ON hb.rate_id = hrr.id
            WHERE hb.booking_ref = ? AND hb.user_id = ?
        ");
    } else if ($booking_type === 'tour' || $booking_type === 'service') {
         $stmt = $conn->prepare("
            SELECT b.*, u.full_name, u.email, t.title as item_name, t.location, t.duration_days, t.price as price_per_person
            FROM bookings b
            JOIN users u ON b.user_id = u.id
            JOIN tours t ON b.tour_id = t.id
            WHERE b.booking_ref = ? AND b.user_id = ? AND t.category = ?
        ");
        $stmt->bind_param("sis", $booking_ref, $user_id, $booking_type);
        $stmt->execute();
        $booking = $stmt->get_result()->fetch_assoc();
    }
    
    if (isset($stmt) && $booking_type === 'hotel') {
        $stmt->bind_param("si", $booking_ref, $user_id);
        $stmt->execute();
        $booking = $stmt->get_result()->fetch_assoc();
    }
    
    if (isset($stmt)) $stmt->close();

    if (!$booking) {
        $page_error = "Booking with reference #" . htmlspecialchars($booking_ref) . " could not be found in your account.";
    } else {
        // Calculate number of nights for hotels
        if ($booking_type === 'hotel') {
            $check_in = new DateTime($booking['check_in_date']);
            $check_out = new DateTime($booking['check_out_date']);
            $booking['num_nights'] = $check_in->diff($check_out)->days;
        }
    }
}

// 4. INCLUDE THE HTML HEADER - we do this here to pass the dynamic title
include '../includes/header.php';
?>

<div class="container my-5">
    <?php if ($page_error): ?>
        <div class="alert alert-danger"><h4 class="alert-heading">Error</h4><p><?php echo $page_error; ?></p><hr><a href="my-bookings.php" class="btn btn-outline-danger">Return to My Bookings</a></div>
    <?php else: ?>
        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
            <div>
                <h1 class="h2">Booking Details</h1>
                <p class="text-muted mb-0">Reference #<span class="fw-bold text-light"><?php echo htmlspecialchars($booking['booking_ref']); ?></span></p>
            </div>
            <a href="my-bookings.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left-circle me-1"></i> Back to My Bookings</a>
        </div>
        
        <div class="row g-4">
            <div class="col-lg-8">
                <div class="card shadow-sm">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><?php echo htmlspecialchars(ucfirst($booking_type)); ?> Details</h5>
                        <?php $status_badge = ['Pending Confirmation' => 'warning', 'Confirmed' => 'primary', 'Completed' => 'success', 'Cancelled' => 'danger']; ?>
                        <span class="badge fs-6 bg-<?php echo $status_badge[$booking['status']] ?? 'secondary'; ?>"><?php echo htmlspecialchars($booking['status']); ?></span>
                    </div>
                    <div class="card-body">
                        <h4><?php echo htmlspecialchars($booking['item_name']); ?></h4>
                        <hr>
                        <?php if ($booking_type === 'hotel'): ?>
                            <dl class="row">
                                <dt class="col-sm-4">Check-in</dt><dd class="col-sm-8"><?php echo date('D, F j, Y', strtotime($booking['check_in_date'])); ?></dd>
                                <dt class="col-sm-4">Check-out</dt><dd class="col-sm-8"><?php echo date('D, F j, Y', strtotime($booking['check_out_date'])); ?></dd>
                                <dt class="col-sm-4">Duration</dt><dd class="col-sm-8"><?php echo $booking['num_nights']; ?> night<?php if($booking['num_nights'] > 1) echo 's'; ?></dd>
                                <dt class="col-sm-4">Guests</dt><dd class="col-sm-8"><?php echo htmlspecialchars($booking['num_guests']); ?></dd>
                                <dt class="col-sm-4">Room Type</dt><dd class="col-sm-8"><?php echo htmlspecialchars($booking['room_type_name']); ?></dd>
                            </dl>
                        <?php else: // Tour or Service ?>
                            <dl class="row">
                                <dt class="col-sm-4">Location</dt><dd class="col-sm-8"><?php echo htmlspecialchars($booking['location']); ?></dd>
                                <dt class="col-sm-4">Date</dt><dd class="col-sm-8"><?php echo date('D, F j, Y', strtotime($booking['booking_date'])); ?></dd>
                                <dt class="col-sm-4">Duration</dt><dd class="col-sm-8"><?php echo htmlspecialchars($booking['duration_days']); ?> Day<?php if($booking['duration_days'] > 1) echo 's'; ?></dd>
                                <dt class="col-sm-4">Travelers</dt><dd class="col-sm-8"><?php echo htmlspecialchars($booking['num_travelers']); ?></dd>
                            </dl>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card shadow-sm mb-4">
                    <div class="card-header"><h5 class="mb-0">Customer</h5></div>
                    <div class="card-body">
                        <strong><?php echo htmlspecialchars($booking['full_name']); ?></strong>
                        <div class="text-muted small"><?php echo htmlspecialchars($booking['email']); ?></div>
                    </div>
                </div>
                <div class="card shadow-sm">
                    <div class="card-header"><h5 class="mb-0">Payment Summary</h5></div>
                     <ul class="list-group list-group-flush">
                        <li class="list-group-item d-flex justify-content-between"><span>Payment Status:</span>
                            <span class="badge bg-<?php echo ($booking['payment_status'] == 'Paid') ? 'success' : 'warning'; ?>"><?php echo htmlspecialchars($booking['payment_status']); ?></span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between"><strong>Total Amount</strong><strong class="text-primary">₱<?php echo number_format($booking['total_price'], 2); ?></strong></li>
                    </ul>
                    <div class="card-body">
                        <div class="d-grid gap-2">
                             <button onclick="window.print();" class="btn btn-outline-secondary"><i class="bi bi-printer-fill me-2"></i>Print Details</button>
                             <?php if ($booking['status'] !== 'Cancelled'): ?>
                                <button class="btn btn-outline-danger" onclick="confirm('Are you sure you want to request a cancellation?');"><i class="bi bi-x-circle me-2"></i>Cancel Booking</button>
                             <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

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