<?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'];

session_write_close();

$users     = $_POST['user1_id'] ?? [];
$accounts  = $_POST['account1_id'] ?? [];
$levels    = $_POST['access1_lvl'] ?? [];

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

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

try {

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

        $user_id    = trim($users[$i] ?? '');
        $account_id = trim($accounts[$i] ?? '');
        $level      = trim($levels[$i] ?? '');

        // Skip empty rows
        if ($user_id === '' && $account_id === '' && $level === '') {
            continue;
        }

        if ($user_id === '' || $account_id === '') {
            throw new Exception("Missing data on row " . ($i + 1));
        }

        $stmt->execute([$coid, $user_id, $account_id, $level]);
    }

    $pdo->commit();

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

} catch (Exception $e) {

    $pdo->rollBack();

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