<?php
namespace App\Controllers;

use App\Services\AuthService;
use App\Services\RbacService;
use App\Utils\Sanitizer;

class RbacController extends ApiController
{
    private RbacService $rbacService;
    private AuthService $authService;

    public function __construct(RbacService $rbacService, AuthService $authService)
    {
        $this->rbacService = $rbacService;
        $this->authService = $authService;
    }

    private function requireAdmin(): void
    {
        if (!$this->authService->isAdmin()) {
            $this->errorResponse('فقط ادمین مجاز است', 403);
        }
    }

    public function getCatalog(): void
    {
        $this->requireAdmin();
        $this->successResponse($this->rbacService->getCatalog());
    }

    public function getRolePermissions(): void
    {
        $this->requireAdmin();
        $roleKey = Sanitizer::sanitize($_REQUEST['role_key'] ?? '');
        if ($roleKey === '') {
            $this->errorResponse('role_key الزامی است');
        }
        $this->successResponse($this->rbacService->getRolePermissions($roleKey));
    }

    public function getCurrentPermissions(): void
    {
        if (!$this->authService->isAuthenticated()) {
            $this->errorResponse('Unauthenticated', 401);
        }
        $roleKey = (string)($_SESSION['role'] ?? 'agent');
        $payload = $this->rbacService->getRolePermissions($roleKey);
        $payload['current_role_key'] = $roleKey;
        $this->successResponse($payload);
    }

    public function saveRole(): void
    {
        $this->requireAdmin();
        $id = (int)($_POST['id'] ?? 0);
        $roleKey = Sanitizer::sanitize($_POST['role_key'] ?? '');
        $title = Sanitizer::sanitize($_POST['title'] ?? '');
        $isActive = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
        $templateFrom = Sanitizer::sanitize($_POST['template_from_role_key'] ?? '');
        $metaJson = $_POST['meta_json'] ?? null;

        $saved = $this->rbacService->saveRole([
            'id' => $id,
            'role_key' => $roleKey,
            'title' => $title,
            'is_active' => $isActive,
            'template_from_role_key' => $templateFrom,
            'meta_json' => $metaJson,
        ]);
        $this->successResponse(['role' => $saved], 'نقش ذخیره شد');
    }

    public function cloneRole(): void
    {
        $this->requireAdmin();
        $newRoleKey = Sanitizer::sanitize($_POST['new_role_key'] ?? '');
        $newTitle = Sanitizer::sanitize($_POST['new_title'] ?? '');
        $templateRoleKey = Sanitizer::sanitize($_POST['template_role_key'] ?? '');

        $saved = $this->rbacService->cloneRoleFromTemplate($newRoleKey, $newTitle, $templateRoleKey);
        $this->successResponse(['role' => $saved], 'نقش از تمپلیت ایجاد شد');
    }

    public function saveRoleCapabilities(): void
    {
        $this->requireAdmin();
        $roleKey = Sanitizer::sanitize($_POST['role_key'] ?? '');
        if ($roleKey === '') {
            $this->errorResponse('role_key الزامی است');
        }
        $raw = $_POST['capability_keys'] ?? [];
        if (!is_array($raw)) {
            $decoded = json_decode((string)$raw, true);
            $raw = is_array($decoded) ? $decoded : array_filter(array_map('trim', explode(',', (string)$raw)));
        }
        $this->rbacService->saveRoleCapabilities($roleKey, (array)$raw);
        $this->successResponse([], 'دسترسی‌های نقش ذخیره شد');
    }

    public function saveRoleScopes(): void
    {
        $this->requireAdmin();
        $roleKey = Sanitizer::sanitize($_POST['role_key'] ?? '');
        if ($roleKey === '') {
            $this->errorResponse('role_key الزامی است');
        }
        $raw = $_POST['scopes'] ?? '[]';
        if (is_array($raw)) {
            $scopes = $raw;
        } else {
            $decoded = json_decode((string)$raw, true);
            $scopes = is_array($decoded) ? $decoded : [];
        }
        $this->rbacService->saveRoleDataScopes($roleKey, $scopes);
        $this->successResponse([], 'محدوده‌های داده نقش ذخیره شد');
    }
}
