<?php
session_start();
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'];

$names      = $_POST['user2_id'] ?? [];
$category  = $_POST['mnu'] ?? [];
$access = $_POST['access2_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,menu_access, 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()
    ]);
}
