<?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();
$booking = $stmt->get_result()->fetch_assoc();

if (!$booking) {
    echo "<script>alert('Booking not found');window.location='conference_bookings.php';</script>";
    exit;
}

// ===============================
// FETCH OPTIONS
// ===============================
$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_list = $conn->query("SELECT * FROM rooms ORDER BY room_type");

// ===============================
// FETCH EXISTING RESOURCES & ROOMS
// ===============================
$existing_meals = [];
$existing_refreshments = [];
$existing_resources = [];
$existing_rooms = [];

$res_stmt = $conn->prepare("SELECT resource_type, resource_id FROM conference_booking_resources WHERE booking_id=?");
$res_stmt->bind_param("i", $booking_id);
$res_stmt->execute();
$res_result = $res_stmt->get_result();
while ($row = $res_result->fetch_assoc()) {
    if ($row['resource_type'] == 'FOOD') $existing_meals[] = $row['resource_id'];
    if ($row['resource_type'] == 'REFRESHMENT') $existing_refreshments[] = $row['resource_id'];
    if ($row['resource_type'] == 'OTHER') $existing_resources[] = $row['resource_id'];
}

$room_stmt = $conn->prepare("SELECT room_id FROM conference_booking_accommodation WHERE booking_id=?");
$room_stmt->bind_param("i", $booking_id);
$room_stmt->execute();
$room_result = $room_stmt->get_result();
while ($row = $room_result->fetch_assoc()) {
    $existing_rooms[] = $row['room_id'];
}

// ===============================
// HANDLE UPDATE
// ===============================
if (isset($_POST['update_booking'])) {
    $client_name = $_POST['client_name'];
    $attendees = intval($_POST['attendees']);
    $num_days = intval($_POST['num_days']);
    $room_price = floatval($_POST['room_price']);
    $food_items_post = $_POST['food_items'] ?? [];
    $refreshment_items_post = $_POST['refreshments'] ?? [];
    $other_resources_post = $_POST['other_resources'] ?? [];
    $selected_rooms_post = $_POST['rooms'] ?? [];

    // ===============================
    // UPDATE BOOKING BASIC INFO
    // ===============================
    $stmt = $conn->prepare("UPDATE conference_bookings SET client_name=?, attendees=?, num_days=?, room_price=? WHERE id=?");
    $stmt->bind_param("siidi", $client_name, $attendees, $num_days, $room_price, $booking_id);
    $stmt->execute();

    // ===============================
    // CLEAR OLD RESOURCES & ROOMS
    // ===============================
    $conn->query("DELETE FROM conference_booking_resources WHERE booking_id=$booking_id");
    $conn->query("DELETE FROM conference_booking_accommodation WHERE booking_id=$booking_id");

    // ===============================
    // INSERT FOOD
    // ===============================
    if (!empty($food_items_post)) {
        $stmt_food = $conn->prepare("INSERT INTO conference_booking_resources (booking_id, resource_type, resource_id, quantity) VALUES (?, 'FOOD', ?, 1)");
        foreach ($food_items_post as $f) {
            $stmt_food->bind_param("ii", $booking_id, $f);
            $stmt_food->execute();
        }
    }

    // ===============================
    // INSERT REFRESHMENTS
    // ===============================
    if (!empty($refreshment_items_post)) {
        $stmt_ref = $conn->prepare("INSERT INTO conference_booking_resources (booking_id, resource_type, resource_id, quantity) VALUES (?, 'REFRESHMENT', ?, 1)");
        foreach ($refreshment_items_post as $r) {
            $stmt_ref->bind_param("ii", $booking_id, $r);
            $stmt_ref->execute();
        }
    }

    // ===============================
    // INSERT OTHER RESOURCES
    // ===============================
    if (!empty($other_resources_post)) {
        $stmt_other = $conn->prepare("INSERT INTO conference_booking_resources (booking_id, resource_type, resource_id, quantity) VALUES (?, 'OTHER', ?, 1)");
        foreach ($other_resources_post as $res_id) {
            $stmt_other->bind_param("ii", $booking_id, $res_id);
            $stmt_other->execute();
        }
    }

    // ===============================
    // INSERT ROOMS
    // ===============================
    if (!empty($selected_rooms_post)) {
        $stmt_room = $conn->prepare("INSERT INTO conference_booking_accommodation (booking_id, room_id) VALUES (?, ?)");
        foreach ($selected_rooms_post as $room_id) {
            $stmt_room->bind_param("ii", $booking_id, $room_id);
            $stmt_room->execute();
        }
    }

    echo "<script>alert('✅ Booking updated successfully!');window.location='view_conference_booking.php?booking_id=$booking_id';</script>";
    exit;
}

?>

<div class="container mt-4">
    <h3>Edit Conference Booking #<?= $booking_id ?></h3>
    <form method="POST">
        <div class="mb-3">
            <label>Client Name</label>
            <input type="text" name="client_name" class="form-control" value="<?= htmlspecialchars($booking['client_name']) ?>" required>
        </div>

        <div class="mb-3">
            <label>Number of Attendees</label>
            <input type="number" name="attendees" class="form-control" value="<?= $booking['attendees'] ?>" required>
        </div>

        <div class="mb-3">
            <label>Number of Days</label>
            <input type="number" name="num_days" class="form-control" value="<?= $booking['num_days'] ?>" required>
        </div>

        <div class="mb-3">
            <label>Conference Room Price (per day)</label>
            <input type="number" name="room_price" class="form-control" value="<?= $booking['room_price'] ?>" step="0.01" required>
        </div>

        <h5>🍽️ Meals</h5>
        <?php while ($meal = $meal_list->fetch_assoc()): ?>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" name="food_items[]" value="<?= $meal['id'] ?>" 
                       <?= in_array($meal['id'], $existing_meals) ? 'checked' : '' ?>>
                <label class="form-check-label"><?= $meal['meal_name'] ?> - MK <?= number_format($meal['price'],2) ?></label>
            </div>
        <?php endwhile; ?>

        <h5>☕ Refreshments</h5>
        <?php while ($ref = $refreshments->fetch_assoc()): ?>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" name="refreshments[]" value="<?= $ref['id'] ?>"
                       <?= in_array($ref['id'], $existing_refreshments) ? 'checked' : '' ?>>
                <label class="form-check-label"><?= $ref['item_name'] ?> - MK <?= number_format($ref['price'],2) ?></label>
            </div>
        <?php endwhile; ?>

        <h5>📦 Other Resources</h5>
        <?php while ($res = $resources_list->fetch_assoc()): ?>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" name="other_resources[]" value="<?= $res['id'] ?>"
                       <?= in_array($res['id'], $existing_resources) ? 'checked' : '' ?>>
                <label class="form-check-label"><?= $res['resource_name'] ?> - MK <?= number_format($res['unit_cost'],2) ?></label>
            </div>
        <?php endwhile; ?>

        <h5>🛏️ Accommodation Rooms</h5>
        <?php while ($room = $rooms_list->fetch_assoc()): ?>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" name="rooms[]" value="<?= $room['id'] ?>"
                       <?= in_array($room['id'], $existing_rooms) ? 'checked' : '' ?>>
                <label class="form-check-label"><?= $room['room_type'] ?> (Capacity: <?= $room['capacity'] ?>) - MK <?= number_format($room['price'],2) ?></label>
            </div>
        <?php endwhile; ?>

        <button type="submit" name="update_booking" class="btn btn-success mt-3">💾 Update Booking</button>
        <a href="view_conference_booking.php?booking_id=<?= $booking_id ?>" class="btn btn-secondary mt-3">⬅ Back</a>
    </form>
</div>

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