<?php

namespace App\Controller\Dashboard;

use App\Repository\CustomerRepository;
use App\Repository\DevisRepository;
use App\Repository\ProductRepository;
use App\Repository\SitePerformanceRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

use App\Service\Pdf\CertificatOnlinePdfService;

#[Route('/crm')]
class HomeController extends AbstractController
{
    private const UMAMI_WEBSITE_ID = "38d713c3-3923-4791-875a-dfe5f45372c3";
    private const UMAMI_BASE_URL = "https://tools-security.esy-web.dev/api";

    public function __construct(
        private readonly ProductRepository $productRepository,
        private readonly CustomerRepository $customerRepository,
        private readonly DevisRepository $devisRepository,
        private readonly SitePerformanceRepository $sitePerformanceRepository,
        private readonly HttpClientInterface $httpClient,
        private readonly CacheInterface $cache,
        #[Autowire('%kernel.project_dir%')]
        private readonly string $projectDir
    ) {
    }

    #[Route('/certificat/online', name: 'app_crm_certificat_online', methods: ['GET'])]
    public function downloadCertificat(CertificatOnlinePdfService $pdfService): Response
    {
        $content = $pdfService->generate();

        return new Response($content, 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'inline; filename="certificat_mise_en_ligne.pdf"'
        ]);
    }

    #[Route('', name: 'app_crm', options: ['sitemap' => false], methods: ['GET'])]
    public function index(): Response
    {
        $stats = $this->getUmamiStats();
        $updates = $this->getSystemUpdates();

        return $this->render('dashboard/home.twig', [
            'product' => $this->productRepository->count([]),
            'devis_wait_sign' => $this->devisRepository->waitSign(),
            'customers' => $this->customerRepository->count([]),
            'nbVisitor' => $stats['visitors'],
            'nbView' => $stats['views'],
            'source_google' => $stats['sources']['google'] ?? 0,
            'source_facebook' => $stats['sources']['facebook'] ?? 0,
            'source_instagram' => $stats['sources']['instagram'] ?? 0,
            'source_tiktok' => $stats['sources']['tiktok'] ?? 0,
            'source_other' => $stats['sources']['other'] ?? 0,
            'statview' => "https://tools-security.esy-web.dev/share/o9j2XMjV4Trnnbfb",
            'updates' => $updates,
            'avg_lcp' => $this->sitePerformanceRepository->getMoyenStat('lcp'),
            'avg_inp' => $this->sitePerformanceRepository->getMoyenStat('inp'),
            'avg_cls' => $this->sitePerformanceRepository->getMoyenStat('cls'),
        ]);
    }

    // --- PRIVATE HELPERS ---

    /**
     * Récupère les statistiques de visite via l'API Umami (avec mise en cache)
     */
    private function getUmamiStats(): array
    {
        // 1. Récupération du Token (Cache 2h)
        $token = $this->cache->get('umami_token', function (ItemInterface $item) {
            $item->expiresAfter(7200);

            try {
                $response = $this->httpClient->request('POST', self::UMAMI_BASE_URL . '/auth/login', [
                    'json' => [
                        'username' => $_ENV['UMAMI_USER'],
                        'password' => $_ENV['UMAMI_PASSWORD'],
                    ]
                ]);
                return $response->toArray()['token'] ?? null;
            } catch (\Exception $e) {
                return null;
            }
        });

        // 2. Récupération des Stats (Cache 15min)
        return $this->cache->get('umami_stats_24h', function (ItemInterface $item) use ($token) {
            $item->expiresAfter(900);

            if (!$token) {
                return ['visitors' => 0, 'views' => 0];
            }

            try {
                $startAt = (time() - (24 * 3600)) * 1000;
                $endAt = time() * 1000;

                // 1. General Stats
                $response = $this->httpClient->request('GET', self::UMAMI_BASE_URL . '/websites/' . self::UMAMI_WEBSITE_ID . '/stats', [
                    'headers' => ['Authorization' => "Bearer $token"],
                    'query' => ['startAt' => $startAt, 'endAt' => $endAt],
                ]);
                $data = $response->toArray();

                // 2. Referrer Metrics
                $metricsResponse = $this->httpClient->request('GET', self::UMAMI_BASE_URL . '/websites/' . self::UMAMI_WEBSITE_ID . '/metrics', [
                    'headers' => ['Authorization' => "Bearer $token"],
                    'query' => [
                        'startAt' => $startAt,
                        'endAt' => $endAt,
                        'type' => 'referrer'
                    ],
                ]);
                $referrers = $metricsResponse->toArray();
                // 3. Process Sources
                $sources = [
                    'google' => 0,
                    'facebook' => 0,
                    'instagram' => 0,
                    'tiktok' => 0,
                    'other' => 0
                ];

                foreach ($referrers as $ref) {
                    // Structure depends on API version, usually object with x (value) and y (count)
                    // Assuming generic format: ['x' => 'google.com', 'y' => 123]
                    $domain = strtolower($ref['x'] ?? '');
                    $count = $ref['y'] ?? 0;

                    if (str_contains($domain, 'google')) {
                        $sources['google'] += $count;
                    } elseif (str_contains($domain, 'facebook')) {
                        $sources['facebook'] += $count;
                    } elseif (str_contains($domain, 'instagram')) {
                        $sources['instagram'] += $count;
                    } elseif (str_contains($domain, 'tiktok')) {
                        $sources['tiktok'] += $count;
                    } else {
                        $sources['other'] += $count;
                    }
                }

                return [
                    'visitors' => $data['visitors']['value'] ?? $data['visitors'] ?? 0,
                    'views' => $data['pageviews']['value'] ?? $data['pageviews'] ?? 0,
                    'sources' => $sources
                ];
            } catch (\Exception $e) {
                dd($e);
                return [
                    'visitors' => 0,
                    'views' => 0,
                    'sources' => [
                        'google' => 0, 'facebook' => 0, 'instagram' => 0, 'tiktok' => 0, 'other' => 0
                    ]
                ];
            }
        });
    }

    /**
     * Récupère et formate le journal de bord des mises à jour
     */
    private function getSystemUpdates(): array
    {
        $updateFile = $this->projectDir . '/var/update.json';

        if (!file_exists($updateFile)) {
            return [];
        }

        $rawUpdates = json_decode(file_get_contents($updateFile), true) ?? [];

        return array_map(function ($update) {
            $update['tag_color'] = match ($update['type'] ?? 'new') {
                'feature'  => 'bg-emerald-100 text-emerald-700 border-emerald-200',
                'fix'      => 'bg-rose-100 text-rose-700 border-rose-200',
                'optimise' => 'bg-amber-100 text-amber-700 border-amber-200',
                'new'      => 'bg-slate-100 text-slate-700 border-slate-200',
                default    => 'bg-gray-100 text-gray-700 border-gray-200',
            };
            return $update;
        }, $rawUpdates);
    }
}
