<?php

declare(strict_types=1);

namespace App\EventSubscriber;

use App\Entity\Installation;
use App\Service\LicenseVerificationService;
use App\Service\TenantContext;
use App\Service\UpdateService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;

/**
 * Loads Installation state per request, checks license/demo status.
 * Replaces the old multi-tenant TenantSubscriber.
 */
class TenantSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly TenantContext $tenantContext,
        private readonly LicenseVerificationService $licenseVerifier,
        private readonly UpdateService $updateService,
        private readonly Environment $twig,
    ) {}

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => ['onKernelRequest', 255],
        ];
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $path = $event->getRequest()->getPathInfo();

        // Profiler, assets skip
        if (str_starts_with($path, '/_') || str_starts_with($path, '/build')) {
            return;
        }

        // Installation kaydını yükle
        $installation = $this->entityManager->getRepository(Installation::class)->find(1);

        if (!$installation) {
            // Henüz kurulum yapılmamış
            if (!str_contains($path, 'install')) {
                $event->setResponse(new Response(
                    '<html><body><h1>Kurulum Gerekli</h1><p><a href="/install.php">Kuruluma Git</a></p></body></html>',
                    200
                ));
            }
            return;
        }

        // TenantContext'e installation'ı set et
        $this->tenantContext->setInstallation($installation);

        // Lisans ayarları sayfasına her zaman erişim ver
        if (str_starts_with($path, '/admin/settings/license')) {
            return;
        }

        // 6 saatlik lisans doğrulama
        if ($installation->getLicenseKey() && $installation->shouldVerify()) {
            $this->licenseVerifier->verify($installation);
        }

        // 6 saatlik güncelleme kontrolü
        if ($installation->shouldCheckUpdate()) {
            try {
                $this->updateService->checkForUpdate($installation);
            } catch (\Exception) {
                // Güncelleme kontrolü başarısız olursa sessizce devam et
            }
        }

        // Demo modu - süresi dolduysa
        if ($installation->isDemo() && $installation->isDemoExpired()) {
            if (str_starts_with($path, '/admin')) {
                return; // Admin panele erişim ver ki lisans girebilsin
            }

            try {
                $html = $this->twig->render('error/demo_expired.html.twig');
            } catch (\Exception) {
                $html = $this->buildErrorHtml(
                    'Demo Süresi Doldu',
                    'Demo süreniz sona erdi. Kullanmaya devam etmek için bir lisans anahtarı girin.',
                    '/admin/settings/license'
                );
            }

            $event->setResponse(new Response($html, 403));
            return;
        }

        // Lisans süresi dolduysa (grace period: 7 gün)
        if ($installation->isExpired()) {
            $days = $installation->getDaysUntilExpiry();
            $gracePeriodOver = $days !== null && $days < -7;

            if ($gracePeriodOver) {
                if (str_starts_with($path, '/admin')) {
                    return;
                }

                try {
                    $html = $this->twig->render('error/license_expired.html.twig');
                } catch (\Exception) {
                    $html = $this->buildErrorHtml(
                        'Lisans Süresi Doldu',
                        'Lisansınızın süresi dolmuş. Lütfen lisansınızı yenileyin.',
                        '/admin/settings/license'
                    );
                }

                $event->setResponse(new Response($html, 403));
            }
        }
    }

    private function buildErrorHtml(string $title, string $message, string $link): string
    {
        return <<<HTML
<!DOCTYPE html>
<html lang="tr">
<head><meta charset="UTF-8"><title>{$title}</title>
<style>body{font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f8f9fa}
.box{text-align:center;padding:40px;background:#fff;border-radius:12px;box-shadow:0 4px 24px rgba(0,0,0,.08)}
h1{color:#1a1a2e;margin-bottom:8px}p{color:#666;margin-bottom:24px}
a{display:inline-block;padding:10px 24px;background:#635bff;color:#fff;text-decoration:none;border-radius:8px;font-weight:600}</style>
</head>
<body><div class="box"><h1>{$title}</h1><p>{$message}</p><a href="{$link}">Lisans Ayarları</a></div></body>
</html>
HTML;
    }
}
