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

// ================= BOOKING INFO =================
$booking_id = intval($_GET['booking_id'] ?? 0);
if($booking_id <= 0){ die("<div class='alert alert-danger'>Invalid booking ID</div>"); }

$booking = $conn->query("SELECT * FROM conference_bookings WHERE id=$booking_id")->fetch_assoc();
if(!$booking){ die("<div class='alert alert-danger'>Booking not found</div>"); }

$attendees = intval($booking['attendees']);
$num_days = intval($booking['num_days']);
$username = $_SESSION['username'] ?? 'Guest';
?>

<div class="container mt-4">
      <button class="btn btn-secondary" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
    <style>
/* Base alert box styling */
.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin: 20px 0;
    position: relative;
    font-family: Arial, sans-serif;
    font-size: 16px;
    display: flex;
    align-items: center;
    gap: 10px;
    border-left: 6px solid;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    background-color: #fff5e6; /* light yellow */
    color: #92400e; /* dark orange */
    border-color: #f59e0b; /* orange border */
}

/* Close button */
.alert .close-btn {
    position: absolute;
    right: 15px;
    top: 50%;
    transform: translateY(-50%);
    background: transparent;
    border: none;
    font-size: 18px;
    cursor: pointer;
    color: inherit;
}
</style>
</head>
<body>

<!-- Success Alert -->
<div class="alert alert-warning">
      ⚠️ <strong>Note!</strong>Separate the production of refreshments and meals. First Refreshments then the meals
    <button class="close-btn" onclick="this.parentElement.style.display='none';">&times;</button>
</div>
    <div class="d-flex justify-content-between align-items-center mb-3">

        <h4><i class="fa fa-utensils text-success"></i> Meal & Refreshment Production for Booking #<?= $booking_id ?></h4>
  
    </div>

    <p><strong>Attendees:</strong> <?= $attendees ?> | <strong>Days:</strong> <?= $num_days ?></p>
    <hr>

    <form action="print_estimations.php" method="post" target="_blank">

        <input type="hidden" name="booking_id" value="<?= $booking_id ?>">
        <input type="hidden" name="people_count" id="hiddenPeopleCount" value="<?= $attendees ?>">
        <input type="hidden" name="days_count" id="hiddenDaysCount" value="<?= $num_days ?>">

        <!-- ======= Select Meals & Refreshments ======= -->
        <h5>Select Items to Produce</h5>

        <div class="mb-3">
            <h6>Meals</h6>
            <?php
            $meals = $conn->query("SELECT * FROM conference_meals WHERE is_active=1 ORDER BY meal_name");
            while($m = $meals->fetch_assoc()):
            ?>
                <div class="form-check">
                    <input class="form-check-input item-checkbox" type="checkbox" 
                           name="selected_items[]" 
                           value="meal_<?= $m['id'] ?>" 
                           data-type="meal" 
                           data-name="<?= htmlspecialchars($m['meal_name']) ?>" 
                           data-price="<?= $m['price'] ?>" 
                           data-meal-name="<?= htmlspecialchars($m['meal_name']) ?>" 
                           id="meal_<?= $m['id'] ?>">
                    <label class="form-check-label" for="meal_<?= $m['id'] ?>">
                        <?= $m['meal_name'] ?> (MK <?= number_format($m['price'],2) ?> per person)
                    </label>
                </div>
            <?php endwhile; ?>
        </div>

        <div class="mb-3">
            <h6>Refreshments</h6>
            <?php
            $refresh = $conn->query("SELECT * FROM conference_refreshments WHERE is_active=1 ORDER BY item_name");
            while($r = $refresh->fetch_assoc()):
            ?>
                <div class="form-check">
                    <input class="form-check-input item-checkbox" type="checkbox" 
                           name="selected_items[]" 
                           value="refresh_<?= $r['id'] ?>" 
                           data-type="refresh" 
                           data-name="<?= htmlspecialchars($r['item_name']) ?>" 
                           data-price="<?= $r['price'] ?>" 
                           id="refresh_<?= $r['id'] ?>">
                    <label class="form-check-label" for="refresh_<?= $r['id'] ?>">
                        <?= $r['item_name'] ?> (MK <?= number_format($r['price'],2) ?> per person)
                    </label>
                </div>
            <?php endwhile; ?>
        </div>

        <div class="mb-3">
            <label>Number of People to Produce For:</label>
            <input type="number" id="peopleCount" class="form-control w-auto" value="<?= $attendees ?>" min="1">
        </div>

        <div class="mb-3">
            <label>Number of Days to Produce For:</label>
            <select id="daysCount" class="form-control w-auto">
                <?php
                for($d=1; $d<=$num_days; $d++){
                    echo "<option value='$d'>$d day".($d>1?'s':'')."</option>";
                }
                echo "<option value='all'>All ($num_days days)</option>";
                ?>
            </select>
        </div>

        <hr>
        <!-- ======= Production Plan Output ======= -->
        <div id="productionResult" class="mb-4"></div>

        <button type="submit" class="btn btn-primary mb-3">
            <i class="fa fa-print"></i> Generate Print Template
        </button>

        <hr>

        <!-- ======= Perishable Ingredients ======= -->
        <h5>Perishable Ingredients</h5>
        <table class="table table-bordered table-striped table-sm" id="perishablesTable">
            <thead class="table-dark">
                <tr>
                    <th>Select</th>
                    <th>#</th>
                    <th>Item</th>
                    <th>Qty per Person</th>
                    <th>Unit</th>
                    <th>Total Qty Needed</th>
                     <th>Unit Price(MWK)</th>
                     <th>Total Cost(MWK)</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $perishables = $conn->query("
                SELECT pp.id, p.name AS item_name, pp.qty_per_person, pp.unit_cost,pp.composition, p.unit 
                FROM perishable_parameters pp
                JOIN perishables p ON pp.perishable_id = p.id
                ORDER BY p.name
            ");
            $i=1;
            while($p = $perishables->fetch_assoc()):
                // Add data-type attribute for JS multiplier logic
                $type = strtolower($p['composition']) === 'refresh' ? 'refresh' : 'meal';
            ?>
             <tr data-type="<?= $p['composition']==2 ? 'refresh' : 'meal' ?>">
    <td>
        <input type="checkbox" 
               class="perishable-checkbox" 
               name="selected_perishables[]" 
               value="<?= $p['id'] ?>" 
               data-qty="<?= $p['qty_per_person'] ?>" 
               data-unit="<?= $p['unit_cost'] ?>">
    </td>
    <td><?= $i ?></td>
    <td><?= $p['item_name'] ?></td>
    <td><?= $p['qty_per_person'] ?></td>
    <td><?= $p['unit'] ?></td>
    <td class="total-qty">0</td>
    <td><?= number_format($p['unit_cost'], 2) ?></td>
    <td class="total-cost">0</td>
</tr>
            <?php $i++; endwhile; ?>
            </tbody>
        </table>

        <hr>

        <!-- ======= Meal Parameters ======= -->
        <h5>Meal Parameters (Conference Only)</h5>
       <table class="table table-bordered table-striped table-sm" id="mealParametersTable">
    <thead class="table-dark">
        <tr>
            <th>Select</th>
            <th>#</th>
            <th>Material</th>
            <th>Qty per Person</th>
            <th>Meal Type</th>
            <th>Total Qty Needed</th>
            <th>Unit Price(MWK)</th>
            <th>Total Cost(MWK)</th>
        </tr>
    </thead>
    <tbody>
    <?php
    $meal_params = $conn->query("
        SELECT mp.id, p.name AS material_name, mp.qty_per_people, mp.meal_type, p.buying_price
        FROM meal_parameters mp
        JOIN products p ON mp.material_id = p.id
        WHERE mp.meal_type='Conference'
        ORDER BY p.name
    ");
    $i=1;
    while($mp = $meal_params->fetch_assoc()):
    ?>
        <tr>
            <td>
                <input type="checkbox" 
                       class="meal-param-checkbox" 
                       name="selected_meal_params[]" 
                       value="<?= $mp['id'] ?>" 
                       data-qty="<?= $mp['qty_per_people'] ?>" 
                       data-price="<?= $mp['buying_price'] ?>">
            </td>
            <td><?= $i ?></td>
            <td><?= $mp['material_name'] ?></td>
            <td><?= $mp['qty_per_people'] ?></td>
            <td><?= $mp['meal_type'] ?></td>
            <td class="total-qty">0</td>
            <td><?= number_format($mp['buying_price'],2) ?></td>
            <td class="total-costs">0</td>
        </tr>
    <?php $i++; endwhile; ?>
    </tbody>
</table>
    </form>
</div>

<script>
// ================= DYNAMIC CALCULATION =================
const peopleInput = document.getElementById('peopleCount');
const daysSelect = document.getElementById('daysCount');
const itemCheckboxes = document.querySelectorAll('.item-checkbox');
const perishableCheckboxes = document.querySelectorAll('.perishable-checkbox');
const mealParamCheckboxes = document.querySelectorAll('.meal-param-checkbox');
const resultDiv = document.getElementById('productionResult');
const hiddenPeople = document.getElementById('hiddenPeopleCount');
const hiddenDays = document.getElementById('hiddenDaysCount');

// Round to 1 significant figure
function roundToOneSigFig(num) {
    if(num === 0) return 0;
    const exponent = Math.floor(Math.log10(Math.abs(num)));
    const factor = Math.pow(10, exponent);
    return Math.round(num / factor) * factor;
}

function updateProduction() {
    const peopleCount = parseInt(peopleInput.value || '0');
    if(peopleCount <= 0){
        resultDiv.innerHTML = "<div class='alert alert-warning'>Enter a valid number of people!</div>";
        return;
    }
    hiddenPeople.value = peopleCount;

    let daysValue = daysSelect.value === 'all' ? <?= $num_days ?> : parseInt(daysSelect.value);
    if(daysValue <= 0) daysValue = 1;
    hiddenDays.value = daysValue;

    resultDiv.innerHTML = `<h5>Production Plan for ${peopleCount} People for ${daysValue} day(s)</h5>`;
    let totalCost = 0;
    let ul = document.createElement('ul');

    // ===== Meals & Refreshments =====
    const selectedMeals = Array.from(itemCheckboxes).filter(cb => cb.checked && cb.dataset.type==='meal');

    // Check if Conference Package is selected
    const isConferencePackage = selectedMeals.some(cb => cb.dataset.name.toLowerCase() === 'conference package');
    const mealMultiplier = isConferencePackage ? 3 : (selectedMeals.length || 1);

    const selectedRefreshments = Array.from(itemCheckboxes).filter(cb => cb.checked && cb.dataset.type==='refresh');
    const hasMorning = selectedRefreshments.some(cb => cb.dataset.name.toLowerCase() === 'morning refreshments');
    const hasAfternoon = selectedRefreshments.some(cb => cb.dataset.name.toLowerCase() === 'afternoon refreshments');
    const refreshMultiplier = (hasMorning && hasAfternoon) ? 2 : 1;

    // ===== Loop through all items =====
    itemCheckboxes.forEach(cb=>{
        if(cb.checked){
            const type = cb.dataset.type;
            const name = cb.dataset.name;
            const price = parseFloat(cb.dataset.price);

            let effectiveMultiplier = type === 'meal' ? mealMultiplier : refreshMultiplier;

            let itemCost = price * peopleCount * daysValue * effectiveMultiplier;
            itemCost = roundToOneSigFig(itemCost);
            totalCost += itemCost;

            let li = document.createElement('li');
            li.innerText = `${type==='meal'?'Meal':'Refreshment'}: ${name} × ${peopleCount} × ${daysValue} day(s) × ${effectiveMultiplier} = MK ${itemCost.toLocaleString()}`;
            ul.appendChild(li);
        }
    });

    // ===== Perishables =====
  // ===== Perishables =====
perishableCheckboxes.forEach(cb=>{
    const tr = cb.closest('tr');
    const qtyPerPerson = parseFloat(cb.dataset.qty);
    const unitCost = parseFloat(cb.dataset.unit); // <- correct
    const totalQtyTd = tr.querySelector('.total-qty');
    const totalCostTd = tr.querySelector('.total-cost');

    const perishableType = tr.dataset.type; // meal or refresh
    const multiplier = perishableType === 'refresh' ? refreshMultiplier : mealMultiplier;

    const totalQty = cb.checked ? (qtyPerPerson * peopleCount * daysValue * multiplier) : 0;
    totalQtyTd.innerText = totalQty;

    const totalCost = cb.checked ? (unitCost * peopleCount * daysValue) : 0;
    totalCostTd.innerText = totalCost.toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2});
});

    // ===== Meal Parameters =====
// ===== Meal Parameters =====
mealParamCheckboxes.forEach(cb => {
    const tr = cb.closest('tr');
    const qtyPerPerson = parseFloat(cb.dataset.qty);
    const unitPrice = parseFloat(cb.dataset.price); // <-- buying price
    const totalQtyTd = tr.querySelector('.total-qty');
    const totalCostTd = tr.querySelector('.total-costs');

    // totalQty considers mealMultiplier if needed
    const totalQty = cb.checked ? (qtyPerPerson * peopleCount * daysValue * mealMultiplier) : 0;
    totalQtyTd.innerText = totalQty.toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2});

    // Corrected: totalCost = totalQty * unitPrice
    const totalCost = cb.checked ? (totalQty * unitPrice) : 0;
    totalCostTd.innerText = totalCost.toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2});
});

    resultDiv.appendChild(ul);
    let totalP = document.createElement('p');
    totalP.className = 'fw-bold mt-2';
    totalP.innerText = "Total Cost: MK " + roundToOneSigFig(totalCost).toLocaleString();
    resultDiv.appendChild(totalP);
}

// Event listeners
peopleInput.addEventListener('input', updateProduction);
daysSelect.addEventListener('change', updateProduction);
itemCheckboxes.forEach(cb => cb.addEventListener('change', updateProduction));
perishableCheckboxes.forEach(cb => cb.addEventListener('change', updateProduction));
mealParamCheckboxes.forEach(cb => cb.addEventListener('change', updateProduction));

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