<?php
include 'includes/auth.php';
include 'db.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 ASSIGNED RESOURCES
// ===============================
$resources_stmt = $conn->prepare("
    SELECT cbr.resource_type, cbr.resource_id, cbr.quantity,
           rm.name AS food_name, rm.price AS food_price,
           cr.resource_name AS other_name
    FROM conference_booking_resources cbr
    LEFT JOIN restaurant_menu rm
        ON cbr.resource_type='FOOD' AND cbr.resource_id=rm.id
    LEFT JOIN conference_resources cr
        ON cbr.resource_type='OTHER' AND cbr.resource_id=cr.id
    WHERE cbr.booking_id=?
");
$resources_stmt->bind_param("i", $booking_id);
$resources_stmt->execute();
$res_result = $resources_stmt->get_result();

$food_items = [];
$other_items = [];
$total_food_cost = 0;

while ($row = $res_result->fetch_assoc()) {
    $qty = $row['quantity'] ?: 1;
    if ($row['resource_type'] == 'FOOD' && $row['food_name']) {
        // Correct: Multiply by quantity AND number of attendees
        $cost = $row['food_price'] * $qty * $booking['attendees'];
        $food_items[] = [
            'name' => $row['food_name'],
            'qty' => $qty,
            'price' => $row['food_price'],
            'total' => $cost
        ];
        $total_food_cost += $cost;
    } elseif ($row['resource_type'] == 'OTHER' && $row['other_name']) {
        $other_items[] = [
            'name' => $row['other_name'],
            'qty' => $row['quantity'] ?: 1
        ];
    }
}

// ===============================
// CALCULATE GRAND TOTAL
// ===============================
$booking_total = $booking['total_amount'] ?? 0;
$grand_total = $booking_total + $total_food_cost;
?>

<style>
.invoice-box{
    max-width:800px;
    margin:auto;
    padding:30px;
    border:1px solid #eee;
    box-shadow:0 0 10px rgba(0,0,0,0.15);
    font-size:14px;
    line-height:24px;
    font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    color:#555;
}
.invoice-box table{
    width:100%;
    line-height:inherit;
    text-align:left;
    border-collapse: collapse;
}
.invoice-box table td{
    padding:5px;
    vertical-align:top;
}
.invoice-box table tr.heading td{
    background:#eee;
    border-bottom:1px solid #ddd;
    font-weight:bold;
}
.invoice-box table tr.total td{
    border-top:2px solid #333;
    font-weight:bold;
}
@media print{
    .no-print{display:none;}
}
</style>

<div class="container mt-4">
<div class="invoice-box">
    <h3>🧾 Conference Booking Invoice</h3>
    <table>
        <tr>
            <td>
                <strong>Client:</strong> <?= htmlspecialchars($booking['client_name']) ?><br>
                <strong>Date:</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>Cost per Participant:</strong> MK <?= number_format($booking['cost_per_participant'],2) ?><br>
            </td>
            <td style="text-align:right;">
                <strong>Invoice #: </strong><?= $booking['id'] ?><br>
                <strong>Date: </strong><?= date('Y-m-d H:i') ?><br/>
                   <strong>TPIN:30798071</strong>
            </td>
        </tr>
    </table>

    <hr>

    <!-- CONFERENCE BOOKING FEE -->
    <h5>🏢 Conference Booking Fee</h5>
    <table cellpadding="0" cellspacing="0" border="1">
        <tr class="heading">
            <td>Description</td>
            <td>Amount (MK)</td>
        </tr>
        <tr>
            <td>Conference Booking (<?= $booking['attendees'] ?> attendees × <?= $booking['num_days'] ?> days × MK <?= number_format($booking['cost_per_participant'],2) ?>)</td>
            <td><?= number_format($booking_total,2) ?></td>
        </tr>
    </table>

    <!-- FOOD ITEMS -->
    <h5 class="mt-3">🍽️ Food Items</h5>
    <?php if(!empty($food_items)): ?>
        <table cellpadding="0" cellspacing="0" border="1">
            <tr class="heading">
                <td>Item</td>
                <td>Qty</td>
                <td>Unit Price (MK)</td>
                <td>Total (MK)</td>
            </tr>
            <?php foreach($food_items as $f): ?>
            <tr>
                <td><?= htmlspecialchars($f['name']) ?></td>
                <td><?= $f['qty'] ?> × <?= $booking['attendees'] ?></td>
                <td><?= number_format($f['price'],2) ?></td>
                <td><?= number_format($f['total'],2) ?></td>
            </tr>
            <?php endforeach; ?>
            <tr class="total">
                <td colspan="3" style="text-align:right;">Total Food Cost</td>
                <td><?= number_format($total_food_cost,2) ?></td>
            </tr>
        </table>
    <?php else: ?>
        <p class="text-muted">No food assigned.</p>
    <?php endif; ?>

    <!-- OTHER RESOURCES -->
    <h5 class="mt-3">📦 Other Conference Resources</h5>
    <?php if(!empty($other_items)): ?>
        <table cellpadding="0" cellspacing="0" border="1">
            <tr class="heading">
                <td>Resource</td>
                <td>Qty</td>
            </tr>
            <?php foreach($other_items as $r): ?>
            <tr>
                <td><?= htmlspecialchars($r['name']) ?></td>
                <td><?= $r['qty'] ?></td>
            </tr>
            <?php endforeach; ?>
        </table>
    <?php else: ?>
        <p class="text-muted">No resources assigned.</p>
    <?php endif; ?>

    <!-- GRAND TOTAL -->
    <p class="fw-bold text-end fs-5 mt-3">Grand Total: MK <?= number_format($grand_total,2) ?></p>

    <button onclick="window.print()" class="btn btn-success no-print">
        <i class="fa fa-print"></i> Print Invoice
    </button>
    <a href="conference_bookings.php" class="btn btn-secondary no-print">⬅️ Back to Bookings</a>
</div>
</div>

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