<?php
// api/acl.php — Role & Permissions boshqaruvi API
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
date_default_timezone_set('Asia/Tashkent');

session_start();

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth_stub.php';

function json_ok(array $data = [], int $code = 200): void {
    http_response_code($code);
    echo json_encode(['status' => 'ok'] + $data, JSON_UNESCAPED_UNICODE);
    exit;
}

function json_error(string $msg, int $code = 400, array $extra = []): void {
    http_response_code($code);
    echo json_encode(['status' => 'error', 'message' => $msg] + $extra, JSON_UNESCAPED_UNICODE);
    exit;
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {

    // === 5) Joriy user permissionlari (front uchun) ===
    if ($action === 'me_permissions') {
        // faqat login bo‘lsin – admin bo‘lishi shart emas
        require_login();

        // current_user_permissions() HOZIR associative array qaytaradi ['users.view' => true, ...]
        $map = current_user_permissions();
        $codes = array_keys($map); // FRONTGA faqat code lar ketadi

        json_ok([
            'user_id'     => current_user_id(),
            'role_id'     => current_user_role_id(),
            'role_name'   => current_user_role_name(),
            'permissions' => $codes, // !!! endi massiv
        ]);
    }

    // Qolgan barcha actionlar uchun roles.manage kerak:
    if (in_array($action, ['get_roles', 'get_permissions', 'get_role_permissions', 'save_role_permissions'], true)) {
        require_permission('roles.manage');
    }

    // === 1) Rollar ro‘yxati ===
    if ($action === 'get_roles') {
        $stmt = $pdo->query("
            SELECT id, code, name, description
            FROM roles
            ORDER BY id
        ");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        json_ok(['roles' => $rows]);
    }

    // === 2) Permissionlar ro‘yxati ===
    if ($action === 'get_permissions') {
        $stmt = $pdo->query("
            SELECT id, code, name, description
            FROM permissions
            ORDER BY code
        ");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        json_ok(['permissions' => $rows]);
    }

    // === 3) Bitta rol permissionlari ===
    if ($action === 'get_role_permissions') {
        $roleId = isset($_GET['role_id']) ? (int)$_GET['role_id'] : 0;
        if ($roleId <= 0) {
            json_error('role_id noto‘g‘ri', 422);
        }

        $stmt = $pdo->prepare("
            SELECT permission_id
            FROM role_permissions
            WHERE role_id = :rid
        ");
        $stmt->execute([':rid' => $roleId]);
        $ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

        json_ok([
            'role_id'       => $roleId,
            'permission_ids'=> array_map('intval', $ids),
        ]);
    }

    // === 4) Role permissionlarini saqlash ===
    if ($action === 'save_role_permissions') {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            json_error('POST bo‘lishi kerak', 405);
        }

        $roleId = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
        if ($roleId <= 0) {
            json_error('role_id noto‘g‘ri', 422);
        }

        $ids = $_POST['permission_ids'] ?? [];
        if (!is_array($ids)) $ids = [];
        $ids = array_map('intval', $ids);
        $ids = array_values(array_unique($ids));

        try {
            $pdo->beginTransaction();

            $del = $pdo->prepare("DELETE FROM role_permissions WHERE role_id = :rid");
            $del->execute([':rid' => $roleId]);

            if (!empty($ids)) {
                $ins = $pdo->prepare("
                    INSERT INTO role_permissions (role_id, permission_id)
                    VALUES (:rid, :pid)
                ");
                foreach ($ids as $pid) {
                    $ins->execute([
                        ':rid' => $roleId,
                        ':pid' => $pid,
                    ]);
                }
            }

            $pdo->commit();

            if (current_user_role_id() === $roleId) {
                unset($_SESSION['user_permissions']);
            }

            json_ok(['message' => 'Ruxsatlar saqlandi', 'role_id' => $roleId]);
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            json_error('Saqlashda xatolik', 500, ['error' => $e->getMessage()]);
        }
    }

    json_error('Noto‘g‘ri action', 404);

} catch (Throwable $e) {
    json_error('Server xatosi', 500, ['error' => $e->getMessage()]);
}
