<?php
namespace App\Controllers;

use App\Repositories\ConfigRepository;
use App\Services\AuthService;

class SettingsController extends ApiController
{
    private ConfigRepository $configRepo;
    private AuthService $authService;

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

    public function getDidarWriteSettings(): void
    {
        $this->ensureAdminOrDelegated('settings.admin.didar_write.manage');

        $value = $this->configRepo->getValue('didar_write_enabled', '1');
        $enabled = $this->normalizeFlag($value);

        $this->successResponse(['didar_write_enabled' => $enabled ? '1' : '0']);
    }

    public function saveDidarWriteSettings(): void
    {
        $this->ensureAdminOrDelegated('settings.admin.didar_write.manage');

        $raw = $_POST['didar_write_enabled'] ?? '1';
        $enabled = $this->normalizeFlag($raw);

        $this->configRepo->setValue('didar_write_enabled', $enabled ? '1' : '0');

        $this->successResponse(['didar_write_enabled' => $enabled ? '1' : '0'], 'تنظیمات با موفقیت ذخیره شد');
    }

    public function getAutoMigrationSettings(): void
    {
        $this->ensureAdminOrDelegated('settings.admin.auto_migration.manage');

        $value = $this->configRepo->getValue('auto_migration_enabled', '0');
        $enabled = $this->normalizeFlag($value);

        $this->successResponse(['auto_migration_enabled' => $enabled ? '1' : '0']);
    }

    public function saveAutoMigrationSettings(): void
    {
        $this->ensureAdminOrDelegated('settings.admin.auto_migration.manage');

        $raw = $_POST['auto_migration_enabled'] ?? '0';
        $enabled = $this->normalizeFlag($raw);

        $this->configRepo->setValue('auto_migration_enabled', $enabled ? '1' : '0');

        $this->successResponse(['auto_migration_enabled' => $enabled ? '1' : '0'], 'تنظیمات مایگریشن با موفقیت ذخیره شد');
    }

    public function getExternalApiSettings(): void
    {
        $this->ensureAdminOrDelegated('settings.admin.external_api.manage');

        $enabled = $this->normalizeFlag($this->configRepo->getValue('external_api_enabled', '0'));
        $token = trim((string)$this->configRepo->getValue('external_api_token', ''));

        $this->successResponse([
            'external_api_enabled' => $enabled ? '1' : '0',
            'token_configured' => $token !== '',
            'token_masked' => $this->maskToken($token),
            'endpoint' => '/?api=get_lead_assignment',
        ]);
    }

    public function saveExternalApiSettings(): void
    {
        $this->ensureAdminOrDelegated('settings.admin.external_api.manage');

        $raw = $_POST['external_api_enabled'] ?? '0';
        $enabled = $this->normalizeFlag($raw);
        $this->configRepo->setValue('external_api_enabled', $enabled ? '1' : '0');

        $token = trim((string)$this->configRepo->getValue('external_api_token', ''));
        $this->successResponse([
            'external_api_enabled' => $enabled ? '1' : '0',
            'token_configured' => $token !== '',
            'token_masked' => $this->maskToken($token),
        ], 'تنظیمات API خارجی با موفقیت ذخیره شد');
    }

    public function getAiSettings(): void
    {
        $this->ensureAdminOrDelegated('ai.admin.settings');

        $enabled = $this->normalizeFlag($this->configRepo->getValue('ai_feature_enabled', defined('OPENAI_FEATURE_ENABLED') ? OPENAI_FEATURE_ENABLED : '0'));
        $apiKey = trim((string)$this->configRepo->getValue('openai_api_key', defined('OPENAI_API_KEY') ? OPENAI_API_KEY : ''));
        $model = trim((string)$this->configRepo->getValue('openai_model', defined('OPENAI_MODEL') ? OPENAI_MODEL : ''));
        $apiBase = trim((string)$this->configRepo->getValue('openai_api_base', defined('OPENAI_API_BASE') ? OPENAI_API_BASE : ''));

        $this->successResponse([
            'ai_feature_enabled' => $enabled ? '1' : '0',
            'openai_configured' => $apiKey !== '',
            'openai_key_masked' => $this->maskToken($apiKey),
            'openai_model' => $model,
            'openai_api_base' => $apiBase,
        ]);
    }

    public function saveAiSettings(): void
    {
        $this->ensureAdminOrDelegated('ai.admin.settings');

        $enabled = $this->normalizeFlag($_POST['ai_feature_enabled'] ?? '0');
        $this->configRepo->setValue('ai_feature_enabled', $enabled ? '1' : '0');

        $this->successResponse([
            'ai_feature_enabled' => $enabled ? '1' : '0',
        ], 'تنظیمات هوش مصنوعی با موفقیت ذخیره شد');
    }

    public function generateExternalApiToken(): void
    {
        $this->ensureAdminOrDelegated('settings.admin.external_api.manage');
        $this->verifyCurrentAdminPassword((string)($_POST['current_admin_password'] ?? ''));

        $token = bin2hex(random_bytes(32));
        $this->configRepo->setValue('external_api_token', $token);
        $this->configRepo->setValue('external_api_enabled', '1');

        $currentUser = $this->authService->getCurrentUser();
        \App\Utils\Logger::logInfo('External API token generated', [
            'user_id' => $_SESSION['user_id'] ?? 0,
            'username' => $currentUser->display_name ?? $currentUser->email ?? '',
        ]);

        $this->successResponse([
            'external_api_enabled' => '1',
            'token_configured' => true,
            'token_masked' => $this->maskToken($token),
            'token' => $token,
            'endpoint' => '/?api=get_lead_assignment',
        ], 'API key جدید با موفقیت ایجاد شد');
    }

    public function revokeExternalApiToken(): void
    {
        $this->ensureAdminOrDelegated('settings.admin.external_api.manage');
        $this->verifyCurrentAdminPassword((string)($_POST['current_admin_password'] ?? ''));

        $this->configRepo->setValue('external_api_token', '');
        $this->configRepo->setValue('external_api_enabled', '0');

        $currentUser = $this->authService->getCurrentUser();
        \App\Utils\Logger::logInfo('External API token revoked', [
            'user_id' => $_SESSION['user_id'] ?? 0,
            'username' => $currentUser->display_name ?? $currentUser->email ?? '',
        ]);

        $this->successResponse([
            'external_api_enabled' => '0',
            'token_configured' => false,
            'token_masked' => '',
        ], 'API key حذف شد و API خارجی غیرفعال شد');
    }

    public function setMasterPassword(): void
    {
        $this->ensureAdminOrDelegated('settings.admin.master_password.manage');

        $currentAdminPassword = $_POST['current_admin_password'] ?? '';
        $newMasterPassword = $_POST['new_master_password'] ?? '';
        $confirmMasterPassword = $_POST['confirm_master_password'] ?? '';

        // Validate inputs
        if (empty($currentAdminPassword)) {
            $this->errorResponse('رمز عبور مدیر الزامی است');
            return;
        }

        if (empty($newMasterPassword)) {
            $this->errorResponse('رمز عبور اصلی جدید الزامی است');
            return;
        }

        if (strlen($newMasterPassword) < 6) {
            $this->errorResponse('رمز عبور اصلی باید حداقل 6 کاراکتر باشد');
            return;
        }

        if ($newMasterPassword !== $confirmMasterPassword) {
            $this->errorResponse('رمز عبور اصلی جدید و تأیید آن مطابقت ندارند');
            return;
        }

        // Verify admin's current password
        $currentUserId = $_SESSION['user_id'] ?? 0;
        $currentUser = $this->authService->getCurrentUser();
        
        if (!$currentUser || empty($currentUser->password) || !password_verify($currentAdminPassword, $currentUser->password)) {
            $this->errorResponse('رمز عبور مدیر اشتباه است');
            return;
        }

        // Hash and save master password
        $masterPasswordHash = password_hash($newMasterPassword, PASSWORD_DEFAULT);
        $this->configRepo->setValue('master_password_hash', $masterPasswordHash);

        \App\Utils\Logger::logInfo("Master password changed", [
            'user_id' => $currentUserId,
            'username' => $currentUser->display_name ?? $currentUser->email
        ]);

        $this->successResponse([], 'رمز عبور اصلی با موفقیت تنظیم شد');
    }

    private function ensureAdminOrDelegated(string $capabilityKey): void
    {
        if (!$this->authService->isAdmin() && !$this->hasDelegatedCapability($capabilityKey)) {
            $this->errorResponse('دسترسی محدود به مدیر سیستم');
        }
    }

    private function normalizeFlag($value): bool
    {
        $normalized = is_string($value) ? strtolower(trim($value)) : $value;
        return in_array($normalized, [1, '1', true, 'true', 'on', 'yes'], true);
    }

    private function verifyCurrentAdminPassword(string $currentAdminPassword): void
    {
        if ($currentAdminPassword === '') {
            $this->errorResponse('رمز عبور مدیر الزامی است');
            return;
        }

        $currentUser = $this->authService->getCurrentUser();
        if (!$currentUser || empty($currentUser->password) || !password_verify($currentAdminPassword, $currentUser->password)) {
            $this->errorResponse('رمز عبور مدیر اشتباه است');
            return;
        }
    }

    private function maskToken(string $token): string
    {
        $token = trim($token);
        if ($token === '') {
            return '';
        }

        $length = strlen($token);
        if ($length <= 8) {
            return str_repeat('*', $length);
        }

        return substr($token, 0, 4) . str_repeat('*', max(4, $length - 8)) . substr($token, -4);
    }
}
