<?php
session_start();
require_once __DIR__ . '/../includes/db.php';
    // At the top of your booking page
require_once __DIR__ . '/../includes/mail_function.php';
require 'get_rooms.php';


function generateAlphanumeric($length = 100) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    
    for ($i = 0; $i < $length; $i++) {
        $randomChar = $characters[rand(0, $charactersLength - 1)];
        $randomString .= $randomChar;
    }
    
    return $randomString;
}

// Example usage
//echo generateAlphanumeric(12); // Outputs something like 'a8F9kLm3Xz0T'






// 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'];
    $booking_type = $_POST['bookingType'];
    $contact = $_POST['contact_address'];
    $price_raw = preg_replace('/[^0-9.]/', '', $_POST['price']); // Remove NGN symbols
    $admin_id  = $admin['id']; // assuming admin is logged in
    //'pending','confirmed','cancelled','checked_in','checked_out'
    $booking_ID ="@sheridan_".generateAlphanumeric(7);

    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 {
        $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 {
            // Calculate number of nights
            $checkinDate = new DateTime($checkin);
            $checkoutDate = new DateTime($checkout);
            $nights = $checkinDate->diff($checkoutDate)->days;

            $totalAmount = $nights * floatval($price_raw);

            try {
                $pdo->beginTransaction();

                // Insert customer
                $stmtCustomer = $pdo->prepare("INSERT INTO customers (`full_name`, `email`, `phone`, `address`, `created_at`) VALUES (?, ?, ?, ?, NOW())");
                $stmtCustomer->execute([$name, $email, $phone, $contact]);
                $customer_id = $pdo->lastInsertId();

                // Insert booking
                $stmtBooking = $pdo->prepare("INSERT INTO bookings (`customer_id`, `booked_by`, `room_id`, `check_in`, `check_out`, `total_amount`, `status`, `created_at`, `booking_type`,`booking_ID`) VALUES (?, ?, ?, ?, ?, ?, 'checked_in', NOW(), ?, ?)");
                $stmtBooking->execute([$customer_id, $admin_id, $room_id, $checkin, $checkout, $totalAmount,$booking_type,$booking_ID]);

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

                $pdo->commit();
                $message = "Room successfully booked!";
                
                // After successful booking
                $booking_details = [
                    'booking_id' => $booking_ID,
                    'guest_name' => $name,
                    'room_type' => $category,
                    'check_in' => $checkin,
                    'check_out' => $checkout,
                    'total_amount' => $totalAmount
                ];

                $email_sent = sendEmail([
                    'to_email' => $email,
                    'to_name' => $name,
                    'subject' => 'Your Sheridan Hotel Booking Confirmation',
                    'body' => generateBookingEmail($booking_details)
                ]);

                if (!$email_sent) {
                    // Log error or notify admin
                    error_log("Failed to send booking confirmation to $customerEmail");
                }





            } catch (Exception $e) {
                $pdo->rollBack();
                $error = "Booking failed: " . $e->getMessage();
            }
        }
    }

}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Book a Room - Sheridan Hotel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .form-field {
            transition: all 0.3s ease;
        }
        
        .form-field:focus {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        }
        
        .nav-item {
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }
        
        .nav-item:hover {
            background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
            transform: translateX(5px);
        }
        
        .nav-item.active {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            color: white;
        }
        
        .sidebar-gradient {
            background: linear-gradient(180deg, #1e293b 0%, #334155 100%);
        }
        
        .form-container {
            background: linear-gradient(135deg, #ffffff, #f8fafc);
            border: 1px solid rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(10px);
        }
        
        .success-animation {
            animation: bounceIn 0.5s ease-out;
        }
        
        .error-animation {
            animation: shakeX 0.5s ease-out;
        }
        
        @keyframes bounceIn {
            0% { transform: scale(0.3); opacity: 0; }
            50% { transform: scale(1.05); }
            70% { transform: scale(0.9); }
            100% { transform: scale(1); opacity: 1; }
        }
        
        @keyframes shakeX {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }
            20%, 40%, 60%, 80% { transform: translateX(10px); }
        }
        
        .pulse-dot {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.1); opacity: 0.8; }
        }
        
        .booking-form {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-gray-50 to-gray-100 min-h-screen">
    <!-- Sidebar -->
    <aside class="fixed left-0 top-0 w-72 h-full sidebar-gradient shadow-2xl z-50">
        <div class="p-8">
            <div class="flex items-center gap-3 mb-2">
                <div class="w-10 h-10 bg-gradient-to-r from-blue-400 to-purple-500 rounded-xl flex items-center justify-center">
                    <i class="fas fa-hotel text-white text-lg"></i>
                </div>
                <h1 class="text-2xl font-bold text-white">Sheridan Hotel</h1>
            </div>
            <div class="flex items-center gap-2 mt-4 p-3 bg-white/10 rounded-lg backdrop-blur-sm">
                <div class="w-2 h-2 bg-green-400 rounded-full pulse-dot"></div>
                <p class="text-white/90 text-sm">Logged in as <span class="font-semibold text-blue-300"><?= $admin['role'] ?></span></p>
            </div>
        </div>
        
        <nav class="px-6 space-y-2">
            <a href="dashboard.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-tachometer-alt w-5"></i>
                <span class="font-medium">Dashboard Home</span>
            </a>
            <a href="book_room.php" class="nav-item active flex items-center gap-3 px-4 py-3 text-white rounded-xl">
                <i class="fas fa-calendar-plus w-5"></i>
                <span class="font-medium">Book a Room</span>
            </a>
            <a href="room_status.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-bed w-5"></i>
                <span class="font-medium">Room Status</span>
            </a>
            </a>
            <a href="check_out.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-sign-out-alt w-5"></i>
                <span class="font-medium">Customer Check-out</span>
            </a>
            <a href="list_booked.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-list-alt w-5"></i>
                <span class="font-medium">Booked Rooms</span>
            </a>
            <a href="list_all_rooms.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-building w-5"></i>
                <span class="font-medium">All Rooms</span>
            </a>
             <a href="addstaff.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-user-plus w-5"></i>
                <span class="font-medium">Add Staff</span>
            </a>
        </nav>
        
        <div class="absolute bottom-0 left-0 right-0 p-6 border-t border-white/10">
            <p class="text-white/60 text-xs mb-3">© Sheridan Hotels and Suites</p>
            <a href="../logout.php" class="flex items-center gap-2 text-red-400 hover:text-red-300 text-sm font-medium transition-colors">
                <i class="fas fa-power-off"></i>
                <span>Logout</span>
            </a>
        </div>
    </aside>

    <!-- Main Content Area -->
    <div class="ml-72 min-h-screen">
        <!-- Top Header -->
        <header class="bg-white/80 backdrop-blur-sm border-b border-gray-200/50 px-8 py-6 sticky top-0 z-40">
            <div class="flex justify-between items-center">
                <div>
                    <h1 class="text-3xl font-bold text-gray-800">Book a Room</h1>
                    <p class="text-gray-600 mt-1">Create new reservations for guests</p>
                </div>
                <div class="flex items-center gap-6">
                    <div class="text-right">
                        <p class="text-sm text-gray-500">Welcome back,</p>
                        <p class="font-semibold text-gray-800"><a href="My_profile.php"><?= htmlspecialchars($admin['name']) ?></a></p>
                    </div>
                    <div class="w-12 h-12 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white font-bold text-lg">
                        <?= strtoupper(substr($admin['name'], 0, 1)) ?>
                    </div>
                    <div class="text-sm text-gray-600 font-mono bg-gray-100 px-3 py-2 rounded-lg">
                        <span id="datetime"></span>
                    </div>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="p-8">
            <!-- Header Banner -->
            <div class="booking-form rounded-2xl p-8 mb-8 text-white">
                <div class="flex items-center justify-between">
                    <div>
                        <h2 class="text-2xl font-bold mb-2">Room Reservation System</h2>
                        <p class="text-blue-100">Fill in the guest details to create a new booking</p>
                    </div>
                    <div class="text-6xl opacity-20">
                        <i class="fas fa-calendar-plus"></i>
                    </div>
                </div>
            </div>

            <!-- Booking Form -->
            <div class="max-w-4xl mx-auto">
                <div class="form-container rounded-2xl shadow-2xl overflow-hidden">
                    <!-- Form Header -->
                    <div class="bg-gradient-to-r from-blue-600 to-purple-600 p-6 text-white">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center">
                                <i class="fas fa-user-plus text-lg"></i>
                            </div>
                            <div>
                                <h3 class="text-xl font-semibold">Guest Information & Booking Details</h3>
                                <p class="text-blue-100 text-sm">Please provide accurate information for the reservation</p>
                            </div>
                        </div>
                    </div>

                    <!-- Messages -->
                    <?php if ($message): ?>
                        <div class="bg-green-50 border-l-4 border-green-400 p-6 success-animation">
                            <div class="flex items-center">
                                <div class="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center mr-3">
                                    <i class="fas fa-check text-green-600"></i>
                                </div>
                                <div>
                                    <h4 class="text-green-800 font-semibold">Booking Successful!</h4>
                                    <p class="text-green-700"><?= htmlspecialchars($message) ?></p>
                                </div>
                            </div>
                        </div>
                    <?php elseif ($error): ?>
                        <div class="bg-red-50 border-l-4 border-red-400 p-6 error-animation">
                            <div class="flex items-center">
                                <div class="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center mr-3">
                                    <i class="fas fa-exclamation-triangle text-red-600"></i>
                                </div>
                                <div>
                                    <h4 class="text-red-800 font-semibold">Booking Error</h4>
                                    <p class="text-red-700"><?= htmlspecialchars($error) ?></p>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Form Content -->
                    <div class="p-8">
                        <form method="POST" class="space-y-6">
                            <!-- Guest Information Section -->
                            <div class="bg-gray-50 rounded-xl p-6">
                                <h4 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                                    <i class="fas fa-user text-blue-500"></i>
                                    Guest Information
                                </h4>
                                <div class="grid md:grid-cols-2 gap-6">
                                    <div class="space-y-2">
                                        <label class="text-sm font-medium text-gray-700 flex items-center gap-2">
                                            <i class="fas fa-user text-gray-400"></i>
                                            Full Name
                                        </label>
                                        <input type="text" name="name" placeholder="Enter guest's full name" required 
                                               class="form-field w-full p-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    </div>
                                    <div class="space-y-2">
                                        <label class="text-sm font-medium text-gray-700 flex items-center gap-2">
                                            <i class="fas fa-phone text-gray-400"></i>
                                            Phone Number
                                        </label>
                                        <input type="text" name="phone" placeholder="Enter phone number" required 
                                               class="form-field w-full p-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    </div>
                                    <div class="space-y-2 md:col-span-2">
                                        <label class="text-sm font-medium text-gray-700 flex items-center gap-2">
                                            <i class="fas fa-envelope text-gray-400"></i>
                                            Email Address
                                        </label>
                                        <input type="email" name="email" placeholder="Enter email address" required 
                                               class="form-field w-full p-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    </div>
                                    <div class="space-y-2 md:col-span-2">
                                        <label class="text-sm font-medium text-gray-700 flex items-center gap-2">
                                            <i class="fas fa-map-marker-alt text-gray-400"></i>
                                            Contact Address
                                        </label>
                                        <input type="text" name="contact_address" placeholder="Enter Contact address" required 
                                               class="form-field w-full p-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    </div>
                                </div>
                            </div>

                            <!-- Room Selection Section -->
                            <div class="bg-blue-50 rounded-xl p-6">
                                <h4 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                                    <i class="fas fa-bed text-blue-500"></i>
                                    Room Selection
                                </h4>
                                <div class="grid md:grid-cols-2 gap-6">
                                    <div class="space-y-2">
                                        <label class="text-sm font-medium text-gray-700 flex items-center gap-2">
                                            <i class="fas fa-list text-gray-400"></i>
                                            Room Category
                                        </label>
                                        <select name="room_category" id="room_category" required 
                                                class="form-field w-full p-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                            <option value="">Select Category</option>
                                            <?php foreach ($categories as $cat): ?>
                                                <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="space-y-2">
                                        <label class="text-sm font-medium text-gray-700 flex items-center gap-2">
                                            <i class="fas fa-door-open text-gray-400"></i>
                                            Available Rooms
                                        </label>
                                        <select name="room_id" id="room_id" required 
                                                class="form-field w-full p-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                            <option value="">Select a category first</option>
                                        </select>
                                    </div>
                                    <div class="space-y-2">
                                        <label class="text-sm font-medium text-gray-700 flex items-center gap-2">
                                            <i class="fas fa-tag text-gray-400"></i>
                                            Room Price (per night)
                                        </label>
                                        <input type="text" name="price" id="price" readonly 
                                               class="w-full p-4 border border-gray-300 rounded-xl bg-gray-100 text-gray-600 font-semibold">
                                    </div>
                                    <div class="space-y-2">
                                        <label class="text-sm font-medium text-gray-700 flex items-center gap-2">
                                            <i class="fas fa-route text-gray-400"></i>
                                            Booking Type
                                        </label>
                                        <select name="bookingType" id="bookingType" required 
                                                class="form-field w-full p-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                            <option value="">Select booking type</option>
                                            <option value="online">Online Booking (Via Mail)</option>
                                            <option value="walk-in">Walk-in</option>
                                            <option value="phone">Phone Call or WhatsApp</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Stay Duration Section -->
                            <div class="bg-purple-50 rounded-xl p-6">
                                <h4 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                                    <i class="fas fa-calendar text-purple-500"></i>
                                    Stay Duration
                                </h4>
                                <div class="grid md:grid-cols-2 gap-6">
                                    <div class="space-y-2">
                                        <label class="text-sm font-medium text-gray-700 flex items-center gap-2">
                                            <i class="fas fa-calendar-plus text-gray-400"></i>
                                            Check-in Date
                                        </label>
                                        <input type="date" name="checkin_date" required 
                                               class="form-field w-full p-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                                    </div>
                                    <div class="space-y-2">
                                        <label class="text-sm font-medium text-gray-700 flex items-center gap-2">
                                            <i class="fas fa-calendar-minus text-gray-400"></i>
                                            Check-out Date
                                        </label>
                                        <input type="date" name="checkout_date" required 
                                               class="form-field w-full p-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                                    </div>
                                </div>
                            </div>

                            <!-- Submit Button -->
                            <div class="pt-6">
                                <button type="submit" 
                                        class="w-full bg-gradient-to-r from-blue-600 to-purple-600 text-white p-4 rounded-xl hover:from-blue-700 hover:to-purple-700 transform hover:scale-105 transition-all duration-300 font-semibold text-lg flex items-center justify-center gap-3 shadow-lg">
                                    <i class="fas fa-check-circle"></i>
                                    Complete Booking
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        function formatCurrency(amount) {
            return new Intl.NumberFormat('en-NG', {
                style: 'currency',
                currency: 'NGN',
            }).format(amount);
        }

        // Set up datetime display
        setInterval(() => {
            document.getElementById('datetime').textContent = new Date().toLocaleString(undefined, { 
                hour12: false,
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }, 1000);

        let currentRoomData = [];

        async function loadRooms() {
            const category = document.getElementById('room_category').value;
            const roomSelect = document.getElementById('room_id');
            const priceInput = document.getElementById('price');
            
            // Clear previous data
            roomSelect.innerHTML = '<option value="">Loading rooms...</option>';
            priceInput.value = '';
            
            if (!category) {
                roomSelect.innerHTML = '<option value="">Select a category first</option>';
                return;
            }

            try {
                const res = await fetch(`get_rooms.php?category_id=${category}`);
                
                if (!res.ok) {
                    throw new Error(`HTTP error! status: ${res.status}`);
                }
                
                const data = await res.json();
                currentRoomData = data;

                roomSelect.innerHTML = '';

                if (data.length === 0) {
                    roomSelect.innerHTML = '<option value="">No rooms available</option>';
                    priceInput.value = '';
                    return;
                }

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

                // Set price for the first room (default)
                if (data.length > 0) {
                    priceInput.value = formatCurrency(data[0].price_per_night);
                }
            } catch (error) {
                console.error('Error loading rooms:', error);
                roomSelect.innerHTML = '<option value="">Error loading rooms</option>';
                priceInput.value = '';
            }
        }

        // Set up event listeners when DOM is loaded
        document.addEventListener('DOMContentLoaded', () => {
            const roomCategorySelect = document.getElementById('room_category');
            const roomSelect = document.getElementById('room_id');
            const priceInput = document.getElementById('price');

            // Add change event listener to room category
            roomCategorySelect.addEventListener('change', loadRooms);

            // Update price when room selection changes
            roomSelect.addEventListener('change', () => {
                const selectedRoomId = roomSelect.value;
                if (selectedRoomId && currentRoomData.length > 0) {
                    const selectedRoom = currentRoomData.find(r => r.id == selectedRoomId);
                    priceInput.value = selectedRoom ? formatCurrency(selectedRoom.price_per_night) : '';
                } else {
                    priceInput.value = '';
                }
            });

            // Set minimum date to today
            const today = new Date().toISOString().split('T')[0];
            document.querySelector('input[name="checkin_date"]').min = today;
            document.querySelector('input[name="checkout_date"]').min = today;

            // Update checkout minimum date based on checkin
            document.querySelector('input[name="checkin_date"]').addEventListener('change', function() {
                const checkinDate = this.value;
                const checkoutInput = document.querySelector('input[name="checkout_date"]');
                checkoutInput.min = checkinDate;
                
                // Clear checkout if it's before new checkin date
                if (checkoutInput.value && checkoutInput.value <= checkinDate) {
                    checkoutInput.value = '';
                }
            });
        });
    </script>
</body>
</html>