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

// ================== FILTERS ==================
// Fetch dropdown options
$mealOptions     = $conn->query("SELECT DISTINCT meal_name FROM meals ORDER BY meal_name");
$categoryOptions = $conn->query("SELECT DISTINCT category FROM meals ORDER BY category");
$sectionOptions  = $conn->query("SELECT DISTINCT section FROM meals ORDER BY section");

// Build filter conditions
$filters = [];
if(!empty($_GET['meal_name'])) $filters[] = "m.meal_name = '".$conn->real_escape_string($_GET['meal_name'])."'";
if(!empty($_GET['category']))  $filters[] = "m.category = '".$conn->real_escape_string($_GET['category'])."'";
if(!empty($_GET['section']))   $filters[] = "m.section = '".$conn->real_escape_string($_GET['section'])."'";
if(!empty($_GET['produced_by'])) $filters[] = "mp.produced_by LIKE '%".$conn->real_escape_string($_GET['produced_by'])."%'";
if(!empty($_GET['date_from']) && !empty($_GET['date_to'])) {
    $filters[] = "DATE(mp.produced_at) BETWEEN '".$conn->real_escape_string($_GET['date_from'])."' AND '".$conn->real_escape_string($_GET['date_to'])."'";
}

$filter_sql = count($filters) ? "WHERE ".implode(" AND ", $filters) : "";

// ================== FETCH PRODUCTIONS ==================
$productions = $conn->query("
    SELECT mp.*, m.meal_name, m.category, m.section
    FROM meal_production mp
    JOIN meals m ON mp.meal_id = m.id
    $filter_sql
    ORDER BY mp.produced_at DESC
");
?>

<div class="container mt-4">
     <center>  <a href="meal_parameters.php" class="btn btn-sm btn-primary">Meal Parameters</a>

            <a href="produce_meal.php" class="btn btn-sm btn-primary">Produce Meal</a>

            <a href="meal_production_list.php" class="btn btn-sm btn-primary">Meal Productions</a>
                <a href="production_reports.php" class="btn btn-sm btn-primary">Reports</a>
      </center>
<h4>📊 Kitchen Production Reports</h4>
<hr>

<!-- FILTER FORM -->
<form method="GET" class="row g-3 mb-4">
    <div class="col-md-3">
        <label>Meal Name</label>
        <select name="meal_name" class="form-control">
            <option value="">-- All Meals --</option>
            <?php while($m = $mealOptions->fetch_assoc()): ?>
            <option value="<?= htmlspecialchars($m['meal_name']) ?>" <?= (($_GET['meal_name'] ?? '')==$m['meal_name'])?'selected':'' ?>>
                <?= htmlspecialchars($m['meal_name']) ?>
            </option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="col-md-3">
        <label>Category</label>
        <select name="category" class="form-control">
            <option value="">-- All Categories --</option>
            <?php while($c = $categoryOptions->fetch_assoc()): ?>
            <option value="<?= htmlspecialchars($c['category']) ?>" <?= (($_GET['category'] ?? '')==$c['category'])?'selected':'' ?>>
                <?= htmlspecialchars($c['category']) ?>
            </option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="col-md-3">
        <label>Section</label>
        <select name="section" class="form-control">
            <option value="">-- All Sections --</option>
            <?php while($s = $sectionOptions->fetch_assoc()): ?>
            <option value="<?= htmlspecialchars($s['section']) ?>" <?= (($_GET['section'] ?? '')==$s['section'])?'selected':'' ?>>
                <?= htmlspecialchars($s['section']) ?>
            </option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="col-md-3">
        <label>Produced By</label>
        <input type="text" name="produced_by" value="<?= htmlspecialchars($_GET['produced_by'] ?? '') ?>" class="form-control">
    </div>
    <div class="col-md-2">
        <label>Date From</label>
        <input type="date" name="date_from" value="<?= htmlspecialchars($_GET['date_from'] ?? '') ?>" class="form-control">
    </div>
    <div class="col-md-2">
        <label>Date To</label>
        <input type="date" name="date_to" value="<?= htmlspecialchars($_GET['date_to'] ?? '') ?>" class="form-control">
    </div>
    <div class="col-md-2 d-flex align-items-end">
        <button class="btn btn-primary w-100">Filter</button>
    </div>
    <div class="col-md-2 d-flex align-items-end">
        <button type="button" class="btn btn-success w-100" onclick="window.print()">🖨 Print Report</button>
    </div>
</form>

<!-- PRODUCTIONS TABLE -->
<table class="table table-bordered table-striped">
<thead class="bg-dark text-white">
<tr>
<th>#</th>
<th>Meal</th>
<th>Category</th>
<th>Section</th>
<th>People</th>
<th>Produced By</th>
<th>Date</th>
<th>Status</th>
<th>Recipe Details</th>
</tr>
</thead>
<tbody>
<?php
$i=1;
while($p = $productions->fetch_assoc()):

    // Fetch recipe details
    $recipe = $conn->query("
        SELECT mr.*, p.name, (mr.qty_required * {$p['people_count']}) AS total_qty
        FROM meal_recipes mr
        JOIN products p ON mr.material_id = p.id
        WHERE mr.meal_id = {$p['meal_id']}
    ");

    $recipeDetails = "<ul class='mb-0'>";
    while($r = $recipe->fetch_assoc()){
        $recipeDetails .= "<li>{$r['name']}: {$r['qty_required']} per person → Total: {$r['total_qty']}</li>";
    }
    $recipeDetails .= "</ul>";
?>
<tr>
<td><?= $i++ ?></td>
<td><?= htmlspecialchars($p['meal_name']) ?></td>
<td><?= htmlspecialchars($p['category']) ?></td>
<td><?= htmlspecialchars($p['section']) ?></td>
<td><?= $p['people_count'] ?></td>
<td><?= htmlspecialchars($p['produced_by']) ?></td>
<td><?= date("d-M-Y H:i", strtotime($p['produced_at'])) ?></td>
<td>
<?php if($p['status']=='Pending'): ?>
<span class="badge bg-warning">Pending</span>
<?php else: ?>
<span class="badge bg-success">Served</span>
<?php endif; ?>
</td>
<td><?= $recipeDetails ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>

<style>
@media print {
    body * { visibility: hidden; }
    .container, .container * { visibility: visible; }
    .container { position: absolute; top: 0; left: 0; width: 100%; }
    .btn { display: none !important; }
}
</style>

<?php include 'includes/footer.php'; ?>
