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

header('Content-Type: application/json');

$data = json_decode(file_get_contents('php://input'), true);

$meal_id    = intval($data['meal_id'] ?? 0);
$meal_type  = $conn->real_escape_string($data['meal_type'] ?? '');
$peopleCount = intval($data['number_of_people'] ?? 0);
$ingredients = $data['ingredients'] ?? [];

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

// ---------- VALIDATION ----------
if(!$meal_id || !$meal_type || !$peopleCount || empty($ingredients)){
    echo json_encode(['success'=>false,'error'=>'Missing required data']);
    exit;
}

// ---------- CHECK STOCK ----------
$insufficient = [];
foreach($ingredients as $row){
    $product_id = intval($row['material_id']);
    $needed_qty = floatval($row['total_qty']);

    // Get total available: products.quantity + sum(product_stock.quantity)
    $prod = $conn->query("
        SELECT p.name, p.unit, p.quantity AS prod_qty, 
               COALESCE(SUM(ps.quantity),0) AS stock_qty 
        FROM products p
        LEFT JOIN product_stock ps ON ps.product_id = p.id
        WHERE p.id = $product_id
        GROUP BY p.id
    ")->fetch_assoc();

    $available_total = ($prod['prod_qty'] ?? 0) + ($prod['stock_qty'] ?? 0);

    if($available_total < $needed_qty){
        $insufficient[] = "{$prod['name']} ({$prod['unit']}, Available: $available_total, Needed: $needed_qty)";
    }

    $row['available_qty'] = $available_total;
}

if(count($insufficient)){
    echo json_encode([
        'success'=>false,
        'error'=>"Cannot produce meal. Insufficient stock for: ".implode(', ', $insufficient)
    ]);
    exit;
}

// ---------- SAVE PRODUCTION ----------
$conn->begin_transaction();

try {
    // 1️⃣ Insert meal production
    $stmt = $conn->prepare("
        INSERT INTO meal_production (meal_id, meal_type, number_of_people, created_by, created_at) 
        VALUES (?, ?, ?, ?, NOW())
    ");
    $stmt->bind_param("isis", $meal_id, $meal_type, $peopleCount, $username);
    $stmt->execute();
    $production_id = $stmt->insert_id;

    // 2️⃣ Prepare statements for ingredients and stock deduction
    $stmt_ing = $conn->prepare("
        INSERT INTO meal_production_items (production_id, product_id, qty_used) 
        VALUES (?, ?, ?)
    ");
    $stmt_upd_products = $conn->prepare("UPDATE products SET quantity = quantity - ? WHERE id = ?");
    $stmt_upd_stock = $conn->prepare("
        UPDATE product_stock 
        SET quantity = quantity - ? 
        WHERE product_id = ? AND quantity >= ? 
        ORDER BY id ASC
        LIMIT 1
    ");

    foreach($ingredients as $row){
        $product_id = intval($row['material_id']);
        $used_qty   = floatval($row['total_qty']);
        $remaining  = $used_qty;

        // Insert into meal_production_items
        $stmt_ing->bind_param("iid", $production_id, $product_id, $used_qty);
        $stmt_ing->execute();

        // Deduct from products table
        $stmt_upd_products->bind_param("di", $used_qty, $product_id);
        $stmt_upd_products->execute();

        // Deduct from product_stock until fully consumed
        while($remaining > 0){
            $stock = $conn->query("
                SELECT id, quantity 
                FROM product_stock 
                WHERE product_id = $product_id AND quantity > 0 
                ORDER BY id ASC 
                LIMIT 1
            ")->fetch_assoc();

            if(!$stock) break;

            $deduct_qty = min($remaining, $stock['quantity']);
            $stmt_upd_stock->bind_param("dii", $deduct_qty, $product_id, $deduct_qty);
            $stmt_upd_stock->execute();

            $remaining -= $deduct_qty;
        }
    }

    $conn->commit();

    // ================== SEND EMAIL ==================
    $admin_emails = ["giantplusmw@gmail.com", "rams.investments@gmail.com"];
    $subject = "New Meal Production Created (#$production_id)";

    $email_message = '
    <html>
    <head>
      <title>Meal Production Notification</title>
      <style>
        body { font-family: Arial, sans-serif; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #2c3e50; color: #fff; }
      </style>
    </head>
    <body>
      <h2>Meal Production Completed</h2>
      <p>Production ID: '.$production_id.'</p>
      <p>Meal ID: '.$meal_id.' | Type: '.htmlspecialchars($meal_type).'</p>
      <p>Prepared by: '.htmlspecialchars($username).'</p>
      <p>Number of People: '.$peopleCount.'</p>

      <h3>Ingredients Used</h3>
      <table>
        <thead><tr><th>Ingredient</th><th>Qty Used</th></tr></thead>
        <tbody>';
    foreach($ingredients as $row){
        $prod_name = $conn->real_escape_string($row['name'] ?? 'Unknown');
        $used_qty  = floatval($row['total_qty']);
        $email_message .= '<tr><td>'.htmlspecialchars($prod_name).'</td><td>'.$used_qty.'</td></tr>';
    }
    $email_message .= '</tbody></table></body></html>';

    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From:cloud@gianterp.space" . "\r\n";

    foreach($admin_emails as $to){
        mail($to, $subject, $email_message, $headers);
    }
    // ==============================================

    echo json_encode(['success'=>true,'production_id'=>$production_id]);

} catch(Exception $e){
    $conn->rollback();
    echo json_encode(['success'=>false,'error'=>$e->getMessage()]);
}