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


// ================= HANDLE ACTIONS ==================

// Mark as served
if(isset($_POST['mark_served'])){
    $prod_id = intval($_POST['production_id']);
    $conn->query("UPDATE meal_production SET status='Served' WHERE id=$prod_id");
    header("Location: produced_meals.php");
    exit;
}

// Delete production
if(isset($_POST['delete_production'])){
    $prod_id = intval($_POST['production_id']);
    $conn->query("DELETE FROM meal_production WHERE id=$prod_id");
    header("Location: produced_meals.php");
    exit;
}
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 = [];

// Filter by meal, category, section, produced_by, date
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'])."'";
} else {
    // Show only today's productions by default if no date filter is applied
    $filters[] = "DATE(mp.produced_at) = CURDATE()";
}

// ================== STATUS FILTER ==================
// Default to Pending if no status filter selected
$status_filter = $_GET['status'] ?? 'Pending';
if($status_filter){
    $filters[] = "mp.status = '".$conn->real_escape_string($status_filter)."'";
}

$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">

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

<h4>📋 Produced Meals</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">
        <label>Status</label>
        <select name="status" class="form-control">
            <option value="">-- All --</option>
            <option value="Pending" <?= ($status_filter=='Pending')?'selected':'' ?>>Pending</option>
            <option value="Served" <?= ($status_filter=='Served')?'selected':'' ?>>Served</option>
        </select>
    </div>
    <div class="col-md-2 d-flex align-items-end">
        <button class="btn btn-primary w-100">Filter</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>
<th>Actions</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><a href="print_production.php?id=<?= $p['id'] ?>" target="_blank"><?= htmlspecialchars($p['meal_name']) ?></a></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>
<td>
<div class="d-flex flex-column gap-1">
<?php if($p['status']=='Pending'): ?>
    <form method="POST" style="display:inline;">
        <input type="hidden" name="production_id" value="<?= $p['id'] ?>">
        <button name="mark_served" class="btn btn-sm btn-success w-100">✓ Serve</button>
    </form>
    <a href="edit_production.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-warning w-100">✎ Edit</a>
    <form method="POST" style="display:inline;" onsubmit="return confirm('Are you sure to delete this production?');">
        <input type="hidden" name="production_id" value="<?= $p['id'] ?>">
        <button name="delete_production" class="btn btn-sm btn-danger w-100">🗑 Delete</button>
    </form>
<?php else: ?>
    <span class="text-success">✔ Completed</span>
<?php endif; ?>
<a href="print_production.php?id=<?= $p['id'] ?>" target="_blank" class="btn btn-sm btn-info w-100">🖨 Print</a>
</div>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

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