<?php
/**
 * PDF Report Generator
 * Generates PDF reports using FPDF-compatible output
 */

class PDFGenerator
{
    private string $orientation;
    private string $unit;
    private array $pageSize;
    private float $pageWidth;
    private float $pageHeight;
    private array $pages = [];
    private int $currentPage = 0;
    private float $currentY = 0;
    private float $leftMargin = 10;
    private float $rightMargin = 10;
    private float $topMargin = 10;
    private string $title = '';
    private string $subtitle = '';
    private string $footerText = '';
    private ?string $logoPath = null;

    public function __construct(string $orientation = 'P', string $unit = 'mm', string $size = 'A4')
    {
        $this->orientation = strtoupper($orientation);
        $this->unit = $unit;

        $sizes = [
            'A4' => [210, 297],
            'A3' => [297, 420],
            'Letter' => [215.9, 279.4],
        ];

        $this->pageSize = $sizes[$size] ?? $sizes['A4'];

        if ($this->orientation === 'L') {
            $this->pageWidth = $this->pageSize[1];
            $this->pageHeight = $this->pageSize[0];
        } else {
            $this->pageWidth = $this->pageSize[0];
            $this->pageHeight = $this->pageSize[1];
        }

        $this->addPage();
    }

    public function setTitle(string $title): void
    {
        $this->title = $title;
    }

    public function setSubtitle(string $subtitle): void
    {
        $this->subtitle = $subtitle;
    }

    public function setFooterText(string $text): void
    {
        $this->footerText = $text;
    }

    public function setLogo(string $logoPath): void
    {
        $this->logoPath = $logoPath;
    }

    private function addPage(): void
    {
        $this->currentPage++;
        $this->currentY = $this->topMargin + 20;
        $this->pages[$this->currentPage] = '';
    }

    private function checkPageBreak(float $height): void
    {
        if ($this->currentY + $height > $this->pageHeight - 15) {
            $this->addPage();
        }
    }

    public function output(string $filename = 'report'): void
    {
        $content = $this->generateHTML();
        header('Content-Type: text/html; charset=utf-8');
        header('Content-Disposition: inline; filename="' . $filename . '.html"');
        echo $content;
        exit;
    }

    public function download(string $filename = 'report'): void
    {
        $content = $this->generateHTML();
        header('Content-Type: text/html; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '.html"');
        echo $content;
        exit;
    }

    public function getHTML(): string
    {
        return $this->generateHTML();
    }

    private function generateHTML(): string
    {
        $html = '<!DOCTYPE html><html><head><meta charset="utf-8">';
        $html .= '<title>' . htmlspecialchars($this->title) . '</title>';
        $html .= '<style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: Arial, sans-serif; font-size: 10pt; color: #333; }
            .page { width: 210mm; min-height: 297mm; padding: 15mm; margin: 0 auto; background: #fff; }
            .page-break { page-break-after: always; }
            .report-header { text-align: center; margin-bottom: 20px; border-bottom: 2px solid #1a73e8; padding-bottom: 15px; }
            .report-header h1 { font-size: 18pt; color: #1a73e8; margin-bottom: 5px; }
            .report-header h2 { font-size: 12pt; color: #666; font-weight: normal; }
            .report-header .date { font-size: 9pt; color: #999; margin-top: 5px; }
            table { width: 100%; border-collapse: collapse; margin: 15px 0; }
            th { background: #1a73e8; color: #fff; padding: 8px 6px; text-align: left; font-size: 9pt; }
            td { padding: 7px 6px; border-bottom: 1px solid #e0e0e0; font-size: 9pt; }
            tr:nth-child(even) { background: #f8f9fa; }
            .summary-box { background: #e8f0fe; border: 1px solid #1a73e8; border-radius: 6px; padding: 15px; margin: 15px 0; }
            .summary-box h3 { color: #1a73e8; margin-bottom: 10px; font-size: 11pt; }
            .summary-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }
            .summary-item { text-align: center; }
            .summary-item .value { font-size: 16pt; font-weight: bold; color: #1a73e8; }
            .summary-item .label { font-size: 8pt; color: #666; }
            .footer { text-align: center; font-size: 8pt; color: #999; margin-top: 30px; border-top: 1px solid #e0e0e0; padding-top: 10px; }
            .badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 8pt; font-weight: bold; }
            .badge-approved { background: #d4edda; color: #155724; }
            .badge-rejected { background: #f8d7da; color: #721c24; }
            .badge-pending { background: #fff3cd; color: #856404; }
            .badge-counted { background: #cce5ff; color: #004085; }
            @media print { .page { margin: 0; box-shadow: none; } }
        </style></head><body>';

        foreach ($this->pages as $i => $content) {
            $isLast = ($i === count($this->pages));
            $html .= '<div class="page' . ($isLast ? '' : ' page-break') . '">';
            $html .= '<div class="report-header">';
            if (!empty($this->logoPath) && file_exists(APP_ROOT . '/' . $this->logoPath)) {
                $html .= '<img src="' . APP_URL . '/' . $this->logoPath . '" alt="Logo" style="max-width:120px; max-height:50px; margin-bottom:10px;">';
            }
            $html .= '<h1>' . htmlspecialchars($this->title) . '</h1>';
            if ($this->subtitle) {
                $html .= '<h2>' . htmlspecialchars($this->subtitle) . '</h2>';
            }
            $html .= '<div class="date">Generated: ' . date('F j, Y \a\t g:i A') . '</div>';
            $html .= '</div>';
            $html .= $content;

            if ($this->footerText) {
                $html .= '<div class="footer">' . htmlspecialchars($this->footerText) . '</div>';
            }
            $html .= '</div>';
        }

        $html .= '</body></html>';
        return $html;
    }

    public function addSummaryBox(array $items): void
    {
        $html = '<div class="summary-box"><h3>Summary</h3><div class="summary-grid">';
        foreach ($items as $item) {
            $html .= '<div class="summary-item">';
            $html .= '<div class="value">' . htmlspecialchars($item['value']) . '</div>';
            $html .= '<div class="label">' . htmlspecialchars($item['label']) . '</div>';
            $html .= '</div>';
        }
        $html .= '</div></div>';
        $this->pages[$this->currentPage] .= $html;
        $this->currentY += 30;
    }

    public function addTable(array $headers, array $rows, array $columnWidths = []): void
    {
        $this->checkPageBreak(50);
        $html = '<table><thead><tr>';
        foreach ($headers as $header) {
            $html .= '<th>' . htmlspecialchars($header) . '</th>';
        }
        $html .= '</tr></thead><tbody>';
        foreach ($rows as $row) {
            $html .= '<tr>';
            foreach ($row as $cell) {
                $html .= '<td>' . $cell . '</td>';
            }
            $html .= '</tr>';
        }
        $html .= '</tbody></table>';
        $this->pages[$this->currentPage] .= $html;
        $this->currentY += 10 + count($rows) * 7;
    }

    public function addText(string $text, string $align = 'left', string $fontSize = '10pt'): void
    {
        $this->checkPageBreak(10);
        $style = "text-align: $align; font-size: $fontSize; margin: 5px 0;";
        $this->pages[$this->currentPage] .= "<p style=\"$style\">" . htmlspecialchars($text) . "</p>";
        $this->currentY += 7;
    }

    public function addHeading(string $text, int $level = 2): void
    {
        $this->checkPageBreak(15);
        $size = ['1' => '16pt', '2' => '13pt', '3' => '11pt'][$level] ?? '11pt';
        $this->pages[$this->currentPage] .= "<h$level style=\"font-size: $size; color: #1a73e8; margin: 15px 0 10px;\">" . htmlspecialchars($text) . "</h$level>";
        $this->currentY += 12;
    }

    public function addLineBreak(): void
    {
        $this->pages[$this->currentPage] .= '<br>';
        $this->currentY += 5;
    }
}
