<?php

namespace App\Service\Pdf;

use App\Entity\EFlex;
use App\Entity\EFlexLine;
use setasign\Fpdi\Fpdi;
use Symfony\Component\HttpKernel\KernelInterface;

if (!\defined('EURO')) {
    \define('EURO', \chr(128)); // @codeCoverageIgnore
}

class EFlexPdf extends Fpdi
{
    public function __construct(
        private readonly KernelInterface $kernel,
        private readonly EFlex $eflex,
    ) {
        parent::__construct();
        $this->SetTitle($this->enc('E-Flex '.$this->eflex->getReference().' - '.$this->eflex->getCustomer()->getFullName()));
        $this->SetAuthor($this->enc('Association E-Cosplay'));
    }

    public function generate(): void
    {
        $this->AliasNbPages();
        $this->AddPage();

        $this->writeHeader();
        $this->writeContextBlock();
        $this->writeEcheancesTable();
        $this->writeConditions();
        $this->writeCreditWarning();
        $this->writeSignatures();
    }

    /** @codeCoverageIgnore */
    public function Header(): void
    {
    }

    /** @codeCoverageIgnore */
    public function Footer(): void
    {
        $this->SetY(-22);
        $this->SetDrawColor(253, 140, 4);
        $this->Line(15, $this->GetY(), 195, $this->GetY());
        $this->Ln(3);
        $this->SetFont('Arial', '', 7);
        $this->SetTextColor(0, 0, 0);
        $this->Cell(190, 3, $this->enc('42 rue de Saint-Quentin - 02800 BEAUTOR - Tel: 07 66 95 70 06 - client@e-cosplay.fr'), 0, 1, 'C');
        $this->Cell(190, 3, $this->enc('Association E-Cosplay - N SIRET 943 121 517 00011 - CODE APE 9329Z - RNA W022006988'), 0, 1, 'C');
        $this->SetFont('Arial', 'I', 7);
        $this->SetTextColor(150, 150, 150);
        $this->Cell(190, 3, $this->enc('Page ').$this->PageNo().' / {nb}', 0, 0, 'C');
    }

    /** @codeCoverageIgnore */
    private function writeHeader(): void
    {
        $logo = $this->kernel->getProjectDir().'/public/logo.jpg';
        if (file_exists($logo)) {
            $this->Image($logo, 10, 8, 45);
        }

        $this->SetFont('Arial', 'B', 16);
        $this->SetXY(60, 10);
        $this->Cell(0, 8, $this->enc('CONTRAT E-FLEX'), 0, 1, 'L');

        $this->SetFont('Arial', '', 9);
        $this->SetXY(60, 18);
        $this->SetTextColor(150, 150, 150);
        $this->Cell(0, 5, $this->enc('Ref. : '.$this->eflex->getReference()), 0, 1, 'L');
        $this->SetTextColor(0, 0, 0);

        $formatter = new \IntlDateFormatter(
            'fr_FR',
            \IntlDateFormatter::FULL,
            \IntlDateFormatter::NONE,
            'Europe/Paris',
            \IntlDateFormatter::GREGORIAN
        );

        $this->SetFont('Arial', '', 10);
        $this->SetXY(60, 24);
        $this->Cell(0, 5, $this->enc('Emis a Beautor, le '.$formatter->format($this->eflex->getCreatedAt())), 0, 1, 'L');

        // Client
        $customer = $this->eflex->getCustomer();
        $y = 35;
        $this->SetFont('Arial', 'B', 11);
        $this->SetXY(120, $y);
        $name = $customer->getRaisonSociale() ?: $customer->getFullName();
        $this->Cell(0, 5, $this->enc($name), 0, 1, 'L');

        if ($address = $customer->getAddress()) {
            $y += 5;
            $this->SetXY(120, $y);
            $this->SetFont('Arial', '', 10);
            $this->Cell(0, 5, $this->enc($address), 0, 1, 'L');
        }

        $y += 5;
        $this->SetXY(120, $y);
        $this->SetFont('Arial', '', 10);
        $cityLine = ($customer->getZipCode() ?? '').' '.($customer->getCity() ?? '');
        $this->Cell(0, 5, $this->enc(trim($cityLine)), 0, 1, 'L');

        if ($customer->getEmail()) {
            $y += 5;
            $this->SetXY(120, $y);
            $this->Cell(0, 5, $this->enc($customer->getEmail()), 0, 1, 'L');
        }

        $this->Ln(10);
    }

    /** @codeCoverageIgnore */
    private function writeContextBlock(): void
    {
        $this->SetY(60);

        $this->SetFillColor(250, 191, 4);
        $this->SetFont('Arial', 'B', 11);
        $this->Cell(0, 8, $this->enc('  E-FLEX - FINANCEMENT DE SERVICES'), 0, 1, 'L', true);
        $this->Ln(5);

        $labelW = 55;

        $this->SetFont('Arial', 'B', 9);
        $this->Cell($labelW, 6, $this->enc('Description :'), 0, 0, 'L');
        $this->SetFont('Arial', '', 9);
        $this->MultiCell(0, 6, $this->enc($this->eflex->getDescription()), 0, 'L');
        $this->Ln(1);

        $this->SetFont('Arial', 'B', 9);
        $this->Cell($labelW, 6, $this->enc('Montant total :'), 0, 0, 'L');
        $this->SetFont('Arial', 'B', 11);
        $this->Cell(0, 6, number_format((float) $this->eflex->getTotalAmount(), 2, ',', ' ').' '.EURO, 0, 1, 'L');

        $this->SetFont('Arial', 'B', 9);
        $this->Cell($labelW, 6, $this->enc('Nombre d\'echeances :'), 0, 0, 'L');
        $this->SetFont('Arial', '', 9);
        $this->Cell(0, 6, (string) $this->eflex->getNbLines().' mois', 0, 1, 'L');

        $this->SetFont('Arial', 'B', 9);
        $this->Cell($labelW, 6, $this->enc('Mensualite :'), 0, 0, 'L');
        $this->SetFont('Arial', 'B', 11);
        $this->SetTextColor(250, 191, 4);
        $this->Cell(0, 6, number_format($this->eflex->getMonthlyAmount(), 2, ',', ' ').' '.EURO.'/mois', 0, 1, 'L');
        $this->SetTextColor(0, 0, 0);

        $this->SetFont('Arial', 'B', 9);
        $this->Cell($labelW, 6, $this->enc('Methode de paiement :'), 0, 0, 'L');
        $this->SetFont('Arial', '', 9);
        $this->Cell(0, 6, $this->enc($this->eflex->getPaymentMethodLabel()), 0, 1, 'L');

        $this->Ln(5);
    }

    /** @codeCoverageIgnore */
    private function writeEcheancesTable(): void
    {
        $this->SetFont('Arial', 'B', 9);
        $this->SetFillColor(35, 35, 35);
        $this->SetTextColor(255, 255, 255);
        $this->Cell(15, 7, $this->enc('N'), 1, 0, 'C', true);
        $this->Cell(60, 7, $this->enc('Date prevue'), 1, 0, 'C', true);
        $this->Cell(40, 7, $this->enc('Montant'), 1, 0, 'C', true);
        $this->Cell(55, 7, $this->enc('Statut'), 1, 1, 'C', true);
        $this->SetTextColor(0, 0, 0);

        $this->SetFont('Arial', '', 9);
        $fill = false;
        $months = [1 => 'Janvier', 'Fevrier', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Decembre'];

        foreach ($this->eflex->getLines() as $line) {
            $this->SetFillColor(245, 245, 240);
            $monthName = $months[(int) $line->getScheduledAt()->format('n')] ?? '';
            $dateLabel = $line->getScheduledAt()->format('d').' '.$monthName.' '.$line->getScheduledAt()->format('Y');

            $this->Cell(15, 6, (string) $line->getPosition(), 'B', 0, 'C', $fill);
            $this->Cell(60, 6, $this->enc($dateLabel), 'B', 0, 'L', $fill);
            $this->Cell(40, 6, number_format((float) $line->getAmount(), 2, ',', ' ').' '.EURO, 'B', 0, 'R', $fill);
            $this->Cell(55, 6, $this->enc('A prelever'), 'B', 1, 'C', $fill);

            $fill = !$fill;
        }

        $this->Ln(5);
    }

    /** @codeCoverageIgnore */
    private function writeConditions(): void
    {
        $this->SetFont('Arial', 'B', 9);
        $this->Cell(0, 6, $this->enc('CONDITIONS'), 0, 1, 'L');
        $this->SetFont('Arial', '', 8);
        $this->SetTextColor(100, 100, 100);

        $conditions = [
            '1. Le financement E-Flex permet d\'etaler le paiement de vos services sur plusieurs mois sans frais supplementaires.',
            '2. Les prelevements seront effectues automatiquement a chaque date prevue selon la methode choisie.',
            '3. En cas d\'echec de prelevement, une relance sera envoyee par email.',
            '4. Apres 2 echecs consecutifs, le contrat E-Flex pourra etre resilie.',
            '5. Les services finances restent actifs pendant toute la duree du financement.',
        ];

        foreach ($conditions as $condition) {
            $this->MultiCell(0, 4, $this->enc($condition), 0, 'L');
            $this->Ln(1);
        }

        $this->SetTextColor(0, 0, 0);
        $this->Ln(3);
    }

    /** @codeCoverageIgnore */
    private function writeCreditWarning(): void
    {
        $this->SetFont('Arial', 'B', 8);
        $this->SetTextColor(234, 88, 12);
        $this->Cell(0, 5, $this->enc('INFORMATION IMPORTANTE'), 0, 1, 'L');
        $this->SetFont('Arial', '', 8);
        $this->SetTextColor(100, 100, 100);
        $this->Cell(0, 4, $this->enc('Un credit vous engage et doit etre rembourse. Verifiez votre capacite de remboursement avant de vous engager.'), 0, 1, 'L');
        $this->SetTextColor(0, 0, 0);
        $this->Ln(5);
    }

    /** @codeCoverageIgnore */
    private function writeSignatures(): void
    {
        if ($this->GetY() + 40 > $this->GetPageHeight() - 25) {
            $this->AddPage();
        }

        $colWidth = 85;

        $this->SetFont('Arial', 'B', 9);
        $this->Cell($colWidth, 5, $this->enc('Pour Association E-Cosplay :'), 0, 0, 'L');
        $this->Cell(10, 5, '', 0, 0);
        $this->Cell($colWidth, 5, $this->enc('Le client :'), 0, 1, 'L');
        $this->Ln(2);

        $this->SetFont('Arial', '', 10);
        $this->Cell($colWidth, 20, '{{Sign;type=signature;role=Company}}', 0, 0, 'L');
        $this->Cell(10, 20, '', 0, 0);
        $this->Cell($colWidth, 20, '{{SignClient;type=signature;role=First Party}}', 0, 1, 'L');

        $this->Ln(5);
        $this->SetFont('Arial', 'I', 8);
        $this->SetTextColor(150, 150, 150);
        $this->Cell(0, 4, $this->enc('Signature electronique via DocuSeal - Valeur juridique (reglement eIDAS, art. 1367 Code civil)'), 0, 1, 'C');
        $this->SetTextColor(0, 0, 0);
    }

    private function enc(string $text): string
    {
        return mb_convert_encoding($text, 'Windows-1252', 'UTF-8');
    }
}
