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

// ================= POST DATA =================
$people_count = intval($_POST['people_count'] ?? 1);
$selected_items = $_POST['selected_items'] ?? [];
$selected_perishables = $_POST['selected_perishables'] ?? [];
$selected_meal_params = $_POST['selected_meal_params'] ?? [];

$today = date('Y-m-d');

// ================= PREPARE INSERT =================
$stmt = $conn->prepare("INSERT INTO walkin_production 
    (production_date, people_count, item_name, item_type, unit, qty_per_person, composition, unit_cost, total_qty, total_costs, total_value,perishable_name) 
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");

// ================= MEALS & REFRESHMENTS =================
foreach($selected_items as $item){
    $parts = explode('_', $item);
    $type = $parts[0];
    $id = intval($parts[1]);

    if($type === 'meal'){
        $row = $conn->query("SELECT name, price FROM restaurant_menu WHERE id=$id")->fetch_assoc();
        $name = $row['name'];
        $unit_cost = $row['price'];
    } else {
        $row = $conn->query("SELECT item_name, price FROM conference_refreshments WHERE id=$id")->fetch_assoc();
        $name = $row['item_name'];
        $unit_cost = $row['price'];
    }

    $unit = null;
    $qty_per_person = null;
    $composition = null;
    $total_qty = $people_count;
    $total_costs = $unit_cost * $people_count;
    $total_value = $total_costs;
      $perishable_name = 1;

   $stmt->bind_param(
    "sisssdddddds",
    $today,
    $people_count,
    $name,
    $type,
    $unit,
    $qty_per_person,
    $composition,
    $unit_cost,
    $total_qty,
    $total_costs,
    $total_value, $perishable_name
);
    $stmt->execute();
}

// ================= PERISHABLES =================
foreach($selected_perishables as $pid){
    $row = $conn->query("
        SELECT pp.qty_per_person, pp.composition, pp.unit_cost, p.name AS perishable_name, p.unit
        FROM perishable_parameters pp
        JOIN perishables p ON pp.perishable_id = p.id
        WHERE pp.id=".intval($pid)
    )->fetch_assoc();

    $qty_per_person = $row['qty_per_person'];
    $total_qty = round($qty_per_person * $people_count, 2);
    $composition = $row['composition'];
    $composition_total = round($composition * $people_count, 2);
    $unit = $row['unit'];
    $unit_cost = $row['unit_cost'];
    $total_costs = $unit_cost * $people_count;
    $total_value = $total_costs;
    $type = 'perishable';
      $perishable_name = $row['perishable_name'];

 $stmt->bind_param(
    "sisssdddddds",
    $today,
    $people_count,
    $name,
    $type,
    $unit,
    $qty_per_person,
    $composition,
    $unit_cost,
    $total_qty,
    $total_costs,
    $total_value,
      $perishable_name
);
    $stmt->execute();
}

// ================= MEAL PARAMETERS =================
foreach($selected_meal_params as $mpid){
    $row = $conn->query("
        SELECT mp.qty_per_people, p.name AS material_name, p.buying_price AS unit_cost
        FROM meal_parameters mp
        JOIN products p ON mp.material_id = p.id
        WHERE mp.id=".intval($mpid)
    )->fetch_assoc();

    $qty_per_person = $row['qty_per_people'];
    $total_qty = round($qty_per_person * $people_count, 2);
    $unit = null;
    $composition = null;
    $unit_cost = $row['unit_cost'];
    $total_costs = $unit_cost * $total_qty;
    $total_value = $total_costs;
    $type = 'meal_param';
      $perishable_name =    $row['material_name'];
 $stmt->bind_param(
    "sisssdddddds",
    $today,
    $people_count,
    $name,
    $type,
    $unit,
    $qty_per_person,
    $composition,
    $unit_cost,
    $total_qty,
    $total_costs,
    $total_value,
     $perishable_name
);
    $stmt->execute();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Walk-in Production Plan</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-..." crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
    body {
        padding: 20px;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background-color: #f9f9f9;
        color: #333;
    }
    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        border-bottom: 2px solid #ccc;
        padding-bottom: 10px;
    }
    .logo img {
        max-height: 80px;
    }
    .restaurant-details {
        text-align: right;
        font-size: 14px;
    }
    h2, h4, h5 {
        font-weight: 700;
        margin-bottom: 15px;
        color: #2c3e50;
    }
    .section-title {
        background-color: #2c3e50;
        color: #fff;
        font-size: 12px;
        padding: 8px 12px;
        border-radius: 4px;
        display: inline-block;
        margin-bottom: 10px;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 30px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        background-color: #fff;
    }
    th, td {
        padding: 10px 12px;
        border: 1px solid #ddd;
    }
    th {
        background-color: #34495e;
        color: #fff;
        text-align: center;
    }
    td {
        text-align: center;
    }
    tbody tr:nth-child(even) {
        background-color: #f2f2f2;
    }
    tbody tr:hover {
        background-color: #d1ecf1;
    }
    .total-row td {
        font-weight: 700;
        background-color: #ecf0f1;
    }
    button.print-btn {
        background-color: #e74c3c;
        color: #fff;
        border: none;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }
    button.print-btn i {
        margin-right: 5px;
    }
    button.print-btn:hover {
        background-color: #c0392b;
    }
    @media print {
        button { display: none; }
        body { background-color: #fff; }
    }
</style>
</head>
<body>

<!-- ===== Header ===== -->
<div class="header">
    <div class="logo">
        <img src="assets/logo.png" alt="Restaurant Logo">
    </div>
    <div class="restaurant-details">
        <p><strong>Website:</strong> <a href="https://ramslodgemw.com" target="_blank">ramslodgemw.com</a></p>
        <p><strong>Date:</strong> <?= date('d-m-Y') ?></p>
    </div>
</div>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h6>Walk-in Meal Production Plan Alakati</h6>
    <button class="print-btn" onclick="window.print()"><i class="fa fa-print"></i> Print</button>
</div>

<p><strong>Number of People:</strong> <?= $people_count ?></p>

<!-- ===== Meals & Refreshments ===== -->
<h5 class="section-title">Meals & Refreshments</h5>
<table class="table table-bordered table-hover">
    <thead>
        <tr>
            <th>#</th>
            <th>Item</th>
            <th>Type</th>
            <th>Unit Cost (MWK)</th>
            <th>Total Qty</th>
            <th>Total Costs (MWK)</th>
            <th>Total Value (MWK)</th>
        </tr>
    </thead>
    <tbody>
    <?php
     $meals_total_costs = 0;        // For Meals & Refreshments
    $i = 1;
    foreach($selected_items as $item){
        $parts = explode('_', $item);
        $type = $parts[0];
        $id = intval($parts[1]);

        if($type==='meal'){
            $row = $conn->query("SELECT name, price FROM restaurant_menu WHERE id=$id")->fetch_assoc();
            $name = $row['name'];
            $unit_cost = $row['price'];
        } else {
            $row = $conn->query("SELECT item_name, price FROM conference_refreshments WHERE id=$id")->fetch_assoc();
            $name = $row['item_name'];
            $unit_cost = $row['price'];


        }

       
$perishables_total_costs = 0;  // For Perishables
$meal_params_total_costs = 0;  // For Meal Ingredients

        $total_qty = $people_count;
        $total_costs = $unit_cost * $people_count;
        $total_value = $total_costs;
        $meals_total_costs += $total_costs; // accumulate total for meals & refreshments

        echo "<tr>
                <td>{$i}</td>
                <td>{$name}</td>
                <td>".ucfirst($type)."</td>
                <td>".number_format($unit_cost,2)."</td>
                <td>{$total_qty}</td>
                <td>".number_format($total_costs,2)."</td>
                <td>".number_format($total_value,2)."</td>
              </tr>";
        $i++;
    } ?>
     <tr class="total-row">
        <td colspan="5">Overall Total</td>
        <td><?= number_format($meals_total_costs,2) ?></td>
        <td><?= number_format($meals_total_costs,2) ?></td>
    </tr>
    
    </tbody>
</table>

<!-- ===== Perishables ===== -->
<?php if(!empty($selected_perishables)): ?>
<h5 class="section-title">Perishable Ingredients Required</h5>
<table class="table table-bordered table-hover">
    <thead>
        <tr>
            <th>#</th>
            <th>Item</th>
            <th>Unit</th>
            <th>Qty per Person</th>
            <th>Total Qty</th>
            <th>Unit Cost (MWK)</th>
            <th>Total Costs (MWK)</th>
            
          
        </tr>
    </thead>
    <tbody>
    <?php
 
    $i=1;
    foreach($selected_perishables as $pid){
        $row = $conn->query("
            SELECT pp.qty_per_person, pp.composition, pp.unit_cost, p.name AS item_name, p.unit
            FROM perishable_parameters pp
            JOIN perishables p ON pp.perishable_id = p.id
            WHERE pp.id=".intval($pid)
        )->fetch_assoc();

        $qty_per_person = $row['qty_per_person'];
        $total_qty = round($qty_per_person * $people_count,2);
        $composition_total = round($row['composition'] * $people_count,2);
        $unit_cost = $row['unit_cost'];
        $total_costs = $unit_cost *  $people_count;
        $total_value = $total_costs;
        $perishables_total_costs += $total_costs; // ✅ accumulate perishable total

        echo "<tr>
                <td>{$i}</td>
                <td>{$row['item_name']}</td>
                <td>{$row['unit']}</td>
                <td>{$qty_per_person}</td>
                <td>{$total_qty}</td>
                <td>".number_format($unit_cost,2)."</td>
                <td>".number_format($total_costs,2)."</td>
                
             
              </tr>";
        $i++;
    }
    ?>
      <tr class="total-row">
        <td colspan="5">Overall Total</td>
        <td></td>
        <td><?= number_format($perishables_total_costs,2) ?></td>
        
    </tr>
    </tbody>
</table>
<?php endif; ?>

<!-- ===== Meal Ingredients ===== -->
<?php if(!empty($selected_meal_params)): ?>
<h5 class="section-title">Meal Ingredients Required</h5>
<table class="table table-bordered table-hover">
    <thead>
        <tr>
            <th>#</th>
            <th>Material</th>
            <th>Qty per Person</th>
            <th>Total Qty</th>
            <th>Unit Cost (MWK)</th>
            <th>Total Costs (MWK)</th>
           
        </tr>
    </thead>
    <tbody>
    <?php
  
$meal_params_total_costs = 0;  // For Meal Ingredients
    $i=1;
    foreach($selected_meal_params as $mpid){
        $row = $conn->query("
            SELECT mp.qty_per_people, p.name AS material_name, p.buying_price AS unit_cost
            FROM meal_parameters mp
            JOIN products p ON mp.material_id = p.id
            WHERE mp.id=".intval($mpid)
        )->fetch_assoc();

        $qty_per_person = $row['qty_per_people'];
        $total_qty = round($qty_per_person * $people_count, 2);
        $total_costs = $row['unit_cost'] * $total_qty;
        $total_value = $total_costs;
            $meal_params_total_costs += $total_costs; // ✅ add here

        echo "<tr>
                <td>{$i}</td>
                <td>{$row['material_name']}</td>
                <td>{$qty_per_person}</td>
                <td>{$total_qty}</td>
                <td>".number_format($row['unit_cost'],2)."</td>
                <td>".number_format($total_costs,2)."</td>
             
              </tr>";
        $i++;
    }
    ?>
      <tr class="total-row">
        <td colspan="5">Overall Total</td>
       <td><?= number_format($meal_params_total_costs,2) ?></td>

    </tr>
    </tbody>
</table>
<?php endif; ?>

</body>
</html>