<?php

namespace App\Controller\Admin;

use App\Entity\Tenant\Setting;
use App\Service\LicenseEnforcementService;
use App\Service\PlanFeatureService;
use App\Service\TenantContext;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class SettingsController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly TenantContext $tenantContext,
        private readonly PlanFeatureService $planFeatureService,
        private readonly LicenseEnforcementService $enforcementService,
    ) {}

    #[Route('/settings', name: 'admin_settings', methods: ['GET', 'POST'])]
    public function index(Request $request): Response
    {
        if ($request->isMethod('POST')) {
            if (!$this->isCsrfTokenValid('site_settings', $request->request->get('_token'))) {
                $this->addFlash('error', 'Geçersiz CSRF token. Lütfen tekrar deneyin.');

                return $this->redirectToRoute('admin_settings');
            }

            $repo = $this->entityManager->getRepository(Setting::class);

            // Define all settings with their groups and types
            $settingFields = [
                // Genel (General)
                'site_title' => ['group' => 'genel', 'type' => 'text'],
                'site_description' => ['group' => 'genel', 'type' => 'textarea'],
                'site_keywords' => ['group' => 'genel', 'type' => 'textarea'],
                'admin_email' => ['group' => 'genel', 'type' => 'text'],
                'timezone' => ['group' => 'genel', 'type' => 'text'],
                'language' => ['group' => 'genel', 'type' => 'text'],
                'contact_phone' => ['group' => 'genel', 'type' => 'text'],
                // Haber (News)
                'news_per_page' => ['group' => 'haber', 'type' => 'number'],
                'default_news_status' => ['group' => 'haber', 'type' => 'text'],
                'auto_publish_agency' => ['group' => 'haber', 'type' => 'boolean'],
                'allow_comments_default' => ['group' => 'haber', 'type' => 'boolean'],
                'comment_moderation' => ['group' => 'haber', 'type' => 'boolean'],
                // SEO
                'google_analytics_id' => ['group' => 'seo', 'type' => 'text'],
                'google_tag_manager' => ['group' => 'seo', 'type' => 'text'],
                'meta_robots_default' => ['group' => 'seo', 'type' => 'text'],
                'sitemap_enabled' => ['group' => 'seo', 'type' => 'boolean'],
                'canonical_base_url' => ['group' => 'seo', 'type' => 'text'],
                // Sosyal Medya (Social)
                'og_default_image' => ['group' => 'sosyal_medya', 'type' => 'text'],
                'twitter_card_type' => ['group' => 'sosyal_medya', 'type' => 'text'],
                'facebook_app_id' => ['group' => 'sosyal_medya', 'type' => 'text'],
                // Email
                'smtp_host' => ['group' => 'email', 'type' => 'text'],
                'smtp_port' => ['group' => 'email', 'type' => 'number'],
                'smtp_username' => ['group' => 'email', 'type' => 'text'],
                'from_email' => ['group' => 'email', 'type' => 'text'],
                'from_name' => ['group' => 'email', 'type' => 'text'],
                // Guvenlik (Security)
                'max_login_attempts' => ['group' => 'guvenlik', 'type' => 'number'],
                'session_lifetime' => ['group' => 'guvenlik', 'type' => 'number'],
                'maintenance_mode' => ['group' => 'guvenlik', 'type' => 'boolean'],
            ];

            foreach ($settingFields as $key => $config) {
                $value = $request->request->get($key);

                // Handle boolean fields
                if ($config['type'] === 'boolean') {
                    $value = $value ? '1' : '0';
                }

                $setting = $repo->findOneBy(['settingKey' => $key]);
                if (!$setting) {
                    $setting = new Setting();
                    $setting->setSettingKey($key);
                    $setting->setSettingGroup($config['group']);
                    $setting->setSettingType($config['type']);
                    $this->entityManager->persist($setting);
                }

                $setting->setSettingValue($value);
            }

            $this->entityManager->flush();

            $this->addFlash('success', 'Ayarlar başarıyla kaydedildi.');

            return $this->redirectToRoute('admin_settings');
        }

        // GET: Load all settings
        $allSettings = $this->entityManager->getRepository(Setting::class)->findAll();

        $settingsMap = [];
        foreach ($allSettings as $setting) {
            $settingsMap[$setting->getSettingKey()] = $setting->getSettingValue();
        }

        // Prepare license data for the license tab
        $licenseData = $this->prepareLicenseData();

        return $this->render('admin/settings/index.html.twig', [
            'settings' => $settingsMap,
            'licenseData' => $licenseData,
        ]);
    }

    #[Route('/settings/activate-license', name: 'admin_settings_activate_license', methods: ['POST'])]
    public function activateLicense(Request $request): Response
    {
        if (!$this->isCsrfTokenValid('activate_license', $request->request->get('_token'))) {
            $this->addFlash('error', 'Geçersiz CSRF token.');
            return $this->redirectToRoute('admin_settings', ['tab' => 'lisans']);
        }

        $licenseKey = trim((string) $request->request->get('license_key', ''));

        if ($licenseKey === '') {
            $this->addFlash('error', 'Lisans anahtarı boş olamaz.');
            return $this->redirectToRoute('admin_settings', ['tab' => 'lisans']);
        }

        $tenant = $this->tenantContext->getTenant();
        if (!$tenant) {
            $this->addFlash('error', 'Tenant bilgisi bulunamadı.');
            return $this->redirectToRoute('admin_settings', ['tab' => 'lisans']);
        }

        // Find the license by key in the central DB
        $license = $this->entityManager->getRepository(License::class)
            ->findOneBy(['licenseKey' => $licenseKey]);

        if (!$license) {
            $this->addFlash('error', 'Geçersiz lisans anahtarı. Lütfen doğru anahtarı girdiğinizden emin olun.');
            return $this->redirectToRoute('admin_settings', ['tab' => 'lisans']);
        }

        // Check if the license belongs to this tenant
        if ($license->getTenant()->getId() !== $tenant->getId()) {
            $this->addFlash('error', 'Bu lisans anahtarı bu siteye ait değil.');
            return $this->redirectToRoute('admin_settings', ['tab' => 'lisans']);
        }

        // Check if the license is active
        if (!$license->isActive()) {
            $this->addFlash('error', 'Bu lisans pasif durumda. Lütfen yöneticinizle iletişime geçin.');
            return $this->redirectToRoute('admin_settings', ['tab' => 'lisans']);
        }

        // Check expiry
        $expiresAt = $license->getExpiresAt();
        if ($expiresAt !== null && $expiresAt < new \DateTimeImmutable()) {
            $this->addFlash('error', 'Bu lisansın süresi dolmuş. Lütfen yöneticinizle iletişime geçin.');
            return $this->redirectToRoute('admin_settings', ['tab' => 'lisans']);
        }

        // Update the tenant's plan from the license
        $tenant->setPlan($license->getPlan());
        if ($tenant->getStatus() === 'trial') {
            $tenant->setStatus('active');
        }
        $this->entityManager->flush();

        // Update TenantContext so the rest of the request sees the new license
        $this->tenantContext->setLicense($license);

        $planName = $this->planFeatureService->getPlanDisplayName($license->getPlan());
        $this->addFlash('success', sprintf(
            'Lisans başarıyla aktive edildi! Plan: %s | Anahtar: %s',
            $planName,
            $licenseKey
        ));

        return $this->redirectToRoute('admin_settings', ['tab' => 'lisans']);
    }

    /**
     * Prepare license/plan data for the settings license tab.
     */
    private function prepareLicenseData(): array
    {
        $license = $this->tenantContext->getLicense();
        $plan = $this->tenantContext->getPlan();
        $planDisplayName = $this->planFeatureService->getPlanDisplayName($plan);
        $planLimits = $this->planFeatureService->getDefaultLimits($plan);
        $planFeatures = $this->planFeatureService->getPlanFeatures($plan);
        $featureLabels = $this->planFeatureService->getFeatureLabels();
        $allowedModules = $this->planFeatureService->getAllowedModules($plan);

        $usage = $this->enforcementService->getUsageSummary();

        $moduleLabels = [
            'menu' => 'Menü Yönetimi',
            'comment' => 'Yorum Sistemi',
            'seo' => 'SEO Araçları',
            'widget' => 'Widget Sistemi',
            'advertisement' => 'Reklam Yönetimi',
            'poll' => 'Anket Modülü',
            'theme' => 'Tema Yönetimi',
            'amp' => 'AMP Desteği',
            'agency' => 'Ajans Haberleri',
            'horoscope' => 'Burç Yorumları',
        ];

        return [
            'hasLicense' => $license !== null,
            'licenseKey' => $license?->getLicenseKey(),
            'plan' => $plan,
            'planDisplayName' => $planDisplayName,
            'type' => $license?->getType(),
            'startsAt' => $license?->getStartsAt(),
            'expiresAt' => $license?->getExpiresAt(),
            'isActive' => $license?->isActive() ?? false,
            'daysUntilExpiry' => $this->tenantContext->getDaysUntilExpiry(),
            'limits' => $planLimits,
            'features' => $planFeatures,
            'featureLabels' => $featureLabels,
            'allowedModules' => $allowedModules,
            'moduleLabels' => $moduleLabels,
            'usage' => [
                'users' => ['current' => $usage->users->current, 'max' => $usage->users->max, 'percentUsed' => $usage->users->percentUsed],
                'news' => ['current' => $usage->news->current, 'max' => $usage->news->max, 'percentUsed' => $usage->news->percentUsed],
                'storage' => ['current' => $usage->storage->current, 'max' => $usage->storage->max, 'percentUsed' => $usage->storage->percentUsed],
            ],
        ];
    }
}
