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

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

// Get production ID
$prod_id = intval($_GET['id'] ?? 0);
if($prod_id <= 0){
    die("Invalid production ID");
}

// Fetch production info
$prod = $conn->query("
    SELECT mp.*, m.meal_name, m.category, m.section
    FROM meal_production mp
    JOIN meals m ON mp.meal_id = m.id
    WHERE mp.id=$prod_id
")->fetch_assoc();

if(!$prod){
    die("Production not found");
}

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Print Production - <?= htmlspecialchars($prod['meal_name']) ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body{padding:20px;}
@media print{
    .no-print{display:none;}
}
</style>
</head>
<body>

<div class="container">
    <div class="text-center mb-4">
        <h2>🍽 Production Details</h2>
        <h4><?= htmlspecialchars($prod['meal_name']) ?></h4>
        <p><strong>Category:</strong> <?= htmlspecialchars($prod['category']) ?> | 
           <strong>Section:</strong> <?= htmlspecialchars($prod['section']) ?></p>
        <hr>
    </div>

    <div class="mb-3">
        <p><strong>Produced By:</strong> <?= htmlspecialchars($prod['produced_by']) ?></p>
        <p><strong>Date:</strong> <?= date("d-M-Y H:i", strtotime($prod['produced_at'])) ?></p>
        <p><strong>People Served:</strong> <?= $prod['people_count'] ?></p>
        <p><strong>Status:</strong> <?= htmlspecialchars($prod['status']) ?></p>
    </div>

    <h5>📋 Recipe / Ingredients Used</h5>
    <table class="table table-bordered">
        <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Ingredient</th>
                <th>Qty per Person/Kg</th>
                <th>Total Qty(Kgs)</th>
            </tr>
        </thead>
        <tbody>
            <?php $i=1; while($r = $recipe->fetch_assoc()): ?>
            <tr>
                <td><?= $i++ ?></td>
                <td><?= htmlspecialchars($r['name']) ?></td>
                <td><?= $r['qty_required'] ?></td>
                <td><?= $r['total_qty'] ?></td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>

    <div class="text-center mt-4 no-print">
        <button onclick="window.print()" class="btn btn-primary">🖨 Print This Page</button>
        <a href="meal_list.php" class="btn btn-secondary">⬅ Back</a>
    </div>
</div>

</body>
</html>
