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

// 🔥 DEBUG (REMOVE IN PRODUCTION)
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors', 1);

// ✅ Validate meal_id
$meal_id = intval($_GET['meal_id'] ?? 0);
if ($meal_id <= 0) {
    die("<div class='alert alert-danger'>Invalid meal ID</div>");
}

// ✅ Add ingredient
if(isset($_POST['add_material'])){

    $material_id = intval($_POST['material_id'] ?? 0);
    $qty = floatval($_POST['qty_required'] ?? 0);

    if($material_id <= 0 || $qty <= 0){
        echo "<div class='alert alert-danger'>Invalid material or quantity</div>";
    } else {

        // 🔒 Prevent duplicates
        $check = $conn->query("
            SELECT id FROM meal_recipes 
            WHERE meal_id=$meal_id AND material_id=$material_id
        ");

        if($check->num_rows > 0){
            echo "<div class='alert alert-warning'>Material already added</div>";
        } else {

            $conn->query("
                INSERT INTO meal_recipes(meal_id, material_id, qty_required)
                VALUES($meal_id, $material_id, $qty)
            ");

            echo "<div class='alert alert-success'>Material added successfully</div>";
        }
    }
}

// ✅ Remove ingredient
if(isset($_GET['remove'])){
    $rid = intval($_GET['remove']);
    $conn->query("DELETE FROM meal_recipes WHERE id=$rid AND meal_id=$meal_id");
    echo "<script>window.location='meal_recipe.php?meal_id=$meal_id';</script>";
    exit;
}

// ✅ Load meal
$meal = $conn->query("SELECT * FROM meals WHERE id=$meal_id")->fetch_assoc();
?>

<div class="container mt-4">
      <!-- ================= WELCOME MESSAGE ================= -->
   

<h4>🧾 Recipe for: <strong><?= htmlspecialchars($meal['meal_name']) ?></strong></h4>
<hr>

<!-- ✅ Add Material Form -->
<form method="POST" class="row mb-3">

    <div class="col-md-5">
        <label>Raw Material</label>
        <select name="material_id" class="form-control" required>
            <option value="">Select material</option>
            <?php
            $mats = $conn->query("
                SELECT p.id, p.name, 
                       COALESCE(ps.quantity,0) AS stock_qty
                FROM products p
                LEFT JOIN product_stock ps 
                    ON p.id = ps.product_id AND ps.store_id = 1
                WHERE p.raw_materials='Yes'
                ORDER BY p.name
            ");

            while($m = $mats->fetch_assoc()):
            ?>
            <option value="<?= $m['id'] ?>">
                <?= htmlspecialchars($m['name']) ?> 
                (Stock: <?= number_format($m['stock_qty'],3) ?>)
            </option>
            <?php endwhile; ?>
        </select>
    </div>

    <div class="col-md-3">
        <label>Qty Required</label>
        <input type="number" step="0.001" name="qty_required"
               class="form-control" required>
    </div>

    <div class="col-md-2 d-flex align-items-end">
        <button type="submit" name="add_material"
                class="btn btn-success w-100">
            <i class="fa fa-plus"></i> Add
        </button>
    </div>

</form>

<!-- ✅ Recipe Table -->
<table class="table table-bordered table-striped">
<thead class="bg-secondary text-white">
<tr>
    <th>#</th>
    <th>Material</th>
    <th>Qty Required</th>
    <th width="120">Action</th>
</tr>
</thead>
<tbody>

<?php
$r = $conn->query("
    SELECT mr.*, p.name AS material_name
    FROM meal_recipes mr
    JOIN products p ON mr.material_id = p.id
    WHERE mr.meal_id = $meal_id
    ORDER BY mr.id DESC
");

$i=1;
while($row = $r->fetch_assoc()):
?>
<tr>
    <td><?= $i++ ?></td>
    <td><?= htmlspecialchars($row['material_name']) ?></td>
    <td><?= number_format($row['qty_required'],3) ?></td>
    <td>
        <a href="meal_recipe.php?meal_id=<?= $meal_id ?>&remove=<?= $row['id'] ?>"
           class="btn btn-danger btn-sm"
           onclick="return confirm('Remove this material?')">
           Remove
        </a>
    </td>
</tr>
<?php endwhile; ?>

<?php if($r->num_rows==0): ?>
<tr>
    <td colspan="4" class="text-center text-muted">
        No ingredients added yet
    </td>
</tr>
<?php endif; ?>

</tbody>
</table>

</div>

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