<?php
// save_inventory_ajax.php
header('Content-Type: application/json');
require_once("../config/config.php");

$response = ['status' => 'error', 'message' => 'Invalid request'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['warehouse_id'])) {
    $warehouse_id = (int)$_POST['warehouse_id'];
    $items = $_POST['items'] ?? [];

    if ($warehouse_id <= 0) {
        $response['message'] = "Please select a warehouse.";
    } elseif (empty($items)) {
        $response['message'] = "No materials to save.";
    } else {
        $inserted = 0;
        foreach ($items as $item) {
            $sku = trim($item['sku'] ?? '');
            $name = trim($item['name'] ?? '');
            $description = trim($item['description'] ?? '');
            $hsn_sac = trim($item['hsn_sac'] ?? '');
            $category = trim($item['category'] ?? '');
            $model_no = trim($item['model_no'] ?? '');
            $supplier_vendor = trim($item['supplier_vendor'] ?? '');
            $uom = trim($item['uom'] ?? '');
            $initial_stock = (float)($item['initial_stock'] ?? 0);
            $reorder_level = (float)($item['reorder_level'] ?? 0);

            if (empty($name) || empty($sku) || empty($hsn_sac) || empty($supplier_vendor)) {
                continue;
            }

            $stmt = $conn->prepare("INSERT INTO inventory_master 
                (sku, name, description, hsn_sac, category, warehouse_id, model_no, 
                 supplier_vendor, uom, current_stock, reorder_level) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

            $stmt->bind_param("sssssisssdd", 
                $sku, $name, $description, $hsn_sac, $category, $warehouse_id,
                $model_no, $supplier_vendor, $uom, $initial_stock, $reorder_level
            );

            if ($stmt->execute()) {
                $inserted++;
            }
            $stmt->close();
        }

        if ($inserted > 0) {
            $response = [
                'status' => 'success',
                'message' => "$inserted material(s) added successfully!"
            ];
        } else {
            $response['message'] = "No valid materials were saved.";
        }
    }
}

echo json_encode($response);
?>