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

$names      = $_POST['product_name'] ?? [];
$locations  = $_POST['sku'] ?? [];
$capacities = $_POST['product_type'] ?? [];
$managers   = $_POST['category_id'] ?? [];

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

$stmt = $pdo->prepare("
    INSERT INTO products (p_name, p_prch_px , p_sale_px, sale_comm)
    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()
    ]);
}
