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

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

// Get JSON data from front-end
$data = json_decode(file_get_contents('php://input'), true);

$number_of_people = intval($data['number_of_people'] ?? 0);
$items = $data['items'] ?? [];
$username = $_SESSION['username'] ?? 'Guest';

if(!$number_of_people || empty($items)){
    echo json_encode(['success'=>false,'error'=>'Missing required data']);
    exit;
}

// Begin transaction
$conn->begin_transaction();

try {
    // Insert into perishable_production table
    $stmt = $conn->prepare("
        INSERT INTO perishable_production (number_of_people, created_by, created_at) 
        VALUES (?,?,NOW())
    ");
    $stmt->bind_param("is", $number_of_people, $username);
    $stmt->execute();
    $production_id = $stmt->insert_id;

    // Insert each item into perishable_production_items
    $stmt_item = $conn->prepare("
        INSERT INTO perishable_production_items 
        (production_id, perishable_id, qty_per_person, people, total_needed, stock_available, status) 
        VALUES (?,?,?,?,?,?,?)
    ");

    $insufficient_items = [];

    foreach($items as $row){
        $perishable_id = intval($row['id']);
        $qty_per_person = floatval($row['qty_per_person']);
        $people = $number_of_people;
        $total_needed = $qty_per_person * $people;
        $stock_available = floatval($row['quantity']);
        $status = $stock_available >= $total_needed ? 'OK' : 'Insufficient';

        if($status === 'Insufficient'){
            $insufficient_items[] = $row['name'] ?? "Item #$perishable_id";
        }

        $stmt_item->bind_param(
            "iidddds",
            $production_id,
            $perishable_id,
            $qty_per_person,
            $people,
            $total_needed,
            $stock_available,
            $status
        );
        $stmt_item->execute();
    }

    $conn->commit();

    // ================= SEND EMAIL ALERT =================
    $admin_emails = [
        'giantplusmw@gmail.com',
        'rams.investments@gmail.com'
    ];

    $subject = "New Perishable Production Created by $username";

    $items_list = "";
    foreach($items as $row){
        $total_needed = floatval($row['qty_per_person']) * $number_of_people;
        $items_list .= "<tr>
            <td>".htmlspecialchars($row['name'] ?? 'Item')."</td>
            <td>".$row['qty_per_person']."</td>
            <td>".$number_of_people."</td>
            <td>".$total_needed."</td>
            <td>".$row['quantity']."</td>
        </tr>";
    }

    $message = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; background:#f4f6f8; padding:20px; }
            .box { max-width:700px; margin:auto; background:#ffffff; padding:20px; border-radius:8px; border-top:5px solid #28a745; }
            .title { font-size:20px; font-weight:bold; color:#28a745; margin-bottom:15px; }
            table { width:100%; border-collapse: collapse; }
            th, td { border:1px solid #ccc; padding:8px; text-align:left; }
            th { background:#28a745; color:#fff; }
        </style>
    </head>
    <body>
        <div class='box'>
            <div class='title'>📦 New Perishable Production Created</div>
            <p><strong>Created by:</strong> ".htmlspecialchars($username)."</p>
            <p><strong>Number of People:</strong> {$number_of_people}</p>
            <table>
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Qty per Person</th>
                        <th>People</th>
                        <th>Total Needed</th>
                        <th>Stock Available</th>
                    </tr>
                </thead>
                <tbody>
                    {$items_list}
                </tbody>
            </table>";

    if(!empty($insufficient_items)){
        $message .= "<p style='color:red;'><strong>Warning:</strong> Insufficient stock for: ".implode(", ", $insufficient_items)."</p>";
    }

    $message .= "
        </div>
    </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, $message, $headers);
    }

    // Generate a URL to view/print the requisition
    $requisition_url = "view_perishable_requisition.php?id={$production_id}";

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

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