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

$booking_id = intval($_POST['booking_id'] ?? 0);
$people_count = intval($_POST['people_count'] ?? 0);
$days_count = $_POST['days_count'] === 'all' ? intval($_POST['days_count_all'] ?? 1) : intval($_POST['days_count']);

if($booking_id <= 0 || $people_count <= 0){
    die("<div class='alert alert-danger'>Invalid booking or people count</div>");
}

// Fetch booking info
$booking = $conn->query("SELECT * FROM conference_bookings WHERE id=$booking_id")->fetch_assoc();
if(!$booking){ die("<div class='alert alert-danger'>Booking not found</div>"); }

// Selected arrays
$selected_items = $_POST['selected_items'] ?? [];
$selected_perishables = $_POST['selected_perishables'] ?? [];
$selected_meal_params = $_POST['selected_meal_params'] ?? [];

// Clear previous plan for this booking
$conn->query("DELETE FROM production_plan WHERE booking_id=$booking_id");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Production Template - Booking #<?= $booking_id ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body{padding:20px;font-family:Arial,sans-serif;}
        table{font-size:14px;}
        h3,h5{margin-top:20px;}
        .logo {height:60px;margin-right:15px;}
        .header {display:flex; align-items:center; margin-bottom:20px;}
        .totals {font-weight:bold;background:#f2f2f2;}
    </style>
</head>
<body>
    <div class="header">
        <img src="assets/logo.png" class="logo" alt="Logo">
        <div>
            <h3>Production Template for Booking #<?= $booking_id ?></h3>
            <p><strong>Attendees:</strong> <?= number_format($people_count) ?> | <strong>Days:</strong> <?= number_format($days_count) ?></p>
        </div>
    </div>
    <hr>

<?php
// ===== Meals & Refreshments =====
if(!empty($selected_items)):
    echo "<h5>Meals & Refreshments</h5><ul>";
    $totalMealsQty = 0;
    foreach($selected_items as $item){
        list($type, $id) = explode('_', $item);
        if($type=='meal'){
            $row = $conn->query("SELECT meal_name AS name FROM conference_meals WHERE id=$id")->fetch_assoc();
        } else {
            $row = $conn->query("SELECT item_name AS name FROM conference_refreshments WHERE id=$id")->fetch_assoc();
        }
        if($row){
            $qty = $people_count * $days_count;
            echo "<li>".ucfirst($type).": {$row['name']} × ".number_format($people_count)." × ".number_format($days_count)." day(s) = <strong>".number_format($qty)."</strong></li>";
            $totalMealsQty += $qty;

            // Insert into production_plan
            $stmt = $conn->prepare("INSERT INTO production_plan 
                (booking_id, item_type, item_name, people_count,unit_price, days_count, total_qty) 
                VALUES (?, ?, ?, ?, ?, ?,?)");
            $stmt->bind_param("issiidd", $booking_id, $type, $row['name'], $people_count,$unit_price,  $days_count, $qty);
            $stmt->execute();
        }
    }
    echo "<li class='totals'>Overall Total Qty: ".number_format($totalMealsQty)."</li>";
    echo "</ul>";
endif;

// ===== Perishables =====
if(!empty($selected_perishables)):
    echo "<h5>Perishable Ingredients</h5>";
    echo "<table class='table table-bordered table-sm'>
            <thead class='table-dark'><tr>
                <th>#</th><th>Item</th><th>Unit</th>
                <th>Unit Cost</th>
                <th>Total Qty Needed</th><th>Total Cost(MWK)</th>
            </tr></thead><tbody>";
    $i=1;
    $totalPerishableQty = 0;
    $totalPerishableCost = 0;
    foreach($selected_perishables as $pid){
        $row = $conn->query("
            SELECT p.name, p.unit, pp.qty_per_person, pp.composition, pp.unit_cost
            FROM perishable_parameters pp
            JOIN perishables p ON pp.perishable_id = p.id
            WHERE pp.id=$pid
        ")->fetch_assoc();
        if($row){
            $composition = floatval($row['composition']) ?: 1;
            $totalQty = $row['qty_per_person'] * $people_count * $days_count * $composition;
            $totalCost = $people_count * $days_count  * floatval($row['unit_cost']);

            echo "<tr>
                    <td>$i</td>
                    <td>{$row['name']}</td>
                    <td>{$row['unit']}</td>
                 
                    <td>".number_format($row['unit_cost'],2)."</td>
                    <td>".number_format($totalQty,2)."</td>
                    <td>".number_format($totalCost,2)."</td>
                </tr>";

            // Insert into production_plan including unit_cost
            $stmt = $conn->prepare("INSERT INTO production_plan 
                (booking_id, item_type, item_name, unit, qty_per_person, composition, unit_cost, people_count, days_count, total_qty, total_cost)
                VALUES (?, 'perishable', ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param(
                "issddididd",
                $booking_id,
                $row['name'],
                $row['unit'],
                $row['qty_per_person'],
                $composition,
                $row['unit_cost'],
                $people_count,
                $days_count,
                $totalQty,
                $totalCost
            );
            $stmt->execute();

            $totalPerishableQty += $totalQty;
            $totalPerishableCost += $totalCost;
            $i++;
        }
    }
    echo "<tr class='totals'>
            <td colspan='4'>Overall Totals</td>
            <td>".number_format($totalPerishableQty,2)."</td>
            <td>".number_format($totalPerishableCost,2)."</td>
          </tr>";
    echo "</tbody></table>";
endif;

// ===== Meal Parameters =====
if(!empty($selected_meal_params)):
    echo "<h5>Meal Parameters (Conference Only)</h5>";
    echo "<table class='table table-bordered table-sm'>
            <thead class='table-dark'><tr>
                <th>#</th><th>Material</th>
                <th>Unit Cost</th><th>Total Qty Needed</th><th>Total Costs(MWK)</th>
            </tr></thead><tbody>";
    $i=1;
    $totalMealParamQty = 0;
    $totalMealParamCost = 0;
    foreach($selected_meal_params as $mpid){
        $row = $conn->query("
            SELECT p.name, mp.qty_per_people, mp.composition,p.buying_price
            FROM meal_parameters mp
            JOIN products p ON mp.material_id = p.id
            WHERE mp.id=$mpid
        ")->fetch_assoc();
        if($row){
            $composition = floatval($row['composition']) ?: 1;
            $totalQty = $row['qty_per_people'] * $people_count * $days_count * $composition;
            $totalCost = $totalQty * floatval($row['buying_price']);

            echo "<tr>
                    <td>$i</td>
                    <td>{$row['name']}</td>
                   
                    <td>".number_format($row['buying_price'],2)."</td>
                    <td>".number_format($totalQty,2)."</td>
                    <td>".number_format($totalCost,2)."</td>
                </tr>";

            // Insert into production_plan
            $stmt = $conn->prepare("INSERT INTO production_plan 
                (booking_id, item_type, item_name, qty_per_person, composition, people_count, days_count, total_qty)
                VALUES (?, 'meal_param', ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("isddidd", $booking_id, $row['name'], $row['qty_per_people'], $composition, $people_count, $days_count, $totalQty);
            $stmt->execute();

            $totalMealParamQty += $totalQty;
            $totalMealParamCost += $totalCost;
            $i++;
        }
    }
    echo "<tr class='totals'>
            <td colspan='3'>Overall Totals</td>
            <td>".number_format($totalMealParamQty,2)."</td>
            <td>".number_format($totalMealParamCost,2)."</td>
          </tr>";
    echo "</tbody></table>";
endif;
?>

<script>window.print();</script>
</body>
</html>