<?php
declare(strict_types=1);

use TCPDF;

final class MdPdfGenerator
{
    public static function generate(
        PDO $pdo,
        int $declarationId
    ): string {

        /* -------------------------
           FETCH DATA
           ------------------------- */

        $decl = self::fetchDeclaration($pdo, $declarationId);
        $answers = self::fetchAnswers($pdo, $declarationId);
        $photos = self::fetchPhotos($pdo, $declarationId);
        $signatures = self::fetchSignatures($pdo, $declarationId);

        if ($decl['status'] !== 'reviewed') {
            throw new RuntimeException('PDF allowed only after review');
        }

        /* -------------------------
           PDF SETUP
           ------------------------- */

        $pdf = new TCPDF();
        $pdf->SetCreator('TechStackBase');
        $pdf->SetAuthor('JB26');
        $pdf->SetTitle('Miner Declaration ' . $decl['declaration_number']);
        $pdf->AddPage();

        /* -------------------------
           LOGOS
           ------------------------- */

        $pdf->Image(__DIR__ . '/../../assets/customer_logo.png', 10, 10, 30);
        $pdf->Image(__DIR__ . '/../../assets/rsp_logo.png', 170, 10, 30);

        $pdf->Ln(25);

        /* -------------------------
           BODY
           ------------------------- */

        $pdf->SetFont('helvetica', '', 10);

        foreach ($answers as $a) {
            $pdf->MultiCell(
                0,
                6,
                "{$a['question_key']}: {$a['selected_option']}\n{$a['comment']}",
                0,
                'L'
            );
            $pdf->Ln(1);

            foreach ($photos[$a['question_key']] ?? [] as $photoPath) {
                $pdf->Image(
                    __DIR__ . '/../../storage/' . $photoPath,
                    '',
                    '',
                    60
                );
                $pdf->Ln(3);
            }
        }

        /* -------------------------
           SIGNATURES
           ------------------------- */

        $pdf->AddPage();
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 10, 'Signatures', 0, 1);

        foreach ($signatures as $sig) {
            $identity = $sig['identity_mode'] === 'NFC'
                ? "Card UID: {$sig['card_uid']}"
                : "{$sig['company_number']} - {$sig['first_name']} {$sig['last_name']}";

            $pdf->SetFont('helvetica', '', 10);
            $pdf->Cell(0, 6, "{$sig['role']} | {$identity}", 0, 1);
            $pdf->Image(
                __DIR__ . '/../../storage/' . $sig['signature_path'],
                '',
                '',
                40
            );
            $pdf->Ln(5);
        }

        /* -------------------------
           SAVE FILE
           ------------------------- */

        $dir = __DIR__ . '/../../storage/md/pdf/' . date('Y/m');
        if (!is_dir($dir)) {
            mkdir($dir, 0770, true);
        }

        $filename = 'md_' . $decl['declaration_number'] . '.pdf';
        $fullPath = $dir . '/' . $filename;

        $pdf->Output($fullPath, 'F');

        return 'md/pdf/' . date('Y/m') . '/' . $filename;
    }

    /* -------------------------
       FETCH HELPERS
       ------------------------- */

    private static function fetchDeclaration(PDO $pdo, int $id): array
    {
        return $pdo->query("
            SELECT *
            FROM md_declarations
            WHERE id = {$id}
        ")->fetch(PDO::FETCH_ASSOC);
    }

    private static function fetchAnswers(PDO $pdo, int $id): array
    {
        return $pdo->query("
            SELECT *
            FROM md_answers
            WHERE declaration_id = {$id}
        ")->fetchAll(PDO::FETCH_ASSOC);
    }

    private static function fetchPhotos(PDO $pdo, int $id): array
    {
        $rows = $pdo->query("
            SELECT question_key, photo_path
            FROM md_photos
            WHERE declaration_id = {$id}
        ")->fetchAll(PDO::FETCH_ASSOC);

        $out = [];
        foreach ($rows as $r) {
            $out[$r['question_key']][] = $r['photo_path'];
        }
        return $out;
    }

    private static function fetchSignatures(PDO $pdo, int $id): array
    {
        return $pdo->query("
            SELECT *
            FROM md_signatures
            WHERE declaration_id = {$id}
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
}
