<?php
/**
 * Gerador de PDF Executivo para Wally Monitor
 * 
 * Usa FPDF (biblioteca leve incluída no WordPress via plugins como WooCommerce)
 * Alternativa: TCPDF (mais completo mas mais pesado)
 * 
 * @package WallyMonitor
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Import namespaced FPDF class
use Wally_Monitor\Lib\Wally_FPDF;

class Wally_PDF_Generator {

    private $pdf;
    private $report;

    public function __construct() {
        /**
         * Load Wally_FPDF library (namespaced FPDF to avoid conflicts)
         * 
         * CONFLICT PREVENTION:
         * - Library is namespaced under Wally_Monitor\Lib
         * - Class is prefixed as Wally_FPDF (not FPDF)
         * - The fpdf.php file has internal class_exists() check
         * - This prevents conflicts with other plugins using standard FPDF
         * 
         * @see includes/lib/fpdf/fpdf.php for full namespacing strategy
         */
        if (!class_exists('Wally_Monitor\\Lib\\Wally_FPDF')) {
            require_once WALLY_MONITOR_PLUGIN_DIR . 'includes/lib/fpdf/fpdf.php';
        }
    }

    /**
     * Converte texto UTF-8 para ISO-8859-1 de forma segura
     */
    private function convert_text($text) {
        if (empty($text) || !is_string($text)) {
            return '';
        }
        
        // Strip SVG tags and HTML tags that may appear in data
        $text = wp_strip_all_tags($text);
        
        // Remove emojis and multibyte symbols not in ISO-8859-1
        $text = preg_replace('/[\x{1F000}-\x{1FFFF}]/u', '', $text);
        $text = preg_replace('/[\x{2600}-\x{27BF}]/u', '', $text);
        $text = preg_replace('/[\x{FE00}-\x{FE0F}]/u', '', $text);  // variation selectors
        $text = preg_replace('/[\x{200D}]/u', '', $text);            // zero-width joiner
        
        // Replace common UTF-8 chars that don't exist in ISO-8859-1
        $text = str_replace(
            ['–', '—', '→', '↑', '↓', '▶', '▼', '▲', '⚡', '✓', '✗', '●', '○', '■', '□', '►', '◄', '★', '☆'],
            ['-', '-', '->', '^', 'v', '>', 'v', '^', '*', 'v', 'x', '*', 'o', '#', '[]', '>', '<', '*', '*'],
            $text
        );
        // Curly quotes and ellipsis (using byte sequences in double quotes)
        $text = str_replace(
            ["\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\xa6",
             "\xe2\x80\x93", "\xe2\x80\x94"],
            ["'", "'", '"', '"', '...', '-', '-'],
            $text
        );
        // Also handle the literal Unicode chars for curly quotes/ellipsis
        $text = str_replace(["\u{2018}", "\u{2019}", "\u{201C}", "\u{201D}", "\u{2026}"], ["'", "'", '"', '"', '...'], $text);
        
        // Convert UTF-8 to ISO-8859-1 with substitution for unmappable chars
        if (function_exists('iconv')) {
            $converted = @iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $text);
            if ($converted !== false) {
                return $converted;
            }
        }
        
        // Fallback: mb_convert_encoding (may drop unmappable chars)
        if (function_exists('mb_convert_encoding')) {
            $converted = @mb_convert_encoding($text, 'ISO-8859-1', 'UTF-8');
            if ($converted !== false) {
                return $converted;
            }
        }
        
        // Last resort: strip all non-ASCII
        return preg_replace('/[^\x20-\x7E]/', '?', $text);
    }

    /**
     * Gera relatório executivo em PDF
     * 
     * @param array $report Dados do relatório
     */
    public function generate_executive_report($report) {
        $this->report = $report;
        
        // Cria PDF usando classe com prefixo Wally
        $this->pdf = new Wally_FPDF('P', 'mm', 'A4');
        $this->pdf->SetAutoPageBreak(true, 20);
        $this->pdf->AddPage();
        
        // Renderiza seções
        $this->render_header();
        $this->render_executive_summary();
        $this->render_score_gauge();
        $this->render_statistics();
        $this->render_timeline_graph();
        $this->render_violations_summary();
        $this->render_detailed_violations();
        $this->render_recommendations();
        $this->render_footer();
        
        // Return PDF as string (caller handles headers and output)
        return $this->pdf->Output('S');
    }

    /**
     * Cabeçalho do relatório
     */
    private function render_header() {
        // Logo/Título
        $this->pdf->SetFont('Arial', 'B', 24);
        $this->pdf->SetTextColor(14, 35, 54); // Equallyze Azul Profundo #0E2336
        $this->pdf->Cell(0, 15, 'WALLY MONITOR', 0, 1, 'C');
        
        $this->pdf->SetFont('Arial', '', 14);
        $this->pdf->SetTextColor(147, 97, 255); // Equallyze Roxo Vibrante #9361FF
        $this->pdf->Cell(0, 8, $this->convert_text( __( 'Relatorio Executivo de Acessibilidade', 'wally-monitor' ) ), 0, 1, 'C');
        
        // Data
        $this->pdf->SetFont('Arial', 'I', 10);
        $this->pdf->Cell(0, 6, date_i18n('d/m/Y H:i'), 0, 1, 'C');
        
        // Linha separadora
        $this->pdf->Ln(5);
        $this->pdf->SetDrawColor(200, 200, 200);
        $this->pdf->Line(20, $this->pdf->GetY(), 190, $this->pdf->GetY());
        $this->pdf->Ln(10);
    }

    /**
     * Resumo executivo
     */
    private function render_executive_summary() {
        $summary = isset($this->report['summary']) ? $this->report['summary'] : array();
        $score = isset($summary['score']) ? (int) $summary['score'] : 0;
        
        // Título
        $this->pdf->SetFont('Arial', 'B', 16);
        $this->pdf->SetTextColor(50, 50, 50);
        $this->pdf->Cell(0, 10, $this->convert_text( __( 'Resumo Executivo', 'wally-monitor' ) ), 0, 1);
        $this->pdf->Ln(3);
        
        // Status geral
        $this->pdf->SetFont('Arial', '', 11);
        $status_text = $score >= 90 ? __( 'EXCELENTE', 'wally-monitor' ) : ($score >= 70 ? __( 'BOM', 'wally-monitor' ) : ($score >= 50 ? __( 'REGULAR', 'wally-monitor' ) : __( 'CRITICO', 'wally-monitor' )));
        $status_color = $score >= 90 ? [22, 84, 63] : ($score >= 70 ? [255, 193, 7] : ($score >= 50 ? [253, 126, 20] : [220, 53, 69]));
        
        $this->pdf->SetTextColor($status_color[0], $status_color[1], $status_color[2]);
        $this->pdf->SetFont('Arial', 'B', 14);
        /* translators: %s: accessibility status (EXCELENTE, BOM, REGULAR, CRITICO) */
        $this->pdf->Cell(0, 8, $this->convert_text( sprintf( __( 'Status: %s', 'wally-monitor' ), $status_text ) ), 0, 1);
        
        $this->pdf->SetTextColor(50, 50, 50);
        $this->pdf->SetFont('Arial', '', 11);
        
        // Métricas principais em box
        $this->render_metrics_box($summary);
        
        $this->pdf->Ln(5);
    }

    /**
     * Box com métricas principais
     */
    private function render_metrics_box($summary) {
        $y_start = $this->pdf->GetY();
        
        // Background
        $this->pdf->SetFillColor(245, 245, 245);
        $this->pdf->Rect(20, $y_start, 170, 40, 'F');
        
        // Grid 2x2
        $col_width = 85;
        $row_height = 20;
        
        // Score
        $this->pdf->SetXY(20, $y_start + 5);
        $this->pdf->SetFont('Arial', 'B', 20);
        $score_val = isset($summary['score']) ? (int) $summary['score'] : 0;
        $score_color = $score_val >= 70 ? [22, 84, 63] : [220, 53, 69];
        $this->pdf->SetTextColor($score_color[0], $score_color[1], $score_color[2]);
        $this->pdf->Cell($col_width, 10, $score_val . '/100', 0, 0, 'C');
        
        $this->pdf->SetXY(20, $y_start + 15);
        $this->pdf->SetFont('Arial', '', 9);
        $this->pdf->SetTextColor(100, 100, 100);
        $this->pdf->Cell($col_width, 5, $this->convert_text( __( 'Score de Acessibilidade', 'wally-monitor' ) ), 0, 0, 'C');
        
        // Total de Problemas
        $this->pdf->SetXY(105, $y_start + 5);
        $this->pdf->SetFont('Arial', 'B', 20);
        $this->pdf->SetTextColor(220, 53, 69);
        $this->pdf->Cell($col_width, 10, (string)(isset($summary['totalProblems']) ? $summary['totalProblems'] : 0), 0, 0, 'C');
        
        $this->pdf->SetXY(105, $y_start + 15);
        $this->pdf->SetFont('Arial', '', 9);
        $this->pdf->SetTextColor(100, 100, 100);
        $this->pdf->Cell($col_width, 5, $this->convert_text( __( 'Total de Problemas', 'wally-monitor' ) ), 0, 0, 'C');
        
        // Regras Violadas
        $this->pdf->SetXY(20, $y_start + 25);
        $this->pdf->SetFont('Arial', 'B', 16);
        $this->pdf->SetTextColor(253, 126, 20);
        $rules_count = isset($summary['rulesViolated']) && is_array($summary['rulesViolated']) ? count($summary['rulesViolated']) : 0;
        $this->pdf->Cell($col_width, 10, (string)$rules_count, 0, 0, 'C');
        
        $this->pdf->SetXY(20, $y_start + 35);
        $this->pdf->SetFont('Arial', '', 9);
        $this->pdf->SetTextColor(100, 100, 100);
        $this->pdf->Cell($col_width, 5, $this->convert_text( __( 'Regras Violadas', 'wally-monitor' ) ), 0, 0, 'C');
        
        // Nível WCAG
        $this->pdf->SetXY(105, $y_start + 25);
        $this->pdf->SetFont('Arial', 'B', 16);
        $this->pdf->SetTextColor(23, 162, 184);
        $conformance = isset($summary['conformanceLevel']) ? $summary['conformanceLevel'] : 'N/A';
        $this->pdf->Cell($col_width, 10, $conformance, 0, 0, 'C');
        
        $this->pdf->SetXY(105, $y_start + 35);
        $this->pdf->SetFont('Arial', '', 9);
        $this->pdf->SetTextColor(100, 100, 100);
        $this->pdf->Cell($col_width, 5, $this->convert_text( __( 'Nivel WCAG', 'wally-monitor' ) ), 0, 0, 'C');
        
        $this->pdf->SetY($y_start + 45);
    }

    /**
     * Indicador visual de score (gauge)
     */
    private function render_score_gauge() {
        $score = isset($this->report['summary']['score']) ? (int) $this->report['summary']['score'] : 0;
        
        $this->pdf->Ln(5);
        $this->pdf->SetFont('Arial', 'B', 14);
        $this->pdf->SetTextColor(50, 50, 50);
        $this->pdf->Cell(0, 10, $this->convert_text( __( 'Indicador de Desempenho', 'wally-monitor' ) ), 0, 1);
        
        // Barra de progresso
        $bar_width = 150;
        $bar_height = 20;
        $x_start = 30;
        $y_start = $this->pdf->GetY();
        
        // Background (cinza)
        $this->pdf->SetFillColor(230, 230, 230);
        $this->pdf->Rect($x_start, $y_start, $bar_width, $bar_height, 'F');
        
        // Progresso (cor baseada no score)
        $fill_width = ($score / 100) * $bar_width;
        $fill_color = $score >= 90 ? [22, 84, 63] : ($score >= 70 ? [255, 193, 7] : ($score >= 50 ? [253, 126, 20] : [220, 53, 69]));
        $this->pdf->SetFillColor($fill_color[0], $fill_color[1], $fill_color[2]);
        $this->pdf->Rect($x_start, $y_start, $fill_width, $bar_height, 'F');
        
        // Borda
        $this->pdf->SetDrawColor(150, 150, 150);
        $this->pdf->Rect($x_start, $y_start, $bar_width, $bar_height);
        
        // Texto do score centralizado
        $this->pdf->SetXY($x_start, $y_start + 3);
        $this->pdf->SetFont('Arial', 'B', 12);
        $this->pdf->SetTextColor(255, 255, 255);
        $this->pdf->Cell($bar_width, $bar_height - 6, $score . '%', 0, 0, 'C');
        
        // Legendas
        $this->pdf->SetY($y_start + $bar_height + 5);
        $this->pdf->SetFont('Arial', '', 8);
        $this->pdf->SetTextColor(100, 100, 100);
        $this->pdf->SetX($x_start);
        $this->pdf->Cell(37.5, 5, $this->convert_text( __( '0-50 Crítico', 'wally-monitor' ) ), 0, 0, 'C');
        $this->pdf->Cell(37.5, 5, $this->convert_text( __( '50-70 Regular', 'wally-monitor' ) ), 0, 0, 'C');
        $this->pdf->Cell(37.5, 5, $this->convert_text( __( '70-90 Bom', 'wally-monitor' ) ), 0, 0, 'C');
        $this->pdf->Cell(37.5, 5, $this->convert_text( __( '90-100 Excelente', 'wally-monitor' ) ), 0, 0, 'C');
        
        $this->pdf->Ln(10);
    }

    /**
     * Estatísticas de conformidade
     */
    private function render_statistics() {
        if (!isset($this->report['summary']['elementsStats'])) {
            return;
        }
        
        $stats = $this->report['summary']['elementsStats'];
        
        $this->pdf->Ln(5);
        $this->pdf->SetFont('Arial', 'B', 14);
        $this->pdf->SetTextColor(50, 50, 50);
        $this->pdf->Cell(0, 10, $this->convert_text( __( 'Estatísticas de Conformidade', 'wally-monitor' ) ), 0, 1);
        
        $this->pdf->SetFont('Arial', '', 10);
        $this->pdf->SetTextColor(70, 70, 70);
        
        $categories = [
            ['label' => $this->convert_text( __( 'Imagens com alt', 'wally-monitor' ) ), 'total' => 'totalImages', 'correct' => 'imagesWithAlt'],
            ['label' => $this->convert_text( __( 'Formulários com label', 'wally-monitor' ) ), 'total' => 'totalFormFields', 'correct' => 'formFieldsWithLabel'],
            ['label' => $this->convert_text( __( 'Links descritivos', 'wally-monitor' ) ), 'total' => 'totalLinks', 'correct' => 'linksWithText'],
            ['label' => $this->convert_text( __( 'Botões com label', 'wally-monitor' ) ), 'total' => 'totalButtons', 'correct' => 'buttonsWithLabel'],
            ['label' => $this->convert_text( __( 'Headings corretos', 'wally-monitor' ) ), 'total' => 'totalHeadings', 'correct' => 'headingsCorrect'],
            ['label' => $this->convert_text( __( 'Tabelas acessíveis', 'wally-monitor' ) ), 'total' => 'totalTables', 'correct' => 'tablesAccessible'],
            ['label' => $this->convert_text( __( 'Vídeos com legendas', 'wally-monitor' ) ), 'total' => 'totalVideos', 'correct' => 'videosWithCaptions']
        ];
        
        foreach ($categories as $cat) {
            $total = isset($stats[$cat['total']]) ? $stats[$cat['total']] : 0;
            $correct = isset($stats[$cat['correct']]) ? $stats[$cat['correct']] : 0;
            
            if ($total > 0) {
                $percentage = round(($correct / $total) * 100);
                
                $this->pdf->SetFont('Arial', '', 10);
                $this->pdf->Cell(60, 6, $cat['label'] . ':', 0, 0);
                
                $this->pdf->SetFont('Arial', 'B', 10);
                $color = $percentage >= 90 ? [22, 84, 63] : ($percentage >= 70 ? [255, 193, 7] : [220, 53, 69]);
                $this->pdf->SetTextColor($color[0], $color[1], $color[2]);
                $this->pdf->Cell(30, 6, $correct . '/' . $total, 0, 0);
                
                $this->pdf->SetTextColor(100, 100, 100);
                $this->pdf->SetFont('Arial', 'I', 9);
                $this->pdf->Cell(20, 6, '(' . $percentage . '%)', 0, 1);
                
                $this->pdf->SetTextColor(70, 70, 70);
            }
        }
        
        $this->pdf->Ln(5);
    }

    /**
     * Gráfico de timeline (simplificado - representação textual)
     */
    private function render_timeline_graph() {
        $history = get_option('wally_monitor_history', []);
        
        if (empty($history)) {
            return;
        }
        
        $this->pdf->AddPage();
        
        $this->pdf->SetFont('Arial', 'B', 14);
        $this->pdf->SetTextColor(50, 50, 50);
        $this->pdf->Cell(0, 10, $this->convert_text( __( 'Evolução Temporal do Score', 'wally-monitor' ) ), 0, 1);
        
        // Últimas 10 análises
        $recent = array_slice($history, -10);
        
        $this->pdf->SetFont('Arial', 'B', 9);
        $this->pdf->SetFillColor(240, 240, 240);
        $this->pdf->Cell(50, 7, $this->convert_text( __( 'Data/Hora', 'wally-monitor' ) ), 1, 0, 'C', true);
        $this->pdf->Cell(30, 7, $this->convert_text( __( 'Score', 'wally-monitor' ) ), 1, 0, 'C', true);
        $this->pdf->Cell(40, 7, $this->convert_text( __( 'Problemas', 'wally-monitor' ) ), 1, 0, 'C', true);
        $this->pdf->Cell(50, 7, $this->convert_text( __( 'Tendência', 'wally-monitor' ) ), 1, 1, 'C', true);
        
        $this->pdf->SetFont('Arial', '', 8);
        $prev_score = null;
        
        foreach ($recent as $item) {
            $date = date_i18n('d/m/Y H:i', strtotime($item['timestamp']));
            $score = $item['score'];
            $problems = $item['total_problems'];
            
            // Tendência
            $trend = '';
            if ($prev_score !== null) {
                if ($score > $prev_score) {
                    /* translators: %d: score improvement points */
                    $trend = $this->convert_text( sprintf( __( '↑ Melhora (+%d)', 'wally-monitor' ), $score - $prev_score ) );
                } elseif ($score < $prev_score) {
                    /* translators: %d: score decline points */
                    $trend = $this->convert_text( sprintf( __( '↓ Piora (-%d)', 'wally-monitor' ), $prev_score - $score ) );
                } else {
                    $trend = $this->convert_text( __( '→ Estável', 'wally-monitor' ) );
                }
            }
            
            $this->pdf->Cell(50, 6, $date, 1, 0, 'C');
            
            // Score colorido
            $score_color = $score >= 70 ? [22, 84, 63] : [220, 53, 69];
            $this->pdf->SetTextColor($score_color[0], $score_color[1], $score_color[2]);
            $this->pdf->Cell(30, 6, $score . '/100', 1, 0, 'C');
            $this->pdf->SetTextColor(70, 70, 70);
            
            $this->pdf->Cell(40, 6, (string)$problems, 1, 0, 'C');
            $this->pdf->Cell(50, 6, $trend, 1, 1, 'C');
            
            $prev_score = $score;
        }
        
        $this->pdf->Ln(5);
    }

    /**
     * Resumo de violações por impacto
     */
    private function render_violations_summary() {
        $summary = isset($this->report['summary']) ? $this->report['summary'] : array();
        
        $this->pdf->SetFont('Arial', 'B', 14);
        $this->pdf->SetTextColor(50, 50, 50);
        $this->pdf->Cell(0, 10, $this->convert_text( __( 'Distribuição por Impacto', 'wally-monitor' ) ), 0, 1);
        
        $impacts = [
            'critical' => ['label' => $this->convert_text( __( 'Crítico', 'wally-monitor' ) ), 'color' => [220, 53, 69]],
            'serious' => ['label' => $this->convert_text( __( 'Sério', 'wally-monitor' ) ), 'color' => [253, 126, 20]],
            'moderate' => ['label' => $this->convert_text( __( 'Moderado', 'wally-monitor' ) ), 'color' => [255, 193, 7]],
            'minor' => ['label' => $this->convert_text( __( 'Leve', 'wally-monitor' ) ), 'color' => [23, 162, 184]]
        ];
        
        $byImpact = isset($summary['byImpact']) ? $summary['byImpact'] : [];
        
        foreach ($impacts as $key => $impact) {
            $count = isset($byImpact[$key]) ? $byImpact[$key] : 0;
            
            $this->pdf->SetFont('Arial', '', 11);
            $this->pdf->SetTextColor(70, 70, 70);
            $this->pdf->Cell(60, 7, $impact['label'] . ':', 0, 0);
            
            $this->pdf->SetFont('Arial', 'B', 11);
            $this->pdf->SetTextColor($impact['color'][0], $impact['color'][1], $impact['color'][2]);
            $this->pdf->Cell(20, 7, (string)$count, 0, 1);
            
            $this->pdf->SetTextColor(70, 70, 70);
        }
        
        $this->pdf->Ln(5);
    }

    /**
     * Lista detalhada de violações (top 10)
     */
    private function render_detailed_violations() {
        $this->pdf->AddPage();
        
        $this->pdf->SetFont('Arial', 'B', 14);
        $this->pdf->SetTextColor(50, 50, 50);
        $this->pdf->Cell(0, 10, $this->convert_text( __( 'Top 10 Violações Detectadas', 'wally-monitor' ) ), 0, 1);
        
        $violations = isset($this->report['violations']) ? array_slice($this->report['violations'], 0, 10) : array();
        
        if (empty($violations)) {
            $this->pdf->SetFont('Arial', '', 11);
            $this->pdf->SetTextColor(100, 100, 100);
            $this->pdf->Cell(0, 10, $this->convert_text( __( 'Nenhuma violação detectada.', 'wally-monitor' ) ), 0, 1);
            return;
        }
        
        foreach ($violations as $i => $violation) {
            $this->pdf->SetFont('Arial', 'B', 11);
            $this->pdf->SetTextColor(220, 53, 69);
            $this->pdf->Cell(10, 6, ($i + 1) . '.', 0, 0);
            
            $this->pdf->SetTextColor(50, 50, 50);
            $help = $this->convert_text(isset($violation['help']) ? $violation['help'] : '');
            $this->pdf->MultiCell(0, 6, $help);
            
            $this->pdf->SetFont('Arial', 'I', 9);
            $this->pdf->SetTextColor(100, 100, 100);
            $this->pdf->SetX(30);
            
            /* translators: %s: impact level (critical, serious, moderate, minor) */
            $impact_label = $this->convert_text( sprintf( __( 'Impacto: %s', 'wally-monitor' ), ucfirst( isset($violation['impact']) ? $violation['impact'] : 'N/A' ) ) );
            $this->pdf->Cell(50, 5, $impact_label, 0, 0);
            
            $nodes_count = isset($violation['nodes']) ? count($violation['nodes']) : (isset($violation['count']) ? $violation['count'] : 0);
            /* translators: %d: number of affected elements */
            $this->pdf->Cell(0, 5, $this->convert_text( sprintf( __( 'Elementos afetados: %d', 'wally-monitor' ), $nodes_count ) ), 0, 1);
            
            $this->pdf->SetFont('Arial', '', 9);
            $this->pdf->SetTextColor(70, 70, 70);
            $this->pdf->SetX(30);
            $raw_desc = isset($violation['description']) ? $violation['description'] : '';
            $desc = $this->convert_text(mb_substr($raw_desc, 0, 120, 'UTF-8'));
            $this->pdf->MultiCell(0, 5, $desc . '...');
            
            $this->pdf->Ln(3);
            
            // Evita overflow de página
            if ($this->pdf->GetY() > 250) {
                $this->pdf->AddPage();
            }
        }
    }

    /**
     * Recomendações
     */
    private function render_recommendations() {
        $score = isset($this->report['summary']['score']) ? (int) $this->report['summary']['score'] : 0;
        
        $this->pdf->AddPage();
        
        $this->pdf->SetFont('Arial', 'B', 14);
        $this->pdf->SetTextColor(50, 50, 50);
        $this->pdf->Cell(0, 10, $this->convert_text( __( 'Recomendações', 'wally-monitor' ) ), 0, 1);
        
        $this->pdf->SetFont('Arial', '', 10);
        $this->pdf->SetTextColor(70, 70, 70);
        
        if ($score < 50) {
            $recommendations = [
                $this->convert_text( __( '1. URGENTE: Corrija todas as violações críticas imediatamente', 'wally-monitor' ) ),
                $this->convert_text( __( '2. Adicione atributos alt em todas as imagens', 'wally-monitor' ) ),
                $this->convert_text( __( '3. Garanta que todos os formulários tenham labels', 'wally-monitor' ) ),
                $this->convert_text( __( '4. Corrija a hierarquia de headings (H1, H2, H3...)', 'wally-monitor' ) ),
                $this->convert_text( __( '5. Consulte um especialista em acessibilidade', 'wally-monitor' ) )
            ];
        } elseif ($score < 70) {
            $recommendations = [
                $this->convert_text( __( '1. Priorize correção de problemas críticos e sérios', 'wally-monitor' ) ),
                $this->convert_text( __( '2. Revise contraste de cores (mínimo 4.5:1)', 'wally-monitor' ) ),
                $this->convert_text( __( '3. Teste navegação por teclado em todo o site', 'wally-monitor' ) ),
                $this->convert_text( __( '4. Adicione ARIA labels onde necessário', 'wally-monitor' ) ),
                $this->convert_text( __( '5. Execute análises periódicas para monitoramento', 'wally-monitor' ) )
            ];
        } elseif ($score < 90) {
            $recommendations = [
                $this->convert_text( __( '1. Parabéns! Seu site está em bom nível de acessibilidade', 'wally-monitor' ) ),
                $this->convert_text( __( '2. Corrija problemas moderados restantes', 'wally-monitor' ) ),
                $this->convert_text( __( '3. Considere certificação WCAG 2.1 AA', 'wally-monitor' ) ),
                $this->convert_text( __( '4. Implemente testes automatizados no CI/CD', 'wally-monitor' ) ),
                $this->convert_text( __( '5. Documente padrões de acessibilidade para a equipe', 'wally-monitor' ) )
            ];
        } else {
            $recommendations = [
                $this->convert_text( __( '1. Excelente! Seu site está altamente acessível', 'wally-monitor' ) ),
                $this->convert_text( __( '2. Mantenha monitoramento contínuo', 'wally-monitor' ) ),
                $this->convert_text( __( '3. Considere certificação WCAG 2.1 AAA', 'wally-monitor' ) ),
                $this->convert_text( __( '4. Compartilhe boas práticas com a comunidade', 'wally-monitor' ) ),
                $this->convert_text( __( '5. Realize testes com usuários reais de leitores de tela', 'wally-monitor' ) )
            ];
        }
        
        foreach ($recommendations as $rec) {
            $this->pdf->MultiCell(0, 6, $rec);
            $this->pdf->Ln(2);
        }
        
        $this->pdf->Ln(10);
        
        // Call to action
        $this->pdf->SetFont('Arial', 'B', 12);
        $this->pdf->SetTextColor(14, 74, 112); // Equallyze Azul Vibrante #0E4A70
        $this->pdf->MultiCell(0, 6, $this->convert_text( __( 'Próximos Passos:', 'wally-monitor' ) ));
        
        $this->pdf->SetFont('Arial', '', 10);
        $this->pdf->SetTextColor(70, 70, 70);
        $this->pdf->MultiCell(0, 6, $this->convert_text( __( 'Acesse o painel do Wally Monitor no WordPress para visualizar detalhes completos, utilizar Quick Fixes e monitorar a evolução ao longo do tempo.', 'wally-monitor' ) ));
    }

    /**
     * Rodapé
     */
    private function render_footer() {
        $this->pdf->SetY(-15);
        $this->pdf->SetFont('Arial', 'I', 8);
        $this->pdf->SetTextColor(150, 150, 150);
        /* translators: 1: date/time, 2: page number */
        $this->pdf->Cell(0, 10, $this->convert_text( sprintf( __( 'Gerado por Wally Monitor | Equallyze Solutions - %1$s - Pagina %2$s', 'wally-monitor' ), date_i18n( 'd/m/Y H:i' ), $this->pdf->PageNo() ) ), 0, 0, 'C');
    }
}
