<?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;
}

$attendees = intval($booking['attendees']);
$num_days = intval($booking['num_days']);

// ===============================
// 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']); 
    $food_items_post = $_POST['food_items'] ?? [];
    $other_resources_post = $_POST['other_resources'] ?? [];
    $selected_acc_rooms = $_POST['rooms'] ?? [];

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

    if (!empty($food_items_post)) {
        $stmt_food = $conn->prepare("INSERT INTO conference_booking_resources (booking_id, resource_type, resource_id, quantity) VALUES (?, ?, ?, 1)");

        foreach ($food_items_post 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 {
                // Refreshment
                $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_post)) {
        $ids = implode(",", array_map('intval', $other_resources_post));
        $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_post as $res_id) {
            $res_id_var = intval($res_id);
            $stmt_other->bind_param("ii", $booking_id, $res_id_var);
            $stmt_other->execute();
        }
    }

    // ================================
    // ACCOMMODATION ROOMS
    // ================================
    $accommodation_total = 0;
    if (!empty($selected_acc_rooms)) {
        $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);
            $res = $conn->query("SELECT price FROM rooms WHERE id=$room_id_var LIMIT 1");
            $room_price = floatval($res->fetch_assoc()['price'] ?? 0);
            $accommodation_total += $room_price * $num_days;

            $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;
}

// ===============================
// FETCH BOOKING RESOURCES FOR DISPLAY
// ===============================
$res_stmt = $conn->prepare("
    SELECT cbr.resource_type, cbr.resource_id,
           cm.meal_name, cm.price AS meal_price,
           crf.item_name AS refreshment_name, crf.price AS refreshment_price,
           cr.resource_name, cr.unit_cost
    FROM conference_booking_resources cbr
    LEFT JOIN conference_meals cm ON (cbr.resource_type='FOOD' AND cbr.resource_id=cm.id)
    LEFT JOIN conference_refreshments crf ON (cbr.resource_type='REFRESHMENT' AND cbr.resource_id=crf.id)
    LEFT JOIN conference_resources cr ON (cbr.resource_type='OTHER' AND cbr.resource_id=cr.id)
    WHERE cbr.booking_id=?
");
$res_stmt->bind_param("i", $booking_id);
$res_stmt->execute();
$res_result = $res_stmt->get_result();

$food_grouped = [];
$refresh_grouped = [];
$other_items = [];
$total_food_cost = 0;
$total_refreshment_cost = 0;
$total_other_cost = 0;

while($row = $res_result->fetch_assoc()) {
    // Meals
    if($row['resource_type']=='FOOD' && $row['meal_name']){
        $id = $row['resource_id'];
        $food_grouped[$id] = ['name'=>$row['meal_name'],'price'=>$row['meal_price']];
        $total_food_cost += $row['meal_price'] * $attendees * $num_days;
    }

    // Refreshments
    if($row['resource_type']=='REFRESHMENT' && $row['refreshment_name']){
        $id = $row['resource_id'];
        $refresh_grouped[$id] = ['name'=>$row['refreshment_name'],'price'=>$row['refreshment_price']];
        $total_refreshment_cost += $row['refreshment_price'] * $attendees * $num_days;
    }

    // Other
    if($row['resource_type']=='OTHER' && $row['resource_name']){
        $cost = $row['unit_cost'];
        $other_items[] = "{$row['resource_name']} - MK ".number_format($cost,2);
        $total_other_cost += $cost;
    }
}

// ===============================
// FETCH ROOMS FOR DISPLAY
// ===============================
$rooms_stmt = $conn->prepare("
    SELECT r.room_type, r.capacity, r.price
    FROM conference_booking_accommodation cba
    JOIN rooms r ON cba.room_id=r.id
    WHERE cba.booking_id=?
");
$rooms_stmt->bind_param("i",$booking_id);
$rooms_stmt->execute();
$rooms_result = $rooms_stmt->get_result();

$rooms_list = [];
$total_room_cost = 0;
$added_rooms = [];
while($room = $rooms_result->fetch_assoc()){
    $room_key = $room['room_type'].'_'.$room['capacity']; // unique key
    if(!isset($added_rooms[$room_key])){
        $cost = $room['price'] * $num_days;
        $rooms_list[] = "{$room['room_type']} (Capacity: {$room['capacity']}) - MK ".number_format($cost,2);
        $total_room_cost += $cost;
        $added_rooms[$room_key] = true;
    }
}

// ===============================
// TOTALS
// ===============================
$conference_room_total = $booking['room_price'] * $num_days;
$grand_total = $conference_room_total + $total_food_cost + $total_refreshment_cost + $total_other_cost;
?>

<div class="container mt-4">
    <h3>View Conference Booking #<?= $booking['id'] ?></h3>
    <hr>
    <strong>Client:</strong> <?= htmlspecialchars($booking['client_name']) ?><br>
    <strong>Attendees:</strong> <?= $attendees ?><br>
    <strong>Number of Days:</strong> <?= $num_days ?><br>
    <strong>Conference Room Price:</strong> MK <?= number_format($booking['room_price'],2) ?><br>
    <strong>Conference Room Total:</strong> MK <?= number_format($conference_room_total,2) ?><br>
    <hr>

    <!-- ================= Buttons ================= -->
    <div class="mb-3">
        <?php if($booking['status']=='PENDING'): ?>
            <a href="edit_conference_booking.php?booking_id=<?= $booking['id'] ?>" class="btn btn-warning me-2">✏️ Edit Booking</a>
            <form method="POST" style="display:inline;">
                <input type="hidden" name="num_days" value="<?= $num_days ?>">
                <input type="hidden" name="room_price" value="<?= $booking['room_price'] ?>">
                <button type="submit" name="confirm_booking" class="btn btn-success">✅ Confirm Booking</button>
            </form>
        <?php else: ?>
            <p class="text-info fw-bold">Booking status: <?= htmlspecialchars($booking['status']) ?></p>
        <?php endif; ?>
    </div>

    <h5>🍽️ Meals</h5>
    <?php if($food_grouped): ?>
        <ul>
            <?php foreach($food_grouped as $f):
                $cost = $f['price']*$attendees*$num_days;
                echo "<li>{$f['name']} (MK {$f['price']} × {$attendees} × {$num_days}) - MK ".number_format($cost,2)."</li>";
            endforeach; ?>
        </ul>
        <p class="fw-bold text-success">Total Meals: MK <?= number_format($total_food_cost,2) ?></p>
    <?php else: ?>
        <p class="text-muted">No meals assigned.</p>
    <?php endif; ?>

    <h5>☕ Refreshments</h5>
    <?php if($refresh_grouped): ?>
        <ul>
            <?php foreach($refresh_grouped as $r):
                $cost = $r['price']*$attendees*$num_days;
                echo "<li>{$r['name']} (MK {$r['price']} × {$attendees} × {$num_days}) - MK ".number_format($cost,2)."</li>";
            endforeach; ?>
        </ul>
        <p class="fw-bold text-success">Total Refreshments: MK <?= number_format($total_refreshment_cost,2) ?></p>
    <?php else: ?>
        <p class="text-muted">No refreshments assigned.</p>
    <?php endif; ?>

    <h5>📦 Other Resources</h5>
    <?php if($other_items): ?>
        <ul><?php foreach($other_items as $o) echo "<li>$o</li>"; ?></ul>
        <p class="fw-bold text-success">Total Resources: MK <?= number_format($total_other_cost,2) ?></p>
    <?php else: ?><p class="text-muted">No resources assigned.</p><?php endif; ?>
<?php
  $rooms_result = $conn->query("SELECT r.room_type, r.capacity, r.price
                              FROM conference_booking_accommodation cba
                              JOIN rooms r ON cba.room_id=r.id
                              WHERE cba.booking_id=$booking_id");

$total_room_cost = 0;
?>
<h5>🛏️ Accommodation</h5>
<ul>
<?php while($room = $rooms_result->fetch_assoc()): 
        $room_cost = $room['price'] * $num_days;
        $total_room_cost += $room_cost;
?>
    <li><?= $room['room_type'] ?> (Capacity: <?= $room['capacity'] ?>) - MK <?= $room['price'] ?> × <?= $num_days ?> = MK <?= number_format($room_cost,2) ?></li>
<?php endwhile; ?>
</ul>
<p class="fw-bold text-success">Total Rooms: MK <?= number_format($total_room_cost,2) ?></p>

    <h4 class="text-primary mt-3">💰 Grand Total: MK <?= number_format($grand_total + $total_room_cost,2) ?></h4>
</div>


    <!-- ACTION BUTTONS -->
    <div class="mt-3 d-flex gap-2 flex-wrap">
    <a href="conference_bookings.php" class="btn btn-secondary">⬅️ Back to Bookings</a>

      <a href="discount_conference_booking.php?booking_id=<?= $booking['id'] ?>" class="btn btn-primary">Discount</a>

    <?php if($booking['status']=='PENDING' || $booking['status']=='CONFIRMED'): ?>
        <a href="edit_conference_booking.php?booking_id=<?= $booking['id'] ?>" class="btn btn-primary">✏️ Edit</a>
        <a href="#" 
           class="btn btn-danger"
           onclick="return confirm('');"></a>
    <?php endif; ?>

    <a href="generate_invoice.php?booking_id=<?= $booking['id'] ?>" class="btn btn-success">
        🧾 Print Invoice
    </a>
   

     <a href="meal_production.php?booking_id=<?= $booking['id'] ?>" class="btn btn-warning">
        💼 Allocate Meal
    </a>
</div>

   
</div>

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