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

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

<div class="container mt-4">

<button class="btn btn-secondary btn-custom" onclick="history.back()">
    <i class="fa fa-arrow-left"></i> Back
</button>
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>

    <h4>Meal Ingredients Dashboard</h4>
    <hr>

    <!-- ======= FILTER SEARCH ======= -->
    <div class="row g-2 mb-3">
        <div class="col-md-4">
            <input type="text" id="searchMeal" class="form-control" placeholder="Search Meal...">
        </div>
    </div>
<a href="meals.php" class="btn btn-success mb-3">
    <i class="fa fa-utensils"></i> Manage Meals
</a>

    <!-- ======= MEAL ASSIGNMENT BUTTON ======= -->
    <button class="btn btn-success mb-3" type="button" data-bs-toggle="collapse" data-bs-target="#assignIngredientsForm">
        <i class="fa fa-plus"></i> Assign Ingredients to Meal
    </button>

    <!-- ======= ASSIGN INGREDIENTS FORM ======= -->
    <div class="collapse mb-4" id="assignIngredientsForm">
        <form id="assignForm" class="row g-2">
            <div class="col-md-3">
                <select id="mealSelect" class="form-control" required>
                    <option value="">-- Select Meal --</option>
                    <?php
                    $res = $conn->query("
                        SELECT m.id AS meal_id, m.meal_name
                        FROM meals m
                        ORDER BY m.meal_name ASC
                    ");
                    while($row = $res->fetch_assoc()){
                        echo "<option value='{$row['meal_id']}'>{$row['meal_name']}</option>";
                    }
                    ?>
                </select>
            </div>

            <div class="col-md-3">
                <select id="mealTypeSelect" class="form-control" required>
                    <option value="">-- Select Type --</option>
                    <option value="Walk-in">Walk-in</option>
                    <option value="Conference">Conference</option>
                </select>
            </div>

            <div class="col-md-4">
                <select id="ingredientSelect" multiple class="form-control" size="5">
                    <?php
                    $ing_res = $conn->query("
                        SELECT mp.id, p.name AS material_name
                        FROM meal_parameters mp
                        LEFT JOIN products p ON p.id = mp.material_id
                        ORDER BY p.name ASC
                    ");
                    while($r=$ing_res->fetch_assoc()){
                        echo "<option value='{$r['id']}'>{$r['material_name']}</option>";
                    }
                    ?>
                </select>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-primary w-100" onclick="assignIngredients()">
                    <i class="fa fa-paper-plane"></i> Assign Selected Ingredients
                </button>
            </div>
        </form>
    </div>

    <!-- ======= MEALS WITH ASSIGNED INGREDIENTS TABLE ======= -->
    <table class="table table-bordered table-striped table-sm">
        <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Meal Name</th>
                <th>Type</th>
                <th>Ingredients</th>
                
                <th>Guests</th>
                <th>Total Qty</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="mealTableBody"></tbody>
    </table>

    <div id="message" class="mt-2"></div>
</div>

<script>
// Load meals with assigned ingredients
function loadMealDashboard(){
    fetch('meal_dashboard_action.php', {
        method:'POST',
        body: new URLSearchParams({action:'list'})
    })
    .then(res=>res.json())
    .then(data=>{
        let tbody = document.getElementById('mealTableBody');
        tbody.innerHTML = '';
        if(data.length===0){
            tbody.innerHTML='<tr><td colspan="8" class="text-center">No meals assigned yet</td></tr>';
            return;
        }

        let i=1;
        data.forEach(meal=>{
            let ingredients = meal.ingredients.map(i=>i.material_name).join(', ');
            let qtyPerPerson = meal.ingredients.map(i=>i.qty_per_people).join(', ');
            let guests = meal.ingredients.map(i=>i.people_count).join(', ');
            let totalQty = meal.ingredients.map(i=>(i.qty_per_people*i.people_count).toFixed(2)).join(', ');

            tbody.innerHTML += `
                <tr>
                    <td>${i}</td>
                    <td>${meal.meal_name}</td>
                    <td>${meal.meal_type}</td>
                    <td>${ingredients}</td>
                   
                    <td>${guests}</td>
                    <td>${totalQty}</td>
                    <td>
                        ${meal.ingredients.map(i=>`<button class="btn btn-danger btn-sm me-1 mb-1" onclick="removeIngredient(${i.id})">
                            <i class="fa fa-trash"></i> ${i.material_name}</button>`).join('')}
                    </td>
                </tr>
            `;
            i++;
        });
    });
}

// Assign ingredients to meal
function assignIngredients(){
    let meal_id = document.getElementById('mealSelect').value;
    let meal_type = document.getElementById('mealTypeSelect').value;
    let selected = Array.from(document.getElementById('ingredientSelect').selectedOptions).map(o=>o.value);

    if(!meal_id){ alert('Select a meal'); return; }
    if(!meal_type){ alert('Select a meal type'); return; }
    if(selected.length===0){ alert('Select at least one ingredient'); return; }

    fetch('meal_dashboard_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=>{
        document.getElementById('message').innerText = data;
        setTimeout(()=>document.getElementById('message').innerText='',3000);
        loadMealDashboard();
    });
}

// Remove ingredient from meal
function removeIngredient(assign_id){
    if(!confirm('Remove this ingredient?')) return;
    fetch('meal_dashboard_action.php', {
        method:'POST',
        body: new URLSearchParams({action:'remove', assign_id:assign_id})
    })
    .then(res=>res.text())
    .then(data=>{
        document.getElementById('message').innerText = data;
        setTimeout(()=>document.getElementById('message').innerText='',3000);
        loadMealDashboard();
    });
}

// Filter meals by search
document.getElementById('searchMeal').addEventListener('keyup', function(){
    let val = this.value.toLowerCase();
    document.querySelectorAll('#mealTableBody tr').forEach(tr=>{
        tr.style.display = tr.children[1].innerText.toLowerCase().includes(val) ? '' : 'none';
    });
});

loadMealDashboard();
</script>
