<?php
namespace App\Controllers;

use App\Repositories\ServiceGovernanceRepository;
use App\Repositories\UserRepository;
use App\Services\AuthService;

class ServiceGovernanceController extends ApiController
{
    private ServiceGovernanceRepository $repo;
    private UserRepository $userRepo;
    private AuthService $authService;

    public function __construct(ServiceGovernanceRepository $repo, UserRepository $userRepo, AuthService $authService)
    {
        $this->repo = $repo;
        $this->userRepo = $userRepo;
        $this->authService = $authService;
    }

    private function ensureAdmin(): void
    {
        if (!$this->authService->isAdmin() && !$this->hasDelegatedCapability('service_governance.admin.manage')) {
            $this->errorResponse('دسترسی محدود به مدیر سیستم', 403);
        }
    }

    public function getServiceGovernanceSettings(): void
    {
        $this->ensureAdmin();
        $users = array_map(static function ($user): array {
            $displayName = trim((string)($user->display_name ?? ''));
            if ($displayName === '') {
                $displayName = trim((string)(($user->first_name ?? '') . ' ' . ($user->last_name ?? '')));
            }
            return [
                'id' => (int)($user->id ?? 0),
                'didar_user_id' => (string)($user->didar_user_id ?? ''),
                'display_name' => $displayName,
                'email' => (string)($user->email ?? ''),
                'role' => (string)($user->role ?? ''),
                'is_active' => (int)($user->is_active ?? 1),
            ];
        }, $this->userRepo->getAll());

        $this->successResponse([
            'settings' => $this->repo->getGovernanceSettings(),
            'users' => $users,
        ]);
    }

    public function saveServiceGovernanceSettings(): void
    {
        $this->ensureAdmin();
        $settings = $this->repo->saveGovernanceSettings([
            'app_source_code' => $_POST['app_source_code'] ?? 'mobile_app',
            'app_default_owner_didar_id' => $_POST['app_default_owner_didar_id'] ?? '',
            'vip_effective_deal_strategy' => $_POST['vip_effective_deal_strategy'] ?? 'latest_vip_deal',
        ]);
        $this->successResponse(['settings' => $settings], 'تنظیمات مدیریت خدمات ذخیره شد');
    }
}
