<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Service;

use OCP\IConfig;
use Psr\Log\LoggerInterface;
use TCPDF;

/**
 * PDF generation service using TCPDF.
 *
 * Renders structured report data (title, headers, rows) into a
 * formatted PDF document with configurable header (Verein name + logo).
 *
 * Part of Issue #46.
 */
class PdfService {

    private const APP_ID = 'mitgliederverwaltung';

    private IConfig $config;
    private LoggerInterface $logger;

    public function __construct(
        IConfig $config,
        LoggerInterface $logger
    ) {
        $this->config = $config;
        $this->logger = $logger;
    }

    /**
     * Generate a PDF from structured report data.
     *
     * @param string $title Report title
     * @param string[] $headers Column headers
     * @param array[] $rows Data rows (array of string arrays)
     * @return string PDF binary content
     */
    public function generatePdf(string $title, array $headers, array $rows): string {
        $vereinName = $this->config->getAppValue(self::APP_ID, 'verein_name', 'Verein');

        $pdf = new TCPDF('L', 'mm', 'A4', true, 'UTF-8', false);

        // ── Document metadata ───────────────────────────────────────
        $pdf->SetCreator('Mitgliederverwaltung');
        $pdf->SetAuthor($vereinName);
        $pdf->SetTitle($title);

        // ── Header configuration ────────────────────────────────────
        $pdf->SetHeaderData('', 0, $vereinName, $title);
        $pdf->setHeaderFont(['dejavusans', '', 10]);
        $pdf->setFooterFont(['dejavusans', '', 8]);

        // ── Margins ─────────────────────────────────────────────────
        $pdf->SetMargins(10, 25, 10);
        $pdf->SetHeaderMargin(10);
        $pdf->SetFooterMargin(15);
        $pdf->SetAutoPageBreak(true, 20);

        // ── Font ────────────────────────────────────────────────────
        $pdf->SetFont('dejavusans', '', 9);

        // ── Add page ────────────────────────────────────────────────
        $pdf->AddPage();

        // ── Build HTML table ────────────────────────────────────────
        $html = $this->buildHtmlTable($headers, $rows);
        $pdf->writeHTML($html, true, false, true, false, '');

        // ── Footer with date and page number ────────────────────────
        // TCPDF handles footer automatically

        return $pdf->Output('', 'S');
    }

    /**
     * Generate a PDF and return it with a filename.
     *
     * @param array{title: string, headers: string[], rows: array[]} $reportData
     * @return array{content: string, filename: string}
     */
    public function generateReport(array $reportData): array {
        $content = $this->generatePdf(
            $reportData['title'],
            $reportData['headers'],
            $reportData['rows']
        );

        $date = (new \DateTime())->format('Y-m-d');
        $safeTitle = preg_replace('/[^a-zA-Z0-9_-]/', '_', $reportData['title']);
        $filename = "{$safeTitle}_{$date}.pdf";

        return [
            'content' => $content,
            'filename' => $filename,
        ];
    }

    /**
     * Build an HTML table string for TCPDF rendering.
     *
     * Uses inline styles for consistent rendering across PDF engines.
     */
    private function buildHtmlTable(array $headers, array $rows): string {
        $html = '<table cellpadding="4" cellspacing="0" border="1" style="border-collapse: collapse;">';

        // Header row
        $html .= '<tr style="background-color: #4472c4; color: #ffffff; font-weight: bold;">';
        foreach ($headers as $header) {
            $html .= '<td>' . htmlspecialchars($header) . '</td>';
        }
        $html .= '</tr>';

        // Data rows with alternating background
        foreach ($rows as $i => $row) {
            $bgColor = ($i % 2 === 0) ? '#f2f2f2' : '#ffffff';
            $html .= '<tr style="background-color: ' . $bgColor . ';">';
            foreach ($row as $cell) {
                $html .= '<td>' . htmlspecialchars((string)$cell) . '</td>';
            }
            $html .= '</tr>';
        }

        $html .= '</table>';

        return $html;
    }
}
