<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';
require_once __DIR__ . '/../../core/permission_audit.php';

/* METHOD */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* RBAC */
require_permission($user, 'role_permissions', 'edit', $pdo);

/* INPUT */
$input = json_decode(file_get_contents('php://input'), true);

if (empty($input['role']) || empty($input['updates']) || !is_array($input['updates'])) {
    json_response(false, 'Invalid input.', [], 400);
}

$role_key = trim($input['role']);
$updates  = $input['updates'];

/* VALIDATE ROLE EXISTS */
$stmt = $pdo->prepare("SELECT COUNT(*) FROM roles WHERE role_key = ?");
$stmt->execute([$role_key]);

if ((int)$stmt->fetchColumn() === 0) {
    json_response(false, 'Invalid role.', [], 400);
}

/* PROTECT SUPER_ADMIN ROLE */
if ($role_key === 'super_admin') {
    json_response(false, 'Cannot modify super_admin permissions.', [], 403);
}

$pdo->beginTransaction();

try {

    foreach ($updates as $module_key => $actions) {

        /* VALIDATE MODULE EXISTS */
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM modules WHERE module_key = ?");
        $stmt->execute([$module_key]);

        if ((int)$stmt->fetchColumn() === 0) {
            continue; // skip invalid module
        }

        /* PROTECT ROLE PERMISSIONS MODULE */
        if ($module_key === 'role_permissions') {
            continue; // prevent self-lockout
        }

        /* FETCH OLD */
        $stmt = $pdo->prepare("
            SELECT *
            FROM role_permissions
            WHERE role = ?
            AND module_key = ?
            LIMIT 1
        ");
        $stmt->execute([$role_key, $module_key]);
        $old = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$old) {
            continue;
        }

        $can_view   = (int)($actions['view']   ?? 0);
        $can_create = (int)($actions['create'] ?? 0);
        $can_edit   = (int)($actions['edit']   ?? 0);
        $can_delete = (int)($actions['delete'] ?? 0);

        /* UPDATE */
        $update = $pdo->prepare("
            UPDATE role_permissions
            SET
                can_view = ?,
                can_create = ?,
                can_edit = ?,
                can_delete = ?
            WHERE role = ?
            AND module_key = ?
        ");

        $update->execute([
            $can_view,
            $can_create,
            $can_edit,
            $can_delete,
            $role_key,
            $module_key
        ]);

        /* AUDIT LOG */
        log_permission_change(
            $pdo,
            (int)$user['id'],
            $role_key,
            $module_key,
            $old,
            [
                'can_view'   => $can_view,
                'can_create' => $can_create,
                'can_edit'   => $can_edit,
                'can_delete' => $can_delete
            ]
        );
    }

    $pdo->commit();

} catch (Throwable $e) {
    $pdo->rollBack();
    json_response(false, 'Update failed.', [], 500);
}

/* ADMIN AUDIT */
log_admin_action(
    $pdo,
    (int)$user['id'],
    'role_permissions',
    'edit',
    null
);

json_response(true, 'Permissions updated successfully.');