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

        // 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 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);
    }
}
