<?php

namespace App\Controller;

use App\Repository\EmailTrackingRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Routing\Attribute\Route;

class EmailTrackingController extends AbstractController
{
    #[Route('/track/{messageId}/logo.jpg', name: 'app_email_track', methods: ['GET'])]
    public function track(
        string $messageId,
        EmailTrackingRepository $repository,
        EntityManagerInterface $em,
        #[Autowire('%kernel.project_dir%')] string $projectDir,
    ): Response {
        $tracking = $repository->findOneBy(['messageId' => $messageId]);

        if (null !== $tracking) {
            $tracking->markAsOpened();
            $em->flush();
        }

        $response = new BinaryFileResponse($projectDir.'/public/logo.jpg');
        $response->headers->set('Content-Type', 'image/jpeg');
        $response->headers->set('Cache-Control', 'no-store');

        return $response;
    }

    #[Route('/email/{messageId}', name: 'app_email_view', methods: ['GET'])]
    public function view(
        string $messageId,
        EmailTrackingRepository $repository,
    ): Response {
        $tracking = $repository->findOneBy(['messageId' => $messageId]);

        if (null === $tracking || null === $tracking->getHtmlBody()) {
            throw $this->createNotFoundException('Email introuvable.');
        }

        $html = $tracking->getHtmlBody();
        $attachments = $tracking->getAttachments();

        if ($attachments) {
            $attachmentHtml = '<table width="600" cellpadding="0" cellspacing="0" style="margin: 16px auto 0; font-family: Arial, Helvetica, sans-serif;">';
            $attachmentHtml .= '<tr><td style="padding: 12px 0 8px; font-size: 12px; font-weight: bold; text-transform: uppercase; color: #666; letter-spacing: 1px;">Pieces jointes</td></tr>';

            foreach ($attachments as $index => $attachment) {
                $name = $attachment['name'];
                $downloadUrl = $this->generateUrl('app_email_attachment', [
                    'messageId' => $messageId,
                    'index' => $index,
                ]);
                $attachmentHtml .= '<tr><td style="padding: 4px 0;">';
                $attachmentHtml .= '<a href="'.$downloadUrl.'" style="display: inline-block; padding: 8px 16px; border: 2px solid #111827; background: #fabf04; color: #111827; font-size: 12px; font-weight: bold; text-transform: uppercase; text-decoration: none; letter-spacing: 0.5px;">';
                $attachmentHtml .= '📎 '.htmlspecialchars($name).'</a>';
                $attachmentHtml .= '</td></tr>';
            }

            $attachmentHtml .= '</table>';
            $html = str_replace('</body>', $attachmentHtml.'</body>', $html);
        }

        return new Response($html);
    }

    #[Route('/email/{messageId}/attachment/{index}', name: 'app_email_attachment', methods: ['GET'])]
    public function attachment(
        string $messageId,
        int $index,
        EmailTrackingRepository $repository,
    ): Response {
        $tracking = $repository->findOneBy(['messageId' => $messageId]);

        if (null === $tracking) {
            throw $this->createNotFoundException('Email introuvable.');
        }

        $attachments = $tracking->getAttachments();

        if (null === $attachments || !isset($attachments[$index])) {
            throw $this->createNotFoundException('Piece jointe introuvable.');
        }

        $attachment = $attachments[$index];
        $path = $attachment['path'];
        $name = $attachment['name'];

        if (!file_exists($path)) {
            throw $this->createNotFoundException('Le fichier n\'est plus disponible.');
        }

        $response = new BinaryFileResponse($path);
        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $name);

        return $response;
    }
}
