<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';


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

// 2. VALIDATE THE BOOKING REFERENCE FROM THE URL
$booking_ref = trim($_GET['ref'] ?? '');
if (empty($booking_ref)) {
    $page_error = "No booking reference was provided.";
} else {
    // 3. FETCH ALL BOOKING DETAILS WITH JOINS
    $stmt_fetch = $conn->prepare("
        SELECT 
            hb.*, 
            u.full_name, u.email,
            h.name as hotel_name,
            hr.room_type_name,
            hrr.rate_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 = ?
    ");
    $stmt_fetch->bind_param("s", $booking_ref);
    $stmt_fetch->execute();
    $booking = $stmt_fetch->get_result()->fetch_assoc();
    $stmt_fetch->close();

    if (!$booking) {
        $page_error = "Booking with reference #" . htmlspecialchars($booking_ref) . " could not be found.";
    } else {
        // 4. HANDLE FORM SUBMISSION FOR UPDATES
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_booking') {
            $booking_id_to_update = filter_input(INPUT_POST, 'booking_id', FILTER_VALIDATE_INT);
            $new_status = $_POST['status'];
            $new_payment_status = $_POST['payment_status'];

            if ($booking_id_to_update === (int)$booking['id']) {
                $stmt_update = $conn->prepare("UPDATE hotel_bookings SET status = ?, payment_status = ? WHERE id = ?");
                $stmt_update->bind_param("ssi", $new_status, $new_payment_status, $booking_id_to_update);
                if ($stmt_update->execute()) {
                    $_SESSION['success_message'] = "Booking #" . $booking_ref . " has been updated.";
                } else {
                    $_SESSION['error_message'] = "Error updating booking.";
                }
                $stmt_update->close();
                header("Location: view-hotel-booking.php?ref=" . $booking_ref);
                exit();
            }
        }
        
        // Calculate number of nights
        $check_in = new DateTime($booking['check_in_date']);
        $check_out = new DateTime($booking['check_out_date']);
        $num_nights = $check_in->diff($check_out)->days;
    }
}


// 5. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<?php if ($page_error): ?>
    <div class="alert alert-danger mt-4"><h4 class="alert-heading">Error</h4><p><?php echo $page_error; ?></p><hr><a href="hotel-bookings.php" class="btn btn-outline-danger">Return to Hotel 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">View Hotel Booking</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="hotel-bookings.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left-circle me-1"></i> Back to List</a>
    </div>

    <div class="row g-4">
        <div class="col-lg-8">
            <div class="card shadow-sm mb-4">
                <div class="card-header"><h5 class="mb-0">Booking Details</h5></div>
                <div class="card-body">
                    <dl class="row">
                        <dt class="col-sm-3">Hotel</dt>
                        <dd class="col-sm-9"><?php echo htmlspecialchars($booking['hotel_name']); ?></dd>
                        
                        <dt class="col-sm-3">Room Type</dt>
                        <dd class="col-sm-9"><?php echo htmlspecialchars($booking['room_type_name']); ?></dd>
                        
                        <dt class="col-sm-3">Rate Type</dt>
                        <dd class="col-sm-9"><?php echo htmlspecialchars($booking['rate_name']); ?></dd>

                        <dt class="col-sm-3">Check-in</dt>
                        <dd class="col-sm-9"><?php echo date('D, F j, Y', strtotime($booking['check_in_date'])); ?></dd>
                        
                        <dt class="col-sm-3">Check-out</dt>
                        <dd class="col-sm-9"><?php echo date('D, F j, Y', strtotime($booking['check_out_date'])); ?></dd>
                        
                        <dt class="col-sm-3">Duration</dt>
                        <dd class="col-sm-9"><?php echo $num_nights; ?> night<?php if($num_nights > 1) echo 's'; ?></dd>
                        
                        <dt class="col-sm-3">Guests</dt>
                        <dd class="col-sm-9"><?php echo htmlspecialchars($booking['num_guests']); ?></dd>
                    </dl>
                </div>
            </div>
            <div class="card shadow-sm">
                <div class="card-header"><h5 class="mb-0">Customer Information</h5></div>
                <div class="card-body">
                    <dl class="row">
                        <dt class="col-sm-3">Name</dt>
                        <dd class="col-sm-9"><?php echo htmlspecialchars($booking['full_name']); ?></dd>
                        <dt class="col-sm-3">Email</dt>
                        <dd class="col-sm-9"><a href="mailto:<?php echo htmlspecialchars($booking['email']); ?>"><?php echo htmlspecialchars($booking['email']); ?></a></dd>
                    </dl>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card shadow-sm mb-4">
                <div class="card-header"><h5 class="mb-0">Status & Financials</h5></div>
                <ul class="list-group list-group-flush">
                    <li class="list-group-item d-flex justify-content-between"><span>Booking Status:</span>
                        <?php $status_badge = ['Pending Confirmation' => 'warning', 'Confirmed' => 'primary', 'Completed' => 'success', 'Cancelled' => 'danger']; ?>
                        <span class="badge bg-<?php echo $status_badge[$booking['status']] ?? 'secondary'; ?>"><?php echo htmlspecialchars($booking['status']); ?></span>
                    </li>
                    <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"><span>Total Price:</span><strong>₱<?php echo number_format($booking['total_price'], 2); ?></strong></li>
                </ul>
            </div>
            <div class="card shadow-sm">
                <div class="card-header"><h5 class="mb-0">Admin Actions</h5></div>
                <div class="card-body">
                    <form method="POST" action="view-hotel-booking.php?ref=<?php echo $booking_ref; ?>">
                        <input type="hidden" name="action" value="update_booking">
                        <input type="hidden" name="booking_id" value="<?php echo $booking['id']; ?>">
                        <div class="mb-3">
                            <label for="status" class="form-label">Update Booking Status</label>
                            <select name="status" id="status" class="form-select">
                                <option value="Pending Confirmation" <?php if($booking['status'] == 'Pending Confirmation') echo 'selected'; ?>>Pending Confirmation</option>
                                <option value="Confirmed" <?php if($booking['status'] == 'Confirmed') echo 'selected'; ?>>Confirmed</option>
                                <option value="Completed" <?php if($booking['status'] == 'Completed') echo 'selected'; ?>>Completed</option>
                                <option value="Cancelled" <?php if($booking['status'] == 'Cancelled') echo 'selected'; ?>>Cancelled</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="payment_status" class="form-label">Update Payment Status</label>
                            <select name="payment_status" id="payment_status" class="form-select">
                                <option value="Unpaid" <?php if($booking['payment_status'] == 'Unpaid') echo 'selected'; ?>>Unpaid</option>
                                <option value="Paid" <?php if($booking['payment_status'] == 'Paid') echo 'selected'; ?>>Paid</option>
                            </select>
                        </div>
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary"><i class="bi bi-save-fill me-1"></i> Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php include 'admin-footer.php'; ?>
