<?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->ensureAdmin();

        $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->ensureAdmin();

        $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->ensureAdmin();

        $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->ensureAdmin();

        $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->ensureAdmin();

        $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->ensureAdmin();

        $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 generateExternalApiToken(): void
    {
        $this->ensureAdmin();
        $this->verifyCurrentAdminPassword($_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->ensureAdmin();
        $this->verifyCurrentAdminPassword($_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->ensureAdmin();

        $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;
        }

        $this->verifyCurrentAdminPassword($currentAdminPassword);

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

        $currentUserId = $_SESSION['user_id'] ?? 0;
        $currentUser = $this->authService->getCurrentUser();

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

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

    private function ensureAdmin(): void
    {
        if (!$this->authService->isAdmin()) {
            $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 (empty($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);
    }
}
