<?php

namespace App\Services\Reports;

use App\Support\MailHtml;
use Dompdf\Dompdf;
use Dompdf\Options;

class SlipPrinterPdfService
{
    public function __construct(private SlipPrinterConfigService $configService)
    {
    }

    public function render(array $data, array $lines, array $options = []): array
    {
        $paper = strtolower((string) ($options['paper'] ?? $this->configService->printerConfig()['paper'] ?? 'card'));
        $fontPt = (float) ($options['font_pt'] ?? env('SLIP_FONT_PT', 13.0));
        $lineH = (float) ($options['line_h'] ?? env('SLIP_LINE_H', 2.0));
        $linesCount = (int) ($options['rows'] ?? count($lines));
        if ($linesCount < 1) {
            $linesCount = count($lines);
        }

        $ptPerLine = $fontPt * $lineH;
        $mmPerPt = 25.4 / 72.0;
        $contentMm = $ptPerLine * $linesCount * $mmPerPt;
        $pageMarginsMm = 6.0;
        $fudgeMm = (float) ($options['fudge_mm'] ?? env('SLIP_FUDGE_MM', 12.0));
        $dynHeightMm = $contentMm + $pageMarginsMm + $fudgeMm;

        switch ($paper) {
            case 'cardp':
            case 'card-portrait':
                $wMm = 53.98;
                $hMm = max($dynHeightMm, 40.0);
                break;
            case 'receipt80':
                $wMm = 72.0;
                $hMm = 90.0;
                break;
            case 'receipt58':
                $wMm = 58.0;
                $hMm = 80.0;
                break;
            case 'card':
            default:
                $wMm = 85.60;
                $hMm = max($dynHeightMm, 40.0);
        }

        $hOverride = $options['height_mm'] ?? $options['h'] ?? null;
        if (is_numeric($hOverride)) {
            $hMm = max(30.0, min(200.0, (float) $hOverride));
        }

        if ($hMm < $dynHeightMm) {
            $hMm = $dynHeightMm;
        }

        $html = MailHtml::slipPdfHtml($data, $lines, [
            'w_mm' => $wMm,
            'h_mm' => $hMm,
        ]);

        $optionsObj = new Options();
        $optionsObj->set('isRemoteEnabled', true);
        $optionsObj->set('defaultFont', 'Courier');

        $dompdf = new Dompdf($optionsObj);
        $dompdf->loadHtml($html, 'UTF-8');

        $mmToPt = 72 / 25.4;
        $wPt = $wMm * $mmToPt;
        $hPt = $hMm * $mmToPt;
        $dompdf->setPaper([0, 0, $wPt, $hPt]);
        $dompdf->render();

        $filename = 'LateSlip_' . preg_replace('/[^A-Za-z0-9]+/', '_', (string) ($data['student_name'] ?? 'slip')) . '_' . date('Ymd_His') . '.pdf';

        return [
            'content' => $dompdf->output(),
            'filename' => $filename,
            'width_mm' => $wMm,
            'height_mm' => $hMm,
        ];
    }
}
