<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$username = $_SESSION['username'] ?? 'Guest';
$user_id  = $_SESSION['user_id'] ?? 0;

// ✅ ADD THIS (SESSION USER)
$created_by = $_SESSION['username'] ?? 'system';

// ================== HANDLE BOOKING SUBMIT ==================
if(isset($_POST['save_booking'])){
    $guest_id        = intval($_POST['guest_id']);
    $room_id         = intval($_POST['conference_room_id']);
    $booking_date_raw = $_POST['booking_date'] ?? '';
    $attendees       = intval($_POST['attendees']);
    $num_days        = intval($_POST['num_days']);

    // Convert datetime-local to MySQL DATETIME
    $booking_date = date('Y-m-d H:i:s', strtotime($booking_date_raw));
    $started_at = $booking_date;

    // Calculate end_date
    $start_dt = new DateTime($booking_date);
    $end_dt = clone $start_dt;
    $end_dt->modify("+".($num_days-1)." days");
    $end_date = $end_dt->format('Y-m-d H:i:s');

    // Get room price
    $room = $conn->query("SELECT price FROM conference_rooms WHERE id=$room_id")->fetch_assoc();
    $room_price = $room['price'] ?? 0;

    $total_amount = $room_price * $num_days;

    // Get guest name
    $guest_row = $conn->query("SELECT name FROM guests WHERE id=$guest_id")->fetch_assoc();
    $client_name = $conn->real_escape_string($guest_row['name'] ?? '');

    // ================== INSERT BOOKING ==================
    $sql = "
        INSERT INTO conference_bookings
        (guest_id, client_name, conference_room_id, booking_date, started_at, end_date, attendees, num_days, room_price, total_amount, status,    created_by)
        VALUES
        ($guest_id, '$client_name', $room_id, '$booking_date', '$started_at', '$end_date', $attendees, $num_days, $room_price, $total_amount, 'PENDING',
  '" . $conn->real_escape_string($created_by) . "'


            )
    ";

    if(!$conn->query($sql)){
        echo "<pre>Error inserting booking: ".$conn->error."</pre>";
        exit;
    }

    // Get auto-increment id
    $id = $conn->insert_id;

    // Generate human-friendly booking_id (optional)
    $booking_id = $guest_id; // e.g., booking numbers start from 1001
    $conn->query("UPDATE conference_bookings SET booking_id=$booking_id WHERE id=$id");

    // ================== SEND EMAIL NOTIFICATION ==================
    $to = "giantplusmw@gmail.com,rams.investments@gmail.com";
    $subject = "New Conference Booking #$booking_id";
    $message = "
        A new conference booking has been made:

        Booking ID: $booking_id
        Guest Name: $client_name
        Room ID: $room_id
        Booking Date: $booking_date
        Number of Attendees: $attendees
        Number of Days: $num_days
        Total Amount: MK $total_amount
        Created By: $created_by
    ";

    $headers = "From: cloud@gianterp.space\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

    @mail($to, $subject, $message, $headers);
    // ===============================================================

    // Success alert
    echo "<script>
            alert('✅ Conference booking #$booking_id added! Total: MK $total_amount');
            window.location='conference_bookings.php';
          </script>";
    exit;
}

// ================== FETCH GUESTS ==================
$guest_list = $conn->query("SELECT id, name FROM guests WHERE status = 2 ORDER BY name");

// ================== FETCH ROOMS ==================
$rooms = $conn->query("SELECT id, name, max_guests, price FROM conference_rooms ORDER BY name");
?>

<div class="container mt-4">
    <button class="btn btn-secondary mb-3" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <h3 class="text-center mb-4">➕ Add Conference Booking</h3>

    <form method="POST" class="row g-3">

        <!-- Guest -->
        <div class="col-md-6">
        <!-- Include Font Awesome (if not already included) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
    .guest-label {
        display: block;
        font-weight: 600;
        color: #1e7e34; /* Nice green */
        margin-bottom: 6px;
        font-size: 15px;
    }

    .guest-label i {
        margin-right: 6px;
        color: #28a745;
    }

    .guest-note {
        display: block;
        font-size: 13px;
        color: #6c757d;
        margin-top: 3px;
    }

    .guest-note i {
        color: #17a2b8;
        margin-right: 4px;
    }
</style>

<label class="guest-label">
    <i class="fa-solid fa-user-check"></i> Guest
</label>
<span class="guest-note">
    <i class="fa-solid fa-circle-info"></i>
    Select an existing guest. If not listed, please add the guest in the Guests section.
</span>
            <select name="guest_id" class="form-control" required>
                <option value="">Select Guest</option>
                <?php while($g = $guest_list->fetch_assoc()): ?>
                    <option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['name']) ?></option>
                <?php endwhile; ?>
            </select>
        </div>

        <!-- Conference Room -->
        <div class="col-md-6">
            <label class="guest-label">Conference Room</label>
            <span class="guest-note">
    <i class="fa-solid fa-circle-info"></i>
    Please select conference room from below.
</span>
            <select name="conference_room_id" id="conference_room_id" class="form-control" required>
                <option value="">Select Room</option>
                <?php while($r = $rooms->fetch_assoc()): ?>
                    <option value="<?= $r['id'] ?>" data-price="<?= $r['price'] ?>">
                        <?= htmlspecialchars($r['name']) ?> (MK <?= number_format($r['price'],2) ?> | Max <?= $r['max_guests'] ?>)
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <!-- Booking Date -->
        <div class="col-md-6">
            <label class="guest-label">Booking Date & Time</label>
                     <span class="guest-note">
    <i class="fa-solid fa-circle-info"></i>
    Please do not forget to add time as well like 08:00 AM.
</span>
            <input type="datetime-local" name="booking_date" class="form-control" required>
        </div>

        <!-- Attendees -->
        <div class="col-md-3">
            <label class="guest-label">Number of Attendees</label>
                            <span class="guest-note">
    <i class="fa-solid fa-circle-info"></i>
    Please add number of attendees.
</span>
            <input type="number" name="attendees" id="attendees" class="form-control" min="1" value="1">
        </div>

        <!-- Number of Days -->
        <div class="col-md-3">
            <label class="guest-label">Number of Days</label>
                                   <span class="guest-note">
    <i class="fa-solid fa-circle-info"></i>
    Please add number of days.Once added it does auto calculate total amount for room.
</span>
            <input type="number" name="num_days" id="num_days" class="form-control" min="1" value="1" required>
        </div>

        <!-- Total Amount -->
        <div class="col-md-6">
            <label>Total Amount (MK)</label>
            <input type="number" id="total_amount" class="form-control" readonly>
        </div>

        <div class="col-12 mt-3">
            <button type="submit" name="save_booking" class="btn btn-success w-100">
                💾 Save Booking
            </button>
        </div>
    </form>
</div>

<script>
// Calculate total based on selected room price and number of days
function calculateTotal(){
    const roomSelect = document.getElementById('conference_room_id');
    const num_days = parseFloat(document.getElementById('num_days').value) || 0;
    const room_price = parseFloat(roomSelect.selectedOptions[0]?.dataset.price || 0);
    document.getElementById('total_amount').value = (room_price * num_days).toFixed(2);
}

// Event listeners
document.getElementById('conference_room_id').addEventListener('change', calculateTotal);
document.getElementById('num_days').addEventListener('input', calculateTotal);

// Initial calculation
calculateTotal();
</script>

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