<?php
require 'db.php';
header('Content-Type: application/json');

$names      = $_POST['warehouse_name'] ?? [];
$locations  = $_POST['location'] ?? [];
$capacities = $_POST['capacity'] ?? [];
$managers   = $_POST['manager_id'] ?? [];

if (empty($names)) {
    echo json_encode(["status" => "error", "message" => "No data received"]);
    exit;
}

$stmt = $pdo->prepare("
    INSERT INTO warehouses (warehouse_name, location, capacity, manager)
    VALUES (?, ?, ?, ?)
");

try {

    $pdo->beginTransaction();

    for ($i = 0; $i < count($names); $i++) {

        $name      = trim($names[$i] ?? '');
        $location  = trim($locations[$i] ?? '');
        $capacity  = (int)($capacities[$i] ?? 0);
        $manager   = trim($managers[$i] ?? '');

        // Skip completely empty rows
        if ($name === '' && $location === '' && $capacity === 0 && $manager === '') {
            continue;
        }

        // Validate required fields
        if ($name === '' || $location === '' || $capacity <= 0 ) {
            throw new Exception("Invalid Capacity on line" . ($i + 1));
        }
        
        // Validate required fields
        if ( $manager === '') {
            throw new Exception("Manager does not exist on line" . ($i + 1));
        }

        $stmt->execute([$name, $location, $capacity, $manager]);
    }

    $pdo->commit();

    echo json_encode(["status" => "success"]);

} catch (Exception $e) {

    $pdo->rollBack();

    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);
}
