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

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4><i class="fa fa-utensils text-success"></i> Walk-in Meal & Refreshment Production</h4>
        <button class="btn btn-secondary" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>
       
    </div>

    <form action="print_walkin_estimations_walk.php" method="post" target="_blank">
        <input type="hidden" name="days_count" value="1"> <!-- Default 1 day -->

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

        <!-- ======= Select Meals & Refreshments ======= -->
        <h5>Select Items to Produce</h5>
        <div class="mb-3">
            <h6>Meals</h6>
            <?php
            $meals = $conn->query("SELECT * FROM  restaurant_menu  WHERE is_active=1 ORDER BY 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['name']) ?>" data-price="<?= $m['price'] ?>" id="meal_<?= $m['id'] ?>">
                    <label class="form-check-label" for="meal_<?= $m['id'] ?>">
                        <?= $m['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>

        <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>Unit Price (MK)</th>
            <th>Composition (Each)</th>
            <th>Total Qty Needed</th>
            <th>Total Value (MK)</th>
        </tr>
    </thead>
    <tbody>
    <?php
    $perishables = $conn->query("
        SELECT pp.id, p.name AS item_name, pp.qty_per_person, pp.unit_cost AS unit_price, p.unit, pp.composition 
        FROM perishable_parameters pp
        JOIN perishables p ON pp.perishable_id = p.id
        ORDER BY p.name
    ");
    $i=1;
    while($p = $perishables->fetch_assoc()):
    ?>
        <tr>
            <td>
                <input type="checkbox" class="perishable-checkbox" 
                    name="selected_perishables[]" 
                    value="<?= $p['id'] ?>" 
                    data-qty="<?= $p['qty_per_person'] ?>" 
                    data-unitprice="<?= $p['unit_price'] ?>">
            </td>
            <td><?= $i ?></td>
            <td><?= $p['item_name'] ?></td>
            <td><?= $p['qty_per_person'] ?></td>
            <td><?= $p['unit'] ?></td>
            <td><?= number_format($p['unit_price'],2) ?></td>
            <td><?= $p['composition'] ?></td>
            <td class="total-qty">0</td>
            <td class="total-qty-unit">0</td>
        </tr>
    <?php $i++; endwhile; ?>
    </tbody>
</table>
        <hr>
        <!-- ======= Meal Parameters for Walk-in ======= -->
        <h5>Meal Ingredients (per Person)</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>Total Qty Needed</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $meal_params = $conn->query("
               SELECT mp.id, p.name AS material_name, mp.qty_per_people
FROM meal_parameters mp
JOIN products p ON mp.material_id = p.id
WHERE mp.meal_type = 'Walk-in'
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'] ?>"></td>
                    <td><?= $i ?></td>
                    <td><?= $mp['material_name'] ?></td>
                    <td><?= $mp['qty_per_people'] ?></td>
                    <td class="total-qty">0</td>
                </tr>
            <?php $i++; endwhile; ?>
            </tbody>
        </table>

    </form>
</div>

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

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

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

    // Meals & Refreshments
    itemCheckboxes.forEach(cb=>{
        if(cb.checked){
            const type = cb.dataset.type;
            const name = cb.dataset.name;
            const price = parseFloat(cb.dataset.price);
            const itemCost = price * peopleCount;
            totalCost += itemCost;

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

    // Perishables
  // Perishables
perishableCheckboxes.forEach(cb=>{
    const tr = cb.closest('tr');
    const qtyPerPerson = parseFloat(cb.dataset.qty);
    const unitPrice = parseFloat(cb.dataset.unitprice); // get unit price
    const totalQtyTd = tr.querySelector('.total-qty');
    const totalValueTd = tr.querySelector('.total-qty-unit'); // total value column

    // Calculate total quantity and total value
    const totalQty = cb.checked ? (qtyPerPerson * peopleCount) : 0;
    const totalValue = cb.checked ? (peopleCount * unitPrice) : 0;

    totalQtyTd.innerText = totalQty;
    totalValueTd.innerText = totalValue.toFixed(2); // display as 2 decimal places

    if(cb.checked){
        let li = document.createElement('li');
        li.innerText = `${tr.cells[2].innerText} → ${totalQty} ${tr.cells[4].innerText} | Total Value: MK ${totalValue.toFixed(2)}`;
        ul.appendChild(li);
    }
});
    // Meal Parameters
    mealParamCheckboxes.forEach(cb=>{
        const tr = cb.closest('tr');
        const qtyPerPerson = parseFloat(cb.dataset.qty);
        const totalTd = tr.querySelector('.total-qty');
        const totalQty = cb.checked ? (qtyPerPerson * peopleCount) : 0;
        totalTd.innerText = totalQty;

        if(cb.checked){
            let li = document.createElement('li');
            li.innerText = `${tr.cells[2].innerText} → ${totalQty}`;
            ul.appendChild(li);
        }
    });

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

// Event listeners
peopleInput.addEventListener('input', 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>