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

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

<div class="container mt-4">
    <!-- ====== Welcome & Back Button ====== -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="welcome-msg">
            <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
        </div>
        <button class="btn btn-secondary" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
    </div>

    <h4>Meal Parameters (Per Person)</h4>
    <hr>

    <!-- ======= Filter by Meal Type ======= -->
    <div class="mb-3 d-flex flex-wrap gap-2 align-items-center">
        <div>
            <label>Filter by Meal Type:</label>
            <select id="filterMealType" class="form-control w-auto d-inline-block">
                <option value="">All Types</option>
                <option value="Walk-in">Walk-in</option>
                  <option value="Walk-in">Walk-in</option>
                <option value="Walk-in_Baking">Walk-in Baking</option>
                 <option value="Conference_Baking">Conference Baking</option>
            </select>
        </div>

        <div>
            <label>Search:</label>
            <input type="text" id="searchInput" placeholder="Search Material or Type" class="form-control w-auto d-inline-block">
        </div>
    </div>

    <!-- ======= ADD / EDIT FORM ======= -->
    <button class="btn btn-success mb-3" type="button" data-bs-toggle="collapse" data-bs-target="#mealFormCollapse">
        <i class="fa fa-plus"></i> Add / Edit Parameter
    </button>

    <div class="collapse mb-4" id="mealFormCollapse">
        <form id="mealForm" class="row g-2">
            <input type="hidden" name="action" value="add">
            <input type="hidden" name="edit_id" value="">

            <div class="col-md-3">
                <label>Material:
                    <select name="material_id" class="form-control" required>
                        <option value="">Select Material</option>
                        <?php
                        $res = $conn->query("SELECT id, name FROM products WHERE raw_materials = 'Yes' ORDER BY name ASC");
                        while($row = $res->fetch_assoc()){
                            echo "<option value='{$row['id']}'>{$row['name']}</option>";
                        }
                        ?>
                    </select>
                </label>
            </div>

            <div class="col-md-3">
                <label>Meal Type:
                    <select name="meal_type" class="form-control" required>
                        <option value="">Select Type</option>
                        <option value="Walk-in">Walk-in</option>
                        <option value="Conference">Conference</option>
                            <option value="Walk-in_Baking">Walk-in Baking</option>
                 <option value="Conference_Baking">Conference Baking</option>
                    </select>
                </label>
            </div>

            <div class="col-md-2">
                <label>Qty per Person:
                    <input type="number" name="qty_per_people" step="0.01" class="form-control" required>
                </label>
            </div>

            <div class="col-md-2">
                <label>Number of Guests:
                    <input type="number" name="people_count" class="form-control" required>
                </label>
            </div>

            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-primary me-2">
                    <i class="fa fa-save"></i> Save
                </button>
                <button type="button" class="btn btn-secondary" onclick="resetForm()">
                    <i class="fa fa-times"></i> Cancel
                </button>
            </div>
        </form>
    </div>

    <div id="message" class="mb-3"></div>

    <!-- ===== Export Button ===== -->
    <button class="btn btn-info mb-3" onclick="exportTableToExcel()">
        <i class="fa fa-file-excel"></i> Export to Excel
    </button>

    <!-- ======= EXISTING PARAMETERS TABLE ======= -->
    <table class="table table-bordered table-striped table-hover table-sm" id="parametersTable">
        <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Material</th>
                <th>Meal Type</th>
                <th>Qty per Person</th>
                <th>Number of Guests</th>
                <th>Total Qty</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="parametersTableBody"></tbody>
    </table>
</div>

<!-- ===== Include SheetJS ===== -->
<script src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>

<script>
// ===== Load Parameters =====
let allParameters = [];

function loadParameters(filterType=''){
    fetch('meal_parameters_action.php', {
        method: 'POST',
        body: new URLSearchParams({action: 'list'})
    })
    .then(res => res.json())
    .then(data => {
        allParameters = data;
        renderTable(filterType, document.getElementById('searchInput').value);
    });
}

// ===== Render Table =====
function renderTable(filterType='', search=''){
    let tbody = document.getElementById('parametersTableBody');
    tbody.innerHTML = '';
    if(allParameters.length === 0){
        tbody.innerHTML = '<tr><td colspan="7" class="text-center">No parameters added yet</td></tr>';
        return;
    }

    let i = 1;
    let searchLower = search.toLowerCase();

    allParameters.forEach(row => {
        if(filterType && row.meal_type !== filterType) return;

        if(search && !(
            row.material_name.toLowerCase().includes(searchLower) ||
            row.meal_type.toLowerCase().includes(searchLower)
        )) return;

        let totalQty = (row.qty_per_people * row.people_count).toFixed(2);
        tbody.innerHTML += `
            <tr>
                <td>${i}</td>
                <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-warning me-1 mb-1" 
                        onclick="editParameter(${row.id}, ${row.material_id}, ${row.qty_per_people}, ${row.people_count}, '${row.meal_type}')">
                        <i class="fa fa-edit"></i> Edit
                    </button>
                    <button class="btn btn-sm btn-danger mb-1" onclick="removeParameter(${row.id})">
                        <i class="fa fa-trash"></i> Remove
                    </button>
                </td>
            </tr>
        `;
        i++;
    });

    if(tbody.innerHTML === '') {
        tbody.innerHTML = '<tr><td colspan="7" class="text-center">No matching records found</td></tr>';
    }
}

// ===== Add / Update Parameter =====
document.getElementById('mealForm').addEventListener('submit', function(e){
    e.preventDefault();
    let formData = new FormData(this);

    fetch('meal_parameters_action.php', {
        method: 'POST',
        body: formData
    })
    .then(res => res.text())
    .then(data => {
        document.getElementById('message').innerText = data;
        setTimeout(() => { document.getElementById('message').innerText = ''; }, 3000);
        loadParameters(document.getElementById('filterMealType').value);
        this.reset();
        this.edit_id.value = '';
        new bootstrap.Collapse(document.getElementById('mealFormCollapse')).hide();
    })
    .catch(err => console.error(err));
});

// ===== Remove Parameter =====
function removeParameter(id){
    if(confirm('Are you sure you want to remove this parameter?')){
        fetch('meal_parameters_action.php', {
            method: 'POST',
            body: new URLSearchParams({action:'remove', id:id})
        })
        .then(res => res.text())
        .then(data => {
            document.getElementById('message').innerText = data;
            setTimeout(() => { document.getElementById('message').innerText = ''; }, 3000);
            loadParameters(document.getElementById('filterMealType').value);
        });
    }
}

// ===== Edit Parameter =====
function editParameter(id, material_id, qty, people, type){
    document.querySelector('[name="edit_id"]').value = id;
    document.querySelector('[name="material_id"]').value = material_id;
    document.querySelector('[name="qty_per_people"]').value = qty;
    document.querySelector('[name="people_count"]').value = people;
    document.querySelector('[name="meal_type"]').value = type;
    new bootstrap.Collapse(document.getElementById('mealFormCollapse')).show();
}

// ===== Reset Form =====
function resetForm(){
    document.getElementById('mealForm').reset();
    document.querySelector('[name="edit_id"]').value = '';
}

// ===== Filter by Meal Type =====
document.getElementById('filterMealType').addEventListener('change', function(){
    renderTable(this.value, document.getElementById('searchInput').value);
});

// ===== Live Search =====
document.getElementById('searchInput').addEventListener('keyup', function(){
    renderTable(document.getElementById('filterMealType').value, this.value);
});

// ===== Export to Excel =====
function exportTableToExcel(filename = 'meal_parameters.xlsx') {
    const table = document.querySelector('table');
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.table_to_sheet(table, {raw:true});

    // remove Action column (last column)
    const range = XLSX.utils.decode_range(ws['!ref']);
    for(let R = range.s.r; R <= range.e.r; ++R){
        const C = range.e.c; // last column
        const cellAddress = { c:C, r:R };
        const cellRef = XLSX.utils.encode_cell(cellAddress);
        delete ws[cellRef];
    }

    XLSX.utils.book_append_sheet(wb, ws, "Meal Parameters");
    XLSX.writeFile(wb, filename);
}

// ===== Initial Load =====
loadParameters();
</script>