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

// ===============================
// GET BOOKING ID
// ===============================
$booking_id = isset($_GET['booking_id']) ? intval($_GET['booking_id']) : 0;
if ($booking_id <= 0) {
    echo "<script>alert('Invalid booking ID');window.location='conference_bookings.php';</script>";
    exit;
}

// ===============================
// FETCH BOOKING
// ===============================
$stmt = $conn->prepare("SELECT * FROM conference_bookings WHERE id = ?");
$stmt->bind_param("i", $booking_id);
$stmt->execute();
$result = $stmt->get_result();
$booking = $result->fetch_assoc();
if (!$booking) {
    echo "<script>alert('Booking not found');window.location='conference_bookings.php';</script>";
    exit;
}

// ===============================
// FETCH MEALS, REFRESHMENTS, RESOURCES, ROOMS
// ===============================
$meal_list = $conn->query("SELECT * FROM conference_meals WHERE is_active=1 ORDER BY id");
$refreshments = $conn->query("SELECT * FROM conference_refreshments WHERE is_active=1 ORDER BY id");
$resources_list = $conn->query("SELECT * FROM conference_resources ORDER BY resource_name");
$rooms = $conn->query("SELECT * FROM rooms ORDER BY room_type");

// ===============================
// HANDLE CONFIRMATION
// ===============================
if (isset($_POST['confirm_booking'])) {

    if ($booking['status'] != 'PENDING') {
        echo "<script>alert('Booking already processed');window.location='conference_bookings.php';</script>";
        exit;
    }

    $num_days = intval($_POST['num_days']);
    $cost_per_participant = floatval($_POST['room_price']); // use input value
    $food_items = $_POST['food_items'] ?? [];
    $other_resources = $_POST['other_resources'] ?? [];
    $selected_acc_rooms = $_POST['rooms'] ?? [];
    $attendees = intval($booking['attendees']);

    // ================================
    // CALCULATE MEALS AND REFRESHMENTS
    // ================================
    $food_total = 0;
    $refreshment_total = 0;

    if (!empty($food_items)) {
        $stmt_food = $conn->prepare("INSERT INTO conference_booking_resources (booking_id, resource_type, resource_id, quantity) VALUES (?, ?, ?, 1)");
        foreach ($food_items as $f) {
            if (is_numeric($f)) {
                // Meal
                $res = $conn->query("SELECT price FROM conference_meals WHERE id=".intval($f)." LIMIT 1");
                $price = floatval($res->fetch_assoc()['price'] ?? 0);
                $food_total += $price * $attendees * $num_days;
                $type = 'FOOD';
                $res_id = intval($f);
            } else {
                // Refreshments (session_type)
                $res = $conn->query("SELECT id, price FROM conference_refreshments WHERE session_type='".$conn->real_escape_string($f)."' LIMIT 1");
                $row = $res->fetch_assoc();
                $res_id = intval($row['id'] ?? 0);
                $price = floatval($row['price'] ?? 28000);
                $refreshment_total += $price * $attendees * $num_days;
                $type = 'REFRESHMENT';
            }

            if ($res_id > 0) {
                $stmt_food->bind_param("isi", $booking_id, $type, $res_id);
                $stmt_food->execute();
            }
        }
    }

    // ================================
    // OTHER RESOURCES (one-time)
    // ================================
    $resources_total = 0;
    if (!empty($other_resources)) {
        $ids = implode(",", array_map('intval', $other_resources));
        $res = $conn->query("SELECT SUM(unit_cost) AS total FROM conference_resources WHERE id IN ($ids)");
        $resources_total = floatval($res->fetch_assoc()['total'] ?? 0);

        $stmt_other = $conn->prepare("INSERT INTO conference_booking_resources (booking_id, resource_type, resource_id, quantity) VALUES (?, 'OTHER', ?, 1)");
        foreach ($other_resources as $res_id) {
            $res_id_var = intval($res_id);
            $stmt_other->bind_param("ii", $booking_id, $res_id_var);
            $stmt_other->execute();
        }
    }

    // ================================
    // ACCOMMODATION ROOMS (multiply per day)
    // ================================
    $accommodation_total = 0;
    if (!empty($selected_acc_rooms)) {
        $ids = implode(",", array_map('intval', $selected_acc_rooms));
        $res = $conn->query("SELECT SUM(price) AS total FROM rooms WHERE id IN ($ids)");
        $accommodation_total = floatval($res->fetch_assoc()['total'] ?? 0) * $num_days;

        $stmt_room = $conn->prepare("INSERT INTO conference_booking_accommodation (booking_id, room_id) VALUES (?, ?)");
        foreach ($selected_acc_rooms as $room_id) {
            $room_id_var = intval($room_id);
            $stmt_room->bind_param("ii", $booking_id, $room_id_var);
            $stmt_room->execute();
        }
    }

    // ================================
    // CONFERENCE ROOM TOTAL
    // ================================
    $conference_room_total = $cost_per_participant * $num_days;

    // ================================
    // FINAL TOTAL
    // ================================
    $total_amount = $conference_room_total + $food_total + $refreshment_total + $resources_total + $accommodation_total;

    // ================================
    // UPDATE BOOKING
    // ================================
    $stmt = $conn->prepare("UPDATE conference_bookings SET status='CONFIRMED', num_days=?, cost_per_participant=?, total_amount=? WHERE id=?");
    $stmt->bind_param("iddi", $num_days, $cost_per_participant, $total_amount, $booking_id);
    $stmt->execute();

    echo "<script>alert('✅ Booking confirmed! Total: MK $total_amount');window.location='conference_bookings.php';</script>";
    exit;
}
?>

<div class="container mt-4">
    <h3>Confirm Conference Booking #<?= $booking['id'] ?></h3>
    <hr>

    <div class="mb-3">
        <strong>Client:</strong> <?= htmlspecialchars($booking['client_name']) ?><br>
        <strong>Date & Time:</strong> <?= date('d-m-Y H:i', strtotime($booking['booking_date'])) ?><br>
        <strong>Attendees:</strong> <?= $booking['attendees'] ?><br>
        <strong>Number of Days:</strong> <?= $booking['num_days'] ?><br>
        <strong>Conference Room Price:</strong> <?= $booking['room_price'] ?><br>
    </div>

    <form method="POST">
        <div class="row g-3">
            <div class="col-md-4">
                <label>Number of Days</label>
                <input type="number" name="num_days" id="num_days" class="form-control" min="1" value="<?= $booking['num_days'] ?? 1 ?>" required>
            </div>
            <div class="col-md-4">
                <label>Room Price</label>
                <input type="number" name="room_price" id="cost_per_participant" class="form-control" min="0" step="0.01" value="<?= $booking['room_price'] ?? 0 ?>" required>
            </div>
            <div class="col-md-4">
                <label>Total Amount (MK)</label>
                <input type="number" id="total_amount" class="form-control" readonly value="<?= $booking['total_amount'] ?? 0 ?>">
            </div>

            <!-- Conference Meals -->
            <div class="col-md-6 mt-3">
                <label class="form-label fw-bold text-success">🍽️ Conference Meals</label>
                <div class="border p-2" style="max-height:200px; overflow-y:auto;">
                    <?php while($f = $meal_list->fetch_assoc()): ?>
                        <div class="form-check d-flex justify-content-between">
                            <div>
                                <input type="checkbox" name="food_items[]" value="<?= $f['id'] ?>" data-price="<?= $f['price'] ?>" class="meal_checkbox" id="meal_<?= $f['id'] ?>">
                                <label for="meal_<?= $f['id'] ?>" class="meal_label"><?= $f['meal_name'] ?></label>
                            </div>
                            <span>MK <?= number_format($f['price'],2) ?></span>
                        </div>
                    <?php endwhile; ?>
                </div>
            </div>

            <!-- Refreshments -->
            <div class="col-md-6 mt-3">
                <label class="form-label fw-bold text-warning">☕ Refreshments</label>
                <div class="border p-2" style="max-height:200px; overflow-y:auto;">
                    <?php while($r = $refreshments->fetch_assoc()): ?>
                        <div class="form-check d-flex justify-content-between">
                            <div>
                                <input type="checkbox" name="food_items[]" value="<?= $r['session_type'] ?>" data-price="<?= $r['price'] ?>" class="meal_checkbox" id="refresh_<?= $r['id'] ?>">
                                <label for="refresh_<?= $r['id'] ?>" class="meal_label"><?= $r['item_name'] ?></label>
                            </div>
                            <span>MK <?= number_format($r['price'],2) ?></span>
                        </div>
                    <?php endwhile; ?>
                </div>
            </div>

            <!-- Other Resources -->
         <div class="col-md-6 mt-3">
    <label class="form-label fw-bold text-info">📦 Other Resources</label>
    <div class="border p-2" style="max-height:200px; overflow-y:auto;">
        <?php while($r = $resources_list->fetch_assoc()): ?>
            <div class="form-check d-flex justify-content-between">
                <div>
                    <input type="checkbox" name="other_resources[]" value="<?= $r['id'] ?>" 
                           data-price="<?= $r['unit_cost'] ?>" 
                           id="res_<?= $r['id'] ?>" checked>
                    <label for="res_<?= $r['id'] ?>"><?= $r['resource_name'] ?></label>
                </div>
                <span>MK <?= number_format($r['unit_cost'],2) ?></span>
            </div>
        <?php endwhile; ?>
    </div>
</div>

            <!-- Accommodation Rooms -->
            <div class="col-md-6 mt-3">
                <label class="form-label fw-bold text-secondary">🛏️ Accommodation Rooms</label>
                <div class="border p-2" style="max-height:200px; overflow-y:auto;">
                    <?php while($room = $rooms->fetch_assoc()): ?>
                        <?php $occupied = $room['status'] != 'Available'; ?>
                        <div class="form-check d-flex justify-content-between <?= $occupied?'bg-danger text-white p-1 rounded mb-1':'' ?>">
                            <div>
                                <input type="checkbox" name="rooms[]" value="<?= $room['id'] ?>" data-price="<?= $room['price'] ?>" id="acc_<?= $room['id'] ?>" <?= $occupied?'disabled':'' ?>>
                                <label for="acc_<?= $room['id'] ?>"><?= $room['room_type'] ?> (<?= $room['capacity'] ?>)</label>
                            </div>
                            <span>MK <?= number_format($room['price'],2) ?></span>
                        </div>
                    <?php endwhile; ?>
                </div>
            </div>

            <!-- Submit -->
            <div class="col-12 mt-3">
                <button type="submit" name="confirm_booking" class="btn btn-success w-100 fw-bold">✅ Confirm Booking</button>
            </div>
        </div>
    </form>
</div>

<script>
// ====================
// DYNAMIC CALCULATION
// ====================
const attendees = <?= intval($booking['attendees']) ?>;

function calculateTotal() {
    const days = parseFloat(document.getElementById('num_days').value) || 0;
    const costPerParticipant = parseFloat(document.getElementById('cost_per_participant').value) || 0;

    // Meals & Refreshments (per attendee per day)
    let foodTotal = 0;
    document.querySelectorAll('input[name="food_items[]"]:checked').forEach(el => {
        const price = parseFloat(el.dataset.price || 0);
        foodTotal += price * attendees * days;

        // Update label dynamically
        const label = el.closest('div').querySelector('.meal_label');
        if(label){
            label.innerText = `${label.innerText.split('(')[0].trim()} (MK ${price} × ${attendees} × ${days})`;
        }
    });

    // Other resources (one-time)
    let resourcesTotal = 0;
    document.querySelectorAll('input[name="other_resources[]"]:checked').forEach(el => {
        resourcesTotal += parseFloat(el.dataset.price || 0);
    });

    // Accommodation rooms (one-time per day)
    let accommodationTotal = 0;
    document.querySelectorAll('input[name="rooms[]"]:checked').forEach(el => {
        accommodationTotal += parseFloat(el.dataset.price || 0) * days;
    });

    // Conference room base cost
    const conferenceRoomTotal = costPerParticipant * days;

    document.getElementById('total_amount').value = (conferenceRoomTotal + foodTotal + resourcesTotal + accommodationTotal).toFixed(2);
}

// Event listeners
document.getElementById('num_days').addEventListener('input', calculateTotal);
document.getElementById('cost_per_participant').addEventListener('input', calculateTotal);
document.querySelectorAll('input[name="food_items[]"], input[name="other_resources[]"], input[name="rooms[]"]').forEach(el => el.addEventListener('change', calculateTotal));

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

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