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

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

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

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

    <h4>Assign Ingredients to Meal</h4>
    <hr>

    <!-- ====== SELECT MEAL ====== -->
    <div class="mb-3">
        <label for="mealSelect" class="form-label fw-bold">Select Meal:</label>
        <select id="mealSelect" class="form-select w-50" 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>

    <!-- ====== SELECT MEAL TYPE ====== -->
    <div class="mb-4">
        <label for="mealTypeSelect" class="form-label fw-bold">Select Meal Type:</label>
        <select id="mealTypeSelect" class="form-select w-50" required>
            <option value="">-- Select Type --</option>
            <option value="Walk-in">Walk-in</option>
            <option value="Conference">Conference</option>
        </select>
    </div>

    <!-- ====== AVAILABLE INGREDIENTS ====== -->
    <h5>Available Ingredients</h5>
    <table class="table table-bordered table-striped table-hover table-sm">
        <thead class="table-dark">
            <tr>
                <th style="width:5%;">Select</th>
                <th>Material</th>
                <th>Qty per person</th>
                <th>Number of Guests</th>
                <th>Total Qty</th>
            </tr>
        </thead>
        <tbody id="ingredientsTableBody"></tbody>
    </table>
    <button class="btn btn-success mb-4" onclick="assignIngredients()">
        <i class="fa fa-check"></i> Assign Selected Ingredients
    </button>

    <!-- ====== CURRENTLY ASSIGNED ====== -->
    <h5>Currently Assigned 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>Qty per person</th>
                <th>Number of Guests</th>
                <th>Total Qty</th>
                <th style="width:10%;">Action</th>
            </tr>
        </thead>
        <tbody id="assignedTableBody"></tbody>
        <tfoot>
            <tr>
                <th colspan="4" class="text-end">Grand Total:</th>
                <th id="grandTotal">0</th>
                <th></th>
            </tr>
        </tfoot>
    </table>

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

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

// Load available ingredients
function loadIngredients(){
    fetch('meal_parameters_action.php', {method:'POST', body: new URLSearchParams({action:'list'})})
    .then(res=>res.json())
    .then(data=>{
        let tbody = document.getElementById('ingredientsTableBody');
        tbody.innerHTML = '';
        data.forEach(row=>{
            let totalQty = (row.qty_per_people*row.people_count).toFixed(2);
            tbody.innerHTML += `
                <tr>
                    <td><input type="checkbox" value="${row.id}"></td>
                    <td>${row.material_name}</td>
                    <td>${row.qty_per_people}</td>
                    <td>${row.people_count}</td>
                    <td>${totalQty}</td>
                </tr>
            `;
        });
    });
}

// Load assigned ingredients
function loadAssigned(meal_id){
    let meal_type = document.getElementById('mealTypeSelect').value;
    if(!meal_type){ return; } // only load if type selected

    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=>{
        let tbody = document.getElementById('assignedTableBody');
        let grandTotal = 0;
        tbody.innerHTML = '';
        if(data.length===0){
            tbody.innerHTML = '<tr><td colspan="6" class="text-center">No ingredients assigned yet</td></tr>';
        }
        data.forEach(row=>{
            let totalQty = (row.qty_per_people*row.people_count).toFixed(2);
            grandTotal += parseFloat(totalQty);
            tbody.innerHTML += `
                <tr>
                    <td>${row.material_name}</td>
                    <td>${row.meal_type}</td>
                    <td>${row.qty_per_people}</td>
                    <td>${row.people_count}</td>
                    <td>${totalQty}</td>
                    <td><button class="btn btn-sm btn-danger" onclick="removeAssigned(${row.id}, ${meal_id})"><i class="fa fa-trash"></i></button></td>
                </tr>
            `;
        });
        document.getElementById('grandTotal').innerText = grandTotal.toFixed(2);
    });
}

// On meal select or type change
document.getElementById('mealSelect').addEventListener('change', function(){ loadAssigned(this.value); });
document.getElementById('mealTypeSelect').addEventListener('change', function(){ 
    let meal_id = document.getElementById('mealSelect').value;
    if(meal_id) loadAssigned(meal_id);
});

// Assign selected ingredients
function assignIngredients(){
    let meal_id = document.getElementById('mealSelect').value;
    let meal_type = document.getElementById('mealTypeSelect').value;
    if(!meal_id || !meal_type){ alert('Select a meal and type first'); return; }

    let selected = Array.from(document.querySelectorAll('#ingredientsTableBody input[type="checkbox"]:checked')).map(c=>c.value);
    if(selected.length===0){ alert('Select at least one ingredient'); return; }

    fetch('assign_to_meal_action.php',{
        method:'POST',
        body: new URLSearchParams({
            action:'assign', 
            meal_id: meal_id, 
            meal_type: meal_type,
            parameter_ids:selected.join(',')
        })
    })
    .then(res=>res.text())
    .then(data=>{
        showMessage(data);
        loadAssigned(meal_id);
    });
}

// Remove assigned ingredient
function removeAssigned(param_id, meal_id){
    let meal_type = document.getElementById('mealTypeSelect').value;
    if(!meal_type) return;

    if(confirm('Remove this ingredient from meal?')){
        fetch('assign_to_meal_action.php',{
            method:'POST',
            body: new URLSearchParams({
                action:'remove', 
                meal_id:meal_id, 
                param_id:param_id,
                meal_type:meal_type
            })
        })
        .then(res=>res.text())
        .then(data=>{
            showMessage(data);
            loadAssigned(meal_id);
        });
    }
}

// Initial load
loadIngredients();
</script>
