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

$username = $_SESSION['username'] ?? 'Guest';
$today = date('Y-m-d'); // today's date
?>

<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 btn-custom mb-3" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <h4>Meal Production Report</h4>
    <hr>

    <!-- ===== FILTER FORM ===== -->
    <form id="filterForm" class="row g-3 mb-4">
        <div class="col-md-3">
            <label class="form-label fw-bold">Select Meal:</label>
            <select id="mealFilter" class="form-select">
                <option value="">All Meals</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-2">
            <label class="form-label fw-bold">From:</label>
            <input type="date" id="fromDate" class="form-control" value="<?= $today ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label fw-bold">To:</label>
            <input type="date" id="toDate" class="form-control" value="<?= $today ?>">
        </div>
        <div class="col-md-2 d-flex align-items-end">
            <button type="button" class="btn btn-primary w-100" onclick="loadReport()">
                <i class="fa fa-filter"></i> Filter
            </button>
        </div>
        <div class="col-md-2 d-flex align-items-end">
            <button type="button" class="btn btn-success w-100" onclick="printReport()">
                <i class="fa fa-print"></i> Print
            </button>
        </div>
    </form>

    <!-- ===== REPORT TABLE ===== -->
    <table class="table table-bordered table-striped table-hover table-sm" id="reportTable">
        <thead class="table-dark">
            <tr>
                <th>Meal</th>
                <th>Type</th>
                <th>Material</th>
                <th>Number of People</th>
                <th>Total Qty</th>
                <th>Produced By</th>
                <th>Produced At</th>
            </tr>
        </thead>
        <tbody id="reportBody">
            <tr><td colspan="7" class="text-center">Use the filter above to load report</td></tr>
        </tbody>
        <tfoot>
            <tr>
                <th colspan="4" class="text-end">Grand Total:</th>
                <th id="grandTotal">0</th>
                <th colspan="2"></th>
            </tr>
        </tfoot>
    </table>
</div>

<script>
// Load report via fetch
function loadReport(){
    let meal_id = document.getElementById('mealFilter').value;
    let fromDate = document.getElementById('fromDate').value;
    let toDate = document.getElementById('toDate').value;

    fetch('meal_production_action.php',{
        method:'POST',
        body: new URLSearchParams({
            action:'list',
            meal_id: meal_id,
            from: fromDate,
            to: toDate
        })
    })
    .then(res => res.json())
    .then(data => {
        let tbody = document.getElementById('reportBody');
        tbody.innerHTML = '';
        let grandTotal = 0;

        if(data.length===0){
            tbody.innerHTML = '<tr><td colspan="7" class="text-center">No records found</td></tr>';
            document.getElementById('grandTotal').innerText = '0';
            return;
        }

        data.forEach(row => {
            grandTotal += parseFloat(row.total_qty);
            tbody.innerHTML += `<tr>
                <td>${row.meal_name}</td>
                <td>${row.meal_type || '-'}</td>
                <td>${row.material_name}</td>
                <td>${row.number_of_people}</td>
                <td>${row.total_qty}</td>
                <td>${row.produced_by}</td>
                <td>${row.produced_at}</td>
            </tr>`;
        });

        document.getElementById('grandTotal').innerText = grandTotal.toFixed(2);
    });
}

// Print report nicely
function printReport(){
    let tableHTML = document.getElementById('reportTable').outerHTML;
    let html = `<html><head><title>Meal Production Report</title>
        <style>
            body{font-family:Arial,sans-serif;padding:20px;}
            table{border-collapse:collapse;width:100%;margin-top:10px;}
            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 Production Report</h2>
        ${tableHTML}
        <p><strong>Generated On:</strong> ${new Date().toLocaleString()}</p>
    </body></html>`;

    let w = window.open();
    w.document.write(html);
    w.print();
}

// Automatically load today's report on page load
window.addEventListener('DOMContentLoaded', loadReport);
</script>
