<?php

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use setasign\Fpdi\Fpdi;

class WashCertificateGenerator
{
    private string $template;
    private string $department;
    private string $color;
    private string $colorBackground;
    private array $signature;
    private array $logo;
    private Spreadsheet $spreadsheet;
    private array $washPerformedAt;

    public function __construct(string $template, string $department)
    {
        $this->template = $template;
        $this->department = $department;
        $this->color = '1488bc'; // Hex color code (Without the #)
        $this->colorBackground = 'd9d9d9'; // Hex color code (Without the #)
        $this->washPerformedAt = [
            'hvidovre' => ['column' => 'A', 'row' => 21],
            'taastrup' => ['column' => 'B', 'row' => 21],
            'glostrup' => ['column' => 'C', 'row' => 21],
            'køge' => ['column' => 'D', 'row' => 21],
            'roskilde' => ['column' => 'E', 'row' => 21],
            'aarhusC' => ['column' => 'F', 'row' => 21],
        ];
        $this->signature = [
            'path' => 'images/truckwash-underskrift.png',
            'x' => 0,
            'y' => 140,
            'is-centered' => true,
            'width' => 70,
        ];
        $this->logo = [
            'path' => 'images/truckwash-banner-png.png',
            'x' => 0,
            'y' => 20,
            'is-centered' => true,
            'width' => 80,
        ];
    }

    public function generateCertificate(string $outputPath, string $sealOrPlumNumber, string $regNumber, string $regNumberTrailer, string $carriedOutBy): void
    {
        $data = [
            'sealOrPlumNumber' => $sealOrPlumNumber,
            'regNumber' => $regNumber,
            'regNumberTrailer' => $regNumberTrailer,
            'carriedOutBy' => $carriedOutBy,
        ];

        $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
        $reader->setReadDataOnly(false);
        $reader->setIncludeCharts(true);
        $this->spreadsheet = $reader->load($this->template);
        $activeWorksheet = $this->spreadsheet->getActiveSheet();
        $activeWorksheet->setTitle('Wash Certificate');

        $this->setCellValues($activeWorksheet, $data);
        $this->setCellStyles($activeWorksheet);
        $this->setPageSetup($activeWorksheet);

        $this->exportToPdf($outputPath);
        $this->addImagesToPdf($outputPath);

        $this->spreadsheet->disconnectWorksheets();
        unset($this->spreadsheet);
    }

    private function setCellValues($activeWorksheet, array $data): void
    {
        $activeWorksheet->setCellValue('A9', $data['sealOrPlumNumber']);
        $activeWorksheet->setCellValue('B17', $data['regNumber']);
        $activeWorksheet->setCellValue('B18', $data['regNumberTrailer']);
        $activeWorksheet->setCellValue('F18', $data['carriedOutBy']);
        $activeWorksheet->setCellValue($this->washPerformedAt[$this->department]['column'] . $this->washPerformedAt[$this->department]['row'], 'X');
    }

    private function setCellStyles($activeWorksheet): void
    {
        $activeWorksheet->getStyle($this->washPerformedAt[$this->department]['column'] . ($this->washPerformedAt[$this->department]['row'] + 1))->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($this->color);
        $activeWorksheet->getStyle('A9')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($this->colorBackground);
        $activeWorksheet->getStyle('B17')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($this->colorBackground);
        $activeWorksheet->getStyle('B18')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($this->colorBackground);
        $activeWorksheet->getStyle('F18')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($this->colorBackground);

        foreach ( $this->washPerformedAt as $key => $value ) {
            if ($key !== $this->department) {
                $activeWorksheet->getStyle($value['column'] . ($value['row'] + 1))->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($this->colorBackground);
            }
        }

        // Make sure the cells 32A:32F has the font size 11
        $activeWorksheet->getStyle('A32:F32')->getFont()->setSize(11);
        // Make sure the cells 35A:35F has the font size 11
        $activeWorksheet->getStyle('A35:F35')->getFont()->setSize(11);

    }

    private function setPageSetup($activeWorksheet): void
    {
        $activeWorksheet->getPageSetup()->setPaperSize(PageSetup::PAPERSIZE_A4);
        $activeWorksheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_PORTRAIT);
        $activeWorksheet->getPageSetup()->setFitToWidth(1);
        $activeWorksheet->getPageSetup()->setFitToHeight(0);
        $activeWorksheet->getPageMargins()->setTop(0.75);
        $activeWorksheet->getPageMargins()->setRight(0.75);
        $activeWorksheet->getPageMargins()->setLeft(0.75);
        $activeWorksheet->getPageMargins()->setBottom(0.75);
        $activeWorksheet->getPageMargins()->setHeader(0.3);
        $activeWorksheet->getPageMargins()->setFooter(0.3);

    }

    private function exportToPdf(string $outputPath): void
    {
        $writer = IOFactory::createWriter($this->spreadsheet, 'Mpdf');
        $writer->setIncludeCharts(false);
        $writer->setPreCalculateFormulas(true);
        $writer->save($outputPath);
    }

    private function addImagesToPdf(string $outputPath): void
    {
        $logo = $this->logo;
        $signature = $this->signature;
        // Center the logo and signature
        $logo['x'] = $logo['is-centered'] ? (210 - $logo['width']) / 2 : $logo['x'];
        $signature['x'] = $signature['is-centered'] ? (210 - $signature['width']) / 2 : $signature['x'];
        $pdf = new Fpdi();
        $pdf->AddPage();
        $pdf->setSourceFile($outputPath);
        $tplIdx = $pdf->importPage(1);
        $pdf->useTemplate($tplIdx, 0, 0, 210);
        $pdf->Image($logo['path'], $logo['x'], $logo['y'], $logo['width']);
        $pdf->Image($signature['path'], $signature['x'], $signature['y'], $signature['width']);
        $pdf->Output($outputPath, 'F');
    }
}