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

$coid  = $_SESSION['co_id'];

session_write_close();

$names      = $_POST['user_id'] ?? [];
$category  = $_POST['categ'] ?? [];
$access = $_POST['access_lvl'] ?? [];
//$managers   = $_POST['manager_id'] ?? [];

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

$stmt = $pdo->prepare("
    INSERT INTO permissions (co_id, user_id,pm_acc_categ, pm_acc_lvl )
    VALUES (?, ?, ?, ?)
");

try {

    $pdo->beginTransaction();
    
        $coid = $_SESSION['co_id'];
    for ($i = 0; $i < count($names); $i++) {

        $user     = trim($names[$i] ?? '');
        $cat  = trim($category[$i] ?? '');
        $acc  = trim($access[$i] ??  '');
        //$manager   = trim($managers[$i] ?? '');

        // Skip completely empty rows
        if ($user === ''  && $cat === '' &&  $acc === '' ) {
            continue;
        }

        // Validate required fields
         if ($user === '' || $cat === '') {
            throw new Exception("Invalid Capacity on line" . ($i + 1));
        }
        
       

        $stmt->execute([$coid, $user, $cat, $acc]);
    }

    $pdo->commit();

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

} catch (Exception $e) {

    $pdo->rollBack();

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