<?php

namespace App\Controller;

use App\Service\RgpdService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/legal', name: 'app_legal_')]
class LegalController extends AbstractController
{
    private const RGPD_ANCHOR = '#exercer-droits';

    #[Route('/mention-legal', name: 'mention_legal')]
    public function mentionLegal(): Response
    {
        return $this->render('legal/mention_legal.html.twig', [
            'breadcrumbs' => [
                ['name' => 'Accueil', 'url' => '/'],
                ['name' => 'Mentions Legales'],
            ],
        ]);
    }

    #[Route('/conditions-general-utilisation', name: 'cgu')]
    public function cgu(): Response
    {
        return $this->render('legal/cgu.html.twig', [
            'breadcrumbs' => [
                ['name' => 'Accueil', 'url' => '/'],
                ['name' => 'CGU'],
            ],
        ]);
    }

    #[Route('/conditions-general-de-vente', name: 'cgv')]
    public function cgv(): Response
    {
        return $this->render('legal/cgv.html.twig', [
            'breadcrumbs' => [
                ['name' => 'Accueil', 'url' => '/'],
                ['name' => 'CGV'],
            ],
        ]);
    }

    #[Route('/cookie', name: 'cookie')]
    public function cookie(): Response
    {
        return $this->render('legal/cookie.html.twig', [
            'breadcrumbs' => [
                ['name' => 'Accueil', 'url' => '/'],
                ['name' => 'Politique de Cookies'],
            ],
        ]);
    }

    #[Route('/hebergement', name: 'hebergement')]
    public function hebergement(): Response
    {
        return $this->render('legal/hebergement.html.twig', [
            'breadcrumbs' => [
                ['name' => 'Accueil', 'url' => '/'],
                ['name' => 'Hebergement'],
            ],
        ]);
    }

    #[Route('/conformite', name: 'conformite')]
    public function conformite(): Response
    {
        return $this->render('legal/conformite.html.twig', [
            'breadcrumbs' => [
                ['name' => 'Accueil', 'url' => '/'],
                ['name' => 'Conformite'],
            ],
        ]);
    }

    #[Route('/tarif', name: 'tarif')]
    public function tarif(): Response
    {
        return $this->render('legal/tarif.html.twig', [
            'breadcrumbs' => [
                ['name' => 'Accueil', 'url' => '/'],
                ['name' => 'Tarifs'],
            ],
        ]);
    }

    #[Route('/rgpd', name: 'rgpd', methods: ['GET'])]
    public function rgpd(Request $request): Response
    {
        return $this->render('legal/rgpd.html.twig', [
            'client_ip' => $request->getClientIp(),
            'breadcrumbs' => [
                ['name' => 'Accueil', 'url' => '/'],
                ['name' => 'Politique RGPD'],
            ],
        ]);
    }

    #[Route('/rgpd/acces', name: 'rgpd_access', methods: ['POST'])]
    public function rgpdAccess(Request $request, RgpdService $rgpd): Response
    {
        return $this->handleRgpdRequest($request, $rgpd, 'access');
    }

    #[Route('/rgpd/suppression', name: 'rgpd_deletion', methods: ['POST'])]
    public function rgpdDeletion(Request $request, RgpdService $rgpd): Response
    {
        return $this->handleRgpdRequest($request, $rgpd, 'deletion');
    }

    private function handleRgpdRequest(Request $request, RgpdService $rgpd, string $type): Response
    {
        $ip = trim($request->request->getString('ip'));
        $email = trim($request->request->getString('email'));

        if ('' === $ip || '' === $email) {
            $this->addFlash('error', 'Veuillez remplir tous les champs.');

            return $this->redirect($this->generateUrl('app_legal_rgpd').self::RGPD_ANCHOR);
        }

        $rgpd->sendVerificationCode($email, $ip, $type);
        $this->addFlash('success', 'Un code de verification a ete envoye a '.$email.'. Veuillez le saisir ci-dessous pour valider votre demande.');

        return $this->redirect($this->generateUrl('app_legal_rgpd_verify', ['type' => $type, 'email' => $email, 'ip' => $ip]));
    }

    #[Route('/rgpd/verify', name: 'rgpd_verify', methods: ['GET'])]
    public function rgpdVerifyForm(Request $request): Response
    {
        $type = $request->query->getString('type');
        $email = $request->query->getString('email');
        $ip = $request->query->getString('ip');

        if ('' === $type || '' === $email || '' === $ip) {
            $this->addFlash('error', 'Parametres manquants.');

            return $this->redirect($this->generateUrl('app_legal_rgpd').self::RGPD_ANCHOR);
        }

        return $this->render('legal/rgpd_verify.html.twig', [
            'type' => $type,
            'email' => $email,
            'ip' => $ip,
        ]);
    }

    #[Route('/rgpd/verify', name: 'rgpd_verify_post', methods: ['POST'])]
    public function rgpdVerifyPost(Request $request, RgpdService $rgpd): Response
    {
        $type = $request->request->getString('type');
        $email = $request->request->getString('email');
        $ip = $request->request->getString('ip');
        $code = trim($request->request->getString('code'));

        if ('' === $type || '' === $email || '' === $ip) {
            $this->addFlash('error', 'Parametres manquants.');

            return $this->redirect($this->generateUrl('app_legal_rgpd').self::RGPD_ANCHOR);
        }

        if (!$rgpd->verifyCode($email, $ip, $type, $code)) {
            $this->addFlash('error', 'Code invalide ou expire. Veuillez reessayer.');

            return $this->render('legal/rgpd_verify.html.twig', [
                'type' => $type,
                'email' => $email,
                'ip' => $ip,
            ]);
        }

        try {
            if ('access' === $type) {
                $result = $rgpd->handleAccessRequest($ip, $email);
                $this->addFlash('success', $result['found']
                    ? 'Votre attestation a ete generee et signee. Elle sera envoyee sur votre boite mail '.$email.'.'
                    : 'Aucune donnee trouvee pour cette adresse IP. Une attestation d\'absence de donnees sera envoyee sur votre boite mail '.$email.'.');
            } else {
                $result = $rgpd->handleDeletionRequest($ip, $email);
                $this->addFlash('success', $result['found']
                    ? 'Vos donnees ont ete supprimees. Une attestation a ete envoyee par email.'
                    : 'Aucune donnee trouvee pour cette adresse IP.');
            }
        } catch (\Throwable) {
            $this->addFlash('error', 'Une erreur est survenue lors du traitement de votre demande. Veuillez reessayer ou nous contacter a client@e-cosplay.fr.');
        }

        return $this->redirect($this->generateUrl('app_legal_rgpd').self::RGPD_ANCHOR);
    }
}
