<?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'];
$names = $_POST['pdt_categname'] ?? [];

session_write_close();

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

$stmt = $pdo->prepare("
    INSERT INTO product_category (co_id, categ_name)
    VALUES (?, ?)
");

try {

    $pdo->beginTransaction();

    foreach ($names as $index => $rawName) {

        $name = trim($rawName);

        // Skip empty rows
        if ($name === '') {
            continue;
        }

        if (strlen($name) < 2) {
            throw new Exception("Category name too short on line " . ($index + 1));
        }

        $stmt->execute([$coid, $name]);
    }

    $pdo->commit();

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

} catch (Exception $e) {

    $pdo->rollBack();

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