<?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->errorResponse('دسترسی محدود به مدیر سیستم', 403);
        }
    }

    public function getServiceCatalog(): void
    {
        $this->ensureAdmin();
        $this->successResponse(['services' => $this->repo->getServiceCatalog()]);
    }

    public function saveServiceCatalogItem(): void
    {
        $this->ensureAdmin();
        $id = $this->repo->saveServiceCatalogItem([
            'id' => $_POST['id'] ?? 0,
            'service_family' => $_POST['service_family'] ?? '',
            'support_mode' => $_POST['support_mode'] ?? '',
            'requires_full_payment_for_access' => $_POST['requires_full_payment_for_access'] ?? '',
            'external_access_code' => $_POST['external_access_code'] ?? '',
        ]);
        $this->successResponse(['id' => $id], 'تنظیمات خدمت ذخیره شد');
    }

    public function getProductServiceLinks(): void
    {
        $this->ensureAdmin();
        $this->successResponse([
            'products' => $this->repo->getProductsWithServices(),
            'services' => $this->repo->getServiceCatalog(),
        ]);
    }

    public function getRawServiceCandidates(): void
    {
        $this->ensureAdmin();
        $this->successResponse([
            'candidates' => $this->repo->getRawServiceCandidates(),
            'services' => $this->repo->getServiceCatalog(),
        ]);
    }

    public function saveRawServiceMapping(): void
    {
        $this->ensureAdmin();

        $currentUser = $this->authService->getCurrentUser();
        $displayName = '';
        if ($currentUser) {
            $displayName = trim((string)($currentUser->display_name ?? ''));
            if ($displayName === '') {
                $displayName = trim((string)(($currentUser->first_name ?? '') . ' ' . ($currentUser->last_name ?? '')));
            }
            if ($displayName === '') {
                $displayName = (string)($currentUser->email ?? '');
            }
        }

        $this->repo->saveRawMapping(
            (string)($_POST['raw_title'] ?? ''),
            (int)($_POST['service_lookup_item_id'] ?? 0),
            [
                'updated_by' => $displayName,
                'updated_by_user_id' => (int)($_SESSION['user_id'] ?? 0),
            ]
        );

        $this->successResponse([], 'نگاشت با موفقیت ذخیره شد');
    }

    public function getServiceDataQualityReport(): void
    {
        $this->ensureAdmin();
        $this->successResponse(['report' => $this->repo->getDataQualityReport()]);
    }

    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',
            'vip_match_strategy' => $_POST['vip_match_strategy'] ?? 'mobile_phone',
        ]);
        $this->successResponse(['settings' => $settings], 'تنظیمات مدیریت خدمات ذخیره شد');
    }
}
