<?php
$pageTitle = "Book Hall";
require_once 'sidebar.php';

$uid = $_SESSION['user_id'];
$hall_id = (int)($_GET['hall_id'] ?? 0);

$hallRes = mysqli_query($conn, "SELECT h.*, u.name as vendor_name FROM halls h 
                                LEFT JOIN users u ON h.vendor_id=u.id WHERE h.id=$hall_id");
if (!$hallRes || mysqli_num_rows($hallRes) === 0) {
    redirect(BASE_URL.'/halls.php', 'Hall not found.', 'danger');
}
$hall = mysqli_fetch_assoc($hallRes);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $date = clean($conn, $_POST['booking_date']);
    $guests = (int)$_POST['guests'];
    $notes = clean($conn, $_POST['notes']);
    
    $check = mysqli_query($conn, "SELECT * FROM hall_dates WHERE hall_id=$hall_id AND available_date='$date' AND status='available'");
    
    if (mysqli_num_rows($check) === 0) {
        $error = "Sorry, this date is not available. Please choose a different date.";
    } else {
        $dup = mysqli_query($conn, "SELECT * FROM bookings WHERE hall_id=$hall_id AND booking_date='$date' AND status IN ('pending','confirmed')");
        if (mysqli_num_rows($dup) > 0) {
            $error = "This date already has a pending or confirmed booking.";
        } else {
            $total = $hall['price_per_day'];
            $q = "INSERT INTO bookings (user_id, hall_id, booking_date, guests, total_amount, notes, status) 
                  VALUES ($uid, $hall_id, '$date', $guests, $total, '$notes', 'pending')";
            if (mysqli_query($conn, $q)) {
                $adminRes = mysqli_query($conn, "SELECT id FROM users WHERE role='admin' LIMIT 1");
                $admin = mysqli_fetch_assoc($adminRes);
                if ($admin) {
                    $msg = "New booking request for {$hall['hall_name']} on $date by " . $_SESSION['name'];
                    mysqli_query($conn, "INSERT INTO messages (sender_id, receiver_id, subject, message) 
                                         VALUES ($uid, {$admin['id']}, 'New Booking Request', '$msg')");
                }
                redirect(BASE_URL.'/user/my-bookings.php', 'Booking request sent! Admin will confirm shortly.');
            } else {
                $error = "Booking failed. Try again.";
            }
        }
    }
}

$availableDates = mysqli_query($conn, "SELECT * FROM hall_dates WHERE hall_id=$hall_id 
                                        AND available_date >= CURDATE() 
                                        AND status='available' 
                                        ORDER BY available_date ASC");
?>

<div class="page-header">
    <h1>Book: <?php echo htmlspecialchars($hall['hall_name']); ?></h1>
    <a href="<?php echo BASE_URL; ?>/hall-details.php?id=<?php echo $hall['id']; ?>" target="_blank" class="btn btn-sm btn-gold">View Hall Details</a>
</div>

<?php showFlash(); ?>
<?php if (!empty($error)): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>

<div class="alert alert-info">
    <div>
        <strong>How It Works:</strong> Submit your booking request. The Super Admin will review and confirm it. 
        Once confirmed, the date will be blocked for other users automatically.
    </div>
</div>

<div class="split-layout narrow">
    <div class="dashboard-card">
        <h2 class="full">Booking Details</h2>
        <?php if (mysqli_num_rows($availableDates) > 0): ?>
            <form method="POST">
                <div class="form-group">
                    <label>Select Available Date *</label>
                    <select name="booking_date" required>
                        <option value="">-- Choose a date --</option>
                        <?php while ($d = mysqli_fetch_assoc($availableDates)): ?>
                            <option value="<?php echo $d['available_date']; ?>">
                                <?php echo date('l, d F Y', strtotime($d['available_date'])); ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Number of Guests *</label>
                    <input type="number" name="guests" required min="1" max="<?php echo $hall['capacity']; ?>" 
                           placeholder="Max <?php echo $hall['capacity']; ?>">
                    <small style="color:#888; font-size:12px;">Maximum capacity: <?php echo $hall['capacity']; ?> guests</small>
                </div>
                <div class="form-group">
                    <label>Special Notes / Requirements</label>
                    <textarea name="notes" rows="4" placeholder="Any special requests, dishes, decoration preferences..."></textarea>
                </div>
                <button type="submit" class="btn" style="width:100%;">Submit Booking Request</button>
            </form>
        <?php else: ?>
            <div class="alert alert-danger">
                <div>Sorry, no dates are currently available for this hall.</div>
            </div>
            <a href="<?php echo BASE_URL; ?>/halls.php" class="btn">Browse Other Halls</a>
        <?php endif; ?>
    </div>
    
    <div>
        <div class="booking-card">
            <div class="price-tag">
                <p class="label">Starting From</p>
                <p class="amount">Rs. <?php echo number_format($hall['price_per_day']); ?><br><small>per day</small></p>
            </div>
            
            <ul class="details-list">
                <li>Capacity <span><?php echo $hall['capacity']; ?> guests</span></li>
                <li>Location <span><?php echo htmlspecialchars(substr($hall['location'], 0, 20)); ?></span></li>
                <li>Vendor <span><?php echo htmlspecialchars(substr($hall['vendor_name'], 0, 20)); ?></span></li>
            </ul>
            
            <img src="<?php echo $hall['main_image'] ? BASE_URL.'/assets/uploads/halls/'.$hall['main_image'] : 'https://via.placeholder.com/400x250'; ?>" 
                 style="width:100%; height:180px; object-fit:cover; border-radius:4px; margin-top:15px;">
        </div>
    </div>
</div>

</main></div></body></html>
