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

$username = $_SESSION['username'] ?? 'System';

// ================= CREATE REQUISITION =================
if(isset($_GET['produce_meal_id']) && isset($_GET['people'])) {

    $meal_id = intval($_GET['produce_meal_id']);
    $people  = intval($_GET['people']);

    // Get meal production record
    $meal = $conn->query("SELECT * FROM meals WHERE id=$meal_id")->fetch_assoc();
    if(!$meal) die("<div class='alert alert-danger'>Meal not found!</div>");

    $meal_name = $conn->real_escape_string($meal['meal_name']);

    // Insert meal production
    $conn->query("
        INSERT INTO meal_production (meal_id, people_count, produced_by, produced_at, category, section)
        VALUES ($meal_id, $people, '$username', NOW(), '{$meal['category']}', '{$meal['section']}')
    ");
    $production_id = $conn->insert_id;

    // Get recipe
    $recipe = $conn->query("
        SELECT mr.*, p.name, p.unit, COALESCE(ps.quantity,0) AS stock_qty
        FROM meal_recipes mr
        JOIN products p ON mr.material_id=p.id
        LEFT JOIN product_stock ps ON p.id=ps.product_id AND ps.store_id=1
        WHERE mr.meal_id=$meal_id
    ");

    while($r = $recipe->fetch_assoc()) {
        $needed_qty = $r['qty_required'] * $people;

        // Insert into requisitions
        $conn->query("
            INSERT INTO kitchen_requisitions
            (meal_production_id, product_id, quantity, requested_by, requested_at, status)
            VALUES ($production_id, {$r['material_id']}, $needed_qty, '$username', NOW(), 'Approved')
        ");

        // Deduct stock
        $conn->query("
            UPDATE product_stock
            SET quantity = quantity - $needed_qty
            WHERE product_id={$r['material_id']} AND store_id=1
        ");

        // Log movement
        $conn->query("
            INSERT INTO stock_movements
            (product_id, from_store_id, to_store_id, quantity, movement_type)
            VALUES ({$r['material_id']}, 1, NULL, $needed_qty, 'Kitchen Consumption')
        ");
    }

    echo "<div class='alert alert-success'>✅ Requisitions created and stock updated for $people people of $meal_name</div>";
}

// ===================== DISPLAY REQUISITIONS =====================
$filters = [];
if(!empty($_GET['meal_id'])) $filters[] = "kr.meal_production_id IN (SELECT id FROM meal_production WHERE meal_id=".intval($_GET['meal_id']).")";
if(!empty($_GET['product_id'])) $filters[] = "kr.product_id=".intval($_GET['product_id']);
if(!empty($_GET['requested_by'])) $filters[] = "kr.requested_by LIKE '%".$conn->real_escape_string($_GET['requested_by'])."%'";
if(!empty($_GET['date_from']) && !empty($_GET['date_to'])) {
    $filters[] = "DATE(kr.requested_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 requisitions
$requisitions = $conn->query("
    SELECT kr.*, p.name AS product_name, p.unit AS product_unit, m.meal_name, mp.people_count
    FROM kitchen_requisitions kr
    JOIN products p ON kr.product_id = p.id
    JOIN meal_production mp ON kr.meal_production_id = mp.id
    JOIN meals m ON mp.meal_id = m.id
    $filter_sql
    ORDER BY kr.requested_at DESC
    LIMIT 500
");

// Fetch meals/products for filters
$meals = $conn->query("SELECT id, meal_name FROM meals ORDER BY meal_name ASC");
$products = $conn->query("SELECT id, name FROM products ORDER BY name ASC");
?>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
<h3 class="text-center">📋 Restaurant Requisitions</h3>
<hr>

<!-- FILTER FORM -->
<form method="GET" class="row g-3 mb-3">
    <div class="col-md-3">
        <label>Meal</label>
        <select name="meal_id" class="form-control">
            <option value="">-- All Meals --</option>
            <?php while($m = $meals->fetch_assoc()): ?>
            <option value="<?= $m['id'] ?>" <?= (isset($_GET['meal_id']) && $_GET['meal_id']==$m['id'])?'selected':'' ?>>
                <?= htmlspecialchars($m['meal_name']) ?>
            </option>
            <?php endwhile; ?>
        </select>
    </div>

    <div class="col-md-3">
        <label>Product</label>
        <select name="product_id" class="form-control">
            <option value="">-- All Products --</option>
            <?php while($p = $products->fetch_assoc()): ?>
            <option value="<?= $p['id'] ?>" <?= (isset($_GET['product_id']) && $_GET['product_id']==$p['id'])?'selected':'' ?>>
                <?= htmlspecialchars($p['name']) ?>
            </option>
            <?php endwhile; ?>
        </select>
    </div>

    <div class="col-md-2">
        <label>Requested By</label>
        <input type="text" name="requested_by" value="<?= htmlspecialchars($_GET['requested_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>
</form>

<!-- PRINT BUTTON -->
<div class="mb-3">
    <a href="restaurant_requesitions_print.php?<?= $_SERVER['QUERY_STRING'] ?>" target="_blank" class="btn btn-dark">
        <i class="fa fa-print"></i> Print / PDF
    </a>
</div>

<!-- REQUISITIONS TABLE -->
<table class="table table-bordered table-striped">
<thead class="bg-dark text-white">
<tr>
<th>#</th>
<th>Meal</th>
<th>People</th>
<th>Product</th>
<th>Quantity</th>
<th>Unit</th>
<th>Requested By</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php 
$i=1;
while($r = $requisitions->fetch_assoc()): 
?>
<tr>
<td><?= $i++ ?></td>
<td><?= htmlspecialchars($r['meal_name']) ?></td>
<td><?= intval($r['people_count']) ?></td>
<td><?= htmlspecialchars($r['product_name']) ?></td>
<td><?= number_format($r['quantity'],2) ?></td>
<td><?= htmlspecialchars($r['product_unit']) ?></td>
<td><?= htmlspecialchars($r['requested_by']) ?></td>
<td><?= date("d-M-Y H:i", strtotime($r['requested_at'])) ?></td>
<td>
<?php if($r['status']=='Approved'): ?>
<span class="badge bg-success"><?= $r['status'] ?></span>
<?php else: ?>
<span class="badge bg-warning"><?= $r['status'] ?></span>
<?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>

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