<?php
session_start();
require 'db.php';
header('Content-Type: application/json');
/* ==========================
   AUTH CHECK
========================== */
if (!isset($_SESSION['co_id'])) {
    echo json_encode(["status" => "error", "message" => "Unauthorized"]);
    exit;
}

$coid  = $_SESSION['co_id'];

session_write_close();

$names      = $_POST['product_name'] ?? [];
$sku  = $_POST['sku'] ?? [];
$product_type = $_POST['product_type'] ?? [];
$status  = $_POST['status'] ?? [];
$category_id = $_POST['category_id'] ?? [];
$sales_rep = $_POST['sales_rep'] ?? [];
$rep_sort = $_POST['rep_sort'] ?? [];
$selling_price = $_POST['selling_price'] ?? [];
$sale_comm = $_POST['sale_comm'] ?? [];
$sale_tax_rate = $_POST['sale_tax_rate'] ?? [];
$admin_comm = $_POST['admin_comm'] ?? [];
$prch_price = $_POST['prch_price'] ?? [];
$prch_comm = $_POST['prch_comm'] ?? [];
$prch_tax_rate = $_POST['prch_tax_rate'] ?? [];
$margin = $_POST['margin'] ?? [];

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

$stmt = $pdo->prepare("
    INSERT INTO products (co_id, p_name, sku , pdt_type, status, pdt_categ, sale_count, reporting_order, p_sale_px, sale_comm, sale_vat, admin_fee, p_prch_px, prch_comm, inp_vat, margin  )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

try {

    $pdo->beginTransaction();
  
        $coid = $_SESSION['co_id'];
    for ($i = 0; $i < count($names); $i++) {
        //$coid      = trim($coid[$i] ?? '');
        $name      = trim($names[$i] ?? '');
        $sku  = trim($sku[$i] ?? '');
        $product_type  = trim($product_type[$i] ?? '');
        $status   = trim($status[$i] ?? '');
        $category_id   = trim($category_id[$i] ?? '');
        $sales_rep   = trim($sales_rep[$i] ?? '');
        $rep_sort   = trim($rep_sort[$i] ?? '');
        $selling_price   = trim($selling_price[$i] ?? '');
        $sale_comm   = trim($sale_comm[$i] ?? '');
        $sale_tax_rate   = trim($sale_tax_rate[$i] ?? '');
        $admin_comm   = trim($admin_comm[$i] ?? '');
        $prch_price   = trim($prch_price[$i] ?? '');
        $prch_comm   = trim($prch_comm[$i] ?? '');
        $prch_tax_rate   = trim($prch_tax_rate[$i] ?? '');
        $margin   = trim($margin[$i] ?? '');

        // Skip completely empty rows
        if ($name === '' && $sku === '' && $product_type === '' && $status === '') {
            continue;
        }

        // Validate required fields
        if ($name === '' || $product_type === '' || $status === '') {
            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([$coid, $name, $sku, $product_type, $status, $category_id,$sales_rep, $rep_sort, $selling_price, $sale_comm, $sale_tax_rate , $admin_comm, $prch_price, $prch_comm, $prch_tax_rate, $margin ]);
    }

    $pdo->commit();

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

} catch (Exception $e) {

    $pdo->rollBack();

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