<?php
//require_once 'includes/db.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/get_rooms.php';
session_start();

// Fetch categories
if (!isset($_SESSION['user'])) {
    header("Location: ../index.php");
    exit;
}
$admin = $_SESSION['user'];
$categories = $pdo->query("SELECT * FROM room_categories")->fetchAll(PDO::FETCH_ASSOC);

// Handle form submission
$message = '';
$error = '';

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name      = trim($_POST['name']);
    $phone     = trim($_POST['phone']);
    $email     = trim($_POST['email']);
    $checkin   = $_POST['checkin_date'];
    $checkout  = $_POST['checkout_date'];
    $category  = $_POST['room_category'];
    $room_id   = $_POST['room_id'];
    $price     = $_POST['price'];

    // Basic input validation
    if (empty($name) || empty($phone) || empty($email) || empty($checkin) || empty($checkout) || empty($category) || empty($room_id)) {
        $error = "All fields are required.";
    } elseif (strtotime($checkin) >= strtotime($checkout)) {
        $error = "Check-out date must be after check-in date.";
    } else {
        // Check if the room is still available
        $roomCheck = $pdo->prepare("SELECT status FROM rooms WHERE id = ?");
        $roomCheck->execute([$room_id]);
        $roomStatus = $roomCheck->fetchColumn();

        if ($roomStatus !== 'available') {
            $error = "This room has already been booked. Please choose another.";
        } else {
            // Insert booking
            $stmt = $pdo->prepare("INSERT INTO bookings (guest_name, phone, email, checkin_date, checkout_date, room_id, category_id, price) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $phone, $email, $checkin, $checkout, $room_id, $category, $price]);

            // Update room status
            $pdo->prepare("UPDATE rooms SET status = 'booked' WHERE id = ?")->execute([$room_id]);

            $message = "Room successfully booked!";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Book a Room</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <!--<link href="../src/output.css" rel="stylesheet">-->
    
    

</head>
<body class="bg-gray-100 flex h-screen">
    <aside class="w-64 bg-white shadow-md h-full flex flex-col">
    <div class="p-6">
        <h1 class="text-xl font-bold text-blue-700">Sheridan Hotel</h1>
        <!--<p class="text-sm text-gray-500 mt-1">Admin Dashboard</p>-->
        <p class="text-gray-600 mb-6">You are logged in as <strong><?= $admin['role'] ?></strong>.</p>
    </div>
    <nav class="flex-1 px-4 space-y-2">
        <a href="dashboard.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Dashboard Home</a>
        <a href="book_room.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Book a Room</a>
        <a href="room_status.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Check Room Status</a>
        <a href="available_rooms.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Available Rooms</a>
        <a href="list_available.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">List of Available Rooms</a>
        <a href="list_booked.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">List of Booked Rooms</a>
    </nav>
    <div class="p-4 border-t">
        <p class="text-sm text-gray-500">All right reserved &copy;Sheridan Hotels and suits
 </p>
        <a href="../logout.php" class="mt-2 inline-block text-red-500 hover:underline text-sm">Logout</a>
    </div>
</aside>

<div class="flex-1 flex flex-col overflow-hidden">
    <nav class="bg-white shadow px-6 py-4 flex justify-between items-center">
        <h1 class="text-xl font-bold text-gray-800">Dashboard Overview</h1>
        <div class="flex items-center gap-4">
            <span class="text-gray-600 text-sm">Welcome, <?= htmlspecialchars($admin['name']) ?>  <span id="datetime"></span>
<script>setInterval(() => document.getElementById('datetime').textContent = new Date().toLocaleString(undefined, { hour12: false }), 1000);</script></span>
             
            
        </div>
    </nav>

    <div class="max-w-2xl mx-auto bg-white p-6 rounded shadow">
        <h2 class="text-xl font-bold mb-4">Book a Room</h2>

        <?php if ($message): ?>
            <div class="bg-green-100 text-green-700 p-2 rounded mb-4"> <?= htmlspecialchars($message) ?> </div>
        <?php elseif ($error): ?>
            <div class="bg-red-100 text-red-700 p-2 rounded mb-4"> <?= htmlspecialchars($error) ?> </div>
        <?php endif; ?>

        <form method="POST">
            <input type="text" name="name" placeholder="Guest Name" required class="w-full mb-3 p-2 border rounded">
            <input type="text" name="phone" placeholder="Phone Number" required class="w-full mb-3 p-2 border rounded">
            <input type="email" name="email" placeholder="Email Address" required class="w-full mb-3 p-2 border rounded">

            <label class="block mt-2 mb-1">Room Category:</label>
            <select name="room_category" id="room_category" onchange="loadRooms()" required class="w-full mb-3 p-2 border rounded">
                <option value="">Select Category</option>
                <?php foreach ($categories as $cat): ?>
                    <option value="<?= $cat['id'] ?>"> <?= htmlspecialchars($cat['name']) ?> </option>
                <?php endforeach; ?>
            </select>

            <label class="block mt-2 mb-1">Available Rooms:</label>
            <select name="room_id" id="room_id" required class="w-full mb-3 p-2 border rounded"></select>

            <label class="block mt-2 mb-1">Check-in Date:</label>
            <input type="date" name="checkin_date" required class="w-full mb-3 p-2 border rounded">

            <label class="block mt-2 mb-1">Check-out Date:</label>
            <input type="date" name="checkout_date" required class="w-full mb-3 p-2 border rounded">

            <label class="block mt-2 mb-1">Room Price:</label>
            <input type="text" name="price" id="price" readonly class="w-full mb-3 p-2 border rounded bg-gray-100">

            <button class="w-full bg-blue-600 text-white p-2 rounded hover:bg-blue-700" type="submit">Book Room</button>
        </form>
    </div>
</div>
    <script>
    async function loadRooms() {
        const category = document.getElementById('room_category').value;
        const res = await fetch(`get_rooms.php?category_id=${category}`);
        const data = await res.json();
        const roomSelect = document.getElementById('room_id');
        roomSelect.innerHTML = '';

        data.forEach(room => {
            const option = document.createElement('option');
            option.value = room.id;
            option.text = `Room ${room.room_number}`;
            roomSelect.appendChild(option);
        });

        document.getElementById('price').value = data.length > 0 ? data[0].price : '';
    }
    </script>
</body>
</html>

