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

$username = $_SESSION['username'] ?? 'Guest';
$user_id  = $_SESSION['user_id'] ?? 0;
?>

<div class="container mt-4">

<button class="btn btn-secondary mb-3" onclick="history.back()">
    <i class="fa fa-arrow-left"></i> Back
</button>

<div class="welcome-msg mb-3">
    <i class="fa fa-user-circle"></i>
    Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
</div>

<h4>Produce Meal</h4>
<hr>

<div class="row mb-4">
    <div class="col-md-3">
        <label class="form-label fw-bold">Select Meal:</label>
        <select id="mealSelect" class="form-select" required>
            <option value="">-- Select Meal --</option>
            <?php
            $res = $conn->query("SELECT id, meal_name, category FROM meals ORDER BY category ASC, meal_name ASC");
            while($row = $res->fetch_assoc()){
                echo "<option value='{$row['id']}'>{$row['category']} → {$row['meal_name']}</option>";
            }
            ?>
        </select>
    </div>
    <div class="col-md-3">
        <label class="form-label fw-bold">Meal Type:</label>
        <select id="mealType" class="form-select" required>
            <option value="">-- Select Type --</option>
            <option value="Walk-in">Walk-in</option>
            <option value="Conference">Conference</option>
        </select>
    </div>
    <div class="col-md-2">
        <label class="form-label fw-bold">Number of People:</label>
        <input type="number" id="peopleCount" class="form-control" min="1" placeholder="Enter number of guests" required>
    </div>
    <div class="col-md-2 d-flex align-items-end">
        <button class="btn btn-success w-100" onclick="calculateIngredients()">
            <i class="fa fa-calculator"></i> Calculate
        </button>
    </div>
</div>

<h5>Required Ingredients</h5>
<table class="table table-bordered table-striped table-hover table-sm">
    <thead class="table-dark">
        <tr>
            <th>Material</th>
            <th>Type</th>
            <th>Number of People</th>
            <th>Total Qty Needed</th>
            <th>Available Stock</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody id="ingredientsTableBody">
        <tr><td colspan="6" class="text-center">Select a meal, type, and number of people</td></tr>
    </tbody>
    <tfoot>
        <tr>
            <th colspan="3" class="text-end">Grand Total:</th>
            <th id="grandTotal">0</th>
            <th id="grandAvailable"></th>
            <th></th>
        </tr>
    </tfoot>
</table>

<div class="mt-3 d-flex gap-2">
    <button id="saveProductionBtn" class="btn btn-primary" onclick="saveAndPrintProduction()" disabled>
        <i class="fa fa-print"></i> Save & Generate Requisition
    </button>
</div>

<div id="message" class="alert alert-success d-none mt-3"></div>
</div>

<script>
let currentIngredients = [];

function showMessage(msg){
    let el = document.getElementById('message');
    el.innerText = msg;
    el.classList.remove('d-none');
    setTimeout(()=>el.classList.add('d-none'),3000);
}

// Calculate ingredients & check stock
function calculateIngredients(){
    let meal_id = document.getElementById('mealSelect').value;
    let meal_type = document.getElementById('mealType').value;
    let peopleCount = parseInt(document.getElementById('peopleCount').value);

    if(!meal_id){ alert('Select a meal'); return; }
    if(!meal_type){ alert('Select meal type'); return; }
    if(!peopleCount || peopleCount<1){ alert('Enter valid number of people'); return; }

    fetch('assign_to_meal_action.php',{
        method:'POST',
        body:new URLSearchParams({action:'list', meal_id: meal_id, meal_type: meal_type})
    })
    .then(res=>res.json())
    .then(data=>{
        currentIngredients = data;
        let tbody = document.getElementById('ingredientsTableBody');
        let grandTotal = 0;
        tbody.innerHTML = '';

        if(data.length===0){
            tbody.innerHTML='<tr><td colspan="6" class="text-center">No ingredients assigned to this meal/type</td></tr>';
            document.getElementById('grandTotal').innerText='0';
            document.getElementById('saveProductionBtn').disabled = true;
            return;
        }

        let canProduce = true;

        data.forEach(row=>{
            row.total_qty = (row.qty_per_people * peopleCount).toFixed(2);
            grandTotal += parseFloat(row.total_qty);

            let availableQty = row.available_qty ?? 0;
            let inStock = availableQty >= row.total_qty ? 'Yes' : 'No';
            if(availableQty < row.total_qty) canProduce = false;

            let inStockClass = inStock === 'Yes' ? 'text-success' : 'text-danger';

            tbody.innerHTML += `<tr>
                <td>${row.material_name}</td>
                <td>${row.meal_type}</td>
                <td>${peopleCount}</td>
                <td>${row.total_qty}</td>
                <td>${availableQty}</td>
                <td class="${inStockClass}">${inStock}</td>
            </tr>`;
        });

        document.getElementById('grandTotal').innerText = grandTotal.toFixed(2);
        document.getElementById('saveProductionBtn').disabled = !canProduce;
        if(!canProduce) showMessage("Cannot produce meal. Insufficient stock for one or more items!");
    });
}

// Save production and reduce stock
function saveAndPrintProduction(){
    let meal_id = document.getElementById('mealSelect').value;
    let meal_type = document.getElementById('mealType').value;
    let peopleCount = parseInt(document.getElementById('peopleCount').value);

    if(!meal_id || !meal_type || !peopleCount || currentIngredients.length===0){ alert('Calculate ingredients first'); return; }

    fetch('save_production.php',{
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({
            meal_id: meal_id,
            meal_type: meal_type,
            number_of_people: peopleCount,
            ingredients: currentIngredients
        })
    })
    .then(res=>res.json())
    .then(data=>{
        if(data.success){
            showMessage('Meal production saved and stock updated!');

            let mealName = document.getElementById('mealSelect').selectedOptions[0].text;
            let html = `<html><head><title>Meal Requisition</title>
                <style>
                    body{font-family:Arial,sans-serif;padding:20px;}
                    h2{text-align:center;}
                    table{border-collapse:collapse;width:100%;margin-top:15px;}
                    th,td{border:1px solid #333;padding:8px;text-align:left;}
                    th{background:#333;color:white;}
                    tfoot th{background:#f0f0f0;color:#000;}
                </style>
            </head><body>
                <h2>Meal Requisition</h2>
                <p><strong>Meal:</strong> ${mealName}</p>
                <p><strong>Type:</strong> ${meal_type}</p>
                <p><strong>Number of People:</strong> ${peopleCount}</p>
                <table>
                    <thead>
                        <tr><th>Material</th><th>Type</th><th>Number of People</th><th>Total Qty</th><th>Available</th></tr>
                    </thead>
                    <tbody>`;

            currentIngredients.forEach(row=>{
                html += `<tr>
                    <td>${row.material_name}</td>
                    <td>${row.meal_type}</td>
                    <td>${peopleCount}</td>
                    <td>${row.total_qty}</td>
                    <td>${row.available_qty}</td>
                </tr>`;
            });

            html += `</tbody>
                    <tfoot>
                        <tr><th colspan="3" class="text-end">Grand Total:</th><th>${document.getElementById('grandTotal').innerText}</th><th></th></tr>
                    </tfoot>
                </table>
                <p><strong>Generated On:</strong> ${new Date().toLocaleString()}</p>
                <p><strong>Prepared By:</strong> <?= htmlspecialchars($username) ?></p>
            </body></html>`;

            let w = window.open();
            w.document.write(html);
            w.print();
        } else {
            showMessage('Error: '+data.error);
        }
    });
}
</script>