<?php
/**
 * Reporter — Format kết quả scan thành HTML
 */
if (!defined('ABSPATH')) exit;

class Foxblock_Reporter
{
    private static $risk_labels = array(
        'high'   => array('label' => 'Nguy hiểm cao',  'class' => 'foxblock-risk-high'),
        'medium' => array('label' => 'Trung bình',      'class' => 'foxblock-risk-medium'),
        'low'    => array('label' => 'Thấp',            'class' => 'foxblock-risk-low'),
    );

    private static $file_type_colors = array(
        'php'   => array('label' => 'PHP',   'color' => '#8b5cf6', 'bg' => '#f3e8ff'), // Tím
        'phtml' => array('label' => 'PHTML', 'color' => '#10b981', 'bg' => '#d1fae5'), // Xanh lá
        'phar'  => array('label' => 'PHAR',  'color' => '#92400e', 'bg' => '#fef3c7'), // Nâu
        'js'    => array('label' => 'JS',    'color' => '#ea580c', 'bg' => '#ffedd5'), // Cam
        'svg'   => array('label' => 'SVG',   'color' => '#0284c7', 'bg' => '#e0f2fe'), // Xanh dương
        'html'  => array('label' => 'HTML',  'color' => '#6b7280', 'bg' => '#f3f4f6'), // Xám
        'htm'   => array('label' => 'HTM',   'color' => '#6b7280', 'bg' => '#f3f4f6'), // Xám
    );

    /**
     * Lấy file extension từ path
     */
    private static function get_file_extension(string $file_path): string
    {
        return strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
    }

    /**
     * Render file type badge
     */
    private static function render_file_type_badge(string $file_path): string
    {
        $ext = self::get_file_extension($file_path);
        $type_info = self::$file_type_colors[$ext] ?? array(
            'label' => strtoupper($ext),
            'color' => '#6b7280',
            'bg'    => '#f3f4f6'
        );

        return sprintf(
            '<span class="foxblock-file-type-badge" style="background:%s;color:%s;padding:3px 8px;border-radius:4px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.5px;">%s</span>',
            esc_attr($type_info['bg']),
            esc_attr($type_info['color']),
            esc_html($type_info['label'])
        );
    }

    /**
     * Render bảng kết quả cuối cùng
     */
    public static function render(array $all_findings, int $scanned, $comparison = null, $last_baseline = null): string
    {
        $total = count($all_findings);

        ob_start();
        ?>
        <div class="foxblock-malware-summary">
            <div class="foxblock-malware-stat <?php echo $total === 0 ? 'foxblock-malware-stat--clean' : 'foxblock-malware-stat--danger'; ?>">
                <span class="foxblock-malware-stat-icon dashicons dashicons-<?php echo $total === 0 ? 'shield' : 'warning'; ?>"></span>
                <div>
                    <strong><?php echo $total === 0 ? 'Không phát hiện mã độc' : number_format($total) . ' đoạn mã đáng ngờ'; ?></strong>
                    <span>Đã quét <?php echo number_format($scanned); ?> file</span>
                </div>
            </div>
            <div style="margin-top:15px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
                <button type="button" class="button button-primary" id="foxblock-save-scan-btn">
                    <span class="dashicons dashicons-database" style="margin-top:3px;"></span> Lưu kết quả quét
                </button>
                <?php if ($last_baseline): ?>
                    <button type="button" class="button button-secondary" id="foxblock-clear-scan-data-btn">
                        <span class="dashicons dashicons-trash" style="margin-top:3px;"></span> Xóa dữ liệu
                    </button>
                    <span style="color:#646970;font-size:12px;">
                        Lần quét trước: <?php echo esc_html($last_baseline->scan_time); ?>
                    </span>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($comparison && $comparison['has_changes']): ?>
            <div class="foxblock-comparison-section" style="margin-top:20px;">
                <h3 style="margin:0 0 15px 0;font-size:16px;color:#d63638;">
                    <span class="dashicons dashicons-update" style="font-size:18px;"></span>
                    Phát hiện thay đổi so với lần quét trước
                </h3>
                
                <?php if (!empty($comparison['new'])): ?>
                    <div class="foxblock-changes-box foxblock-changes-new">
                        <h4 class="foxblock-comparison-toggle" data-target="comparison-new">
                            <span class="foxblock-toggle-icon">
                                <span class="dashicons dashicons-plus-alt2"></span>
                            </span>
                            <span>Vấn đề mới phát hiện (<?php echo count($comparison['new']); ?>)</span>
                        </h4>
                        <div id="comparison-new" class="foxblock-comparison-details" style="display:none;">
                            <div class="foxblock-table-responsive-2">
                                <table class="foxblock-table">
                                    <thead>
                                        <tr>
                                            <th style="width:50px">Loại</th>
                                            <th style="width:50px">Dòng</th>
                                            <th style="width:180px">Loại nguy hiểm</th>
                                            <th>File</th>
                                            <th>Đoạn mã</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($comparison['new'] as $f): ?>
                                        <tr class="foxblock-new-issue">
                                            <td style="text-align:center;"><?php echo self::render_file_type_badge($f['file']); ?></td>
                                            <td style="text-align:center;"><?php echo intval($f['line']); ?></td>
                                            <td><span class="foxblock-malware-badge"><?php echo esc_html($f['label']); ?></span></td>
                                            <td><code class="foxblock-fim-path"><?php echo esc_html($f['file']); ?></code></td>
                                            <td><code class="foxblock-malware-code"><?php echo esc_html(mb_strimwidth($f['code'], 0, 150, '...')); ?></code></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if (!empty($comparison['removed'])): ?>
                    <div class="foxblock-changes-box foxblock-changes-removed">
                        <h4 class="foxblock-comparison-toggle" data-target="comparison-removed">
                            <span class="foxblock-toggle-icon">
                                <span class="dashicons dashicons-plus-alt2"></span>
                            </span>
                            <span>Vấn đề đã được sửa/xóa (<?php echo count($comparison['removed']); ?>)</span>
                        </h4>
                        <div id="comparison-removed" class="foxblock-comparison-details" style="display:none;">
                            <div class="foxblock-table-responsive-2">
                                <table class="foxblock-table">
                                    <thead>
                                        <tr>
                                            <th style="width:50px">Loại</th>
                                            <th style="width:50px">Dòng</th>
                                            <th style="width:180px">Loại nguy hiểm</th>
                                            <th>File</th>
                                            <th>Đoạn mã</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($comparison['removed'] as $f): ?>
                                        <tr class="foxblock-removed-issue">
                                            <td style="text-align:center;"><?php echo self::render_file_type_badge($f['file']); ?></td>
                                            <td style="text-align:center;"><?php echo intval($f['line']); ?></td>
                                            <td><span class="foxblock-malware-badge"><?php echo esc_html($f['label']); ?></span></td>
                                            <td><code class="foxblock-fim-path"><?php echo esc_html($f['file']); ?></code></td>
                                            <td><code class="foxblock-malware-code"><?php echo esc_html(mb_strimwidth($f['code'], 0, 150, '...')); ?></code></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if ($total === 0): ?>
            <div class="foxblock-fim-clean-msg">
                <span class="dashicons dashicons-shield"></span>
                Tuyệt vời! Không tìm thấy mã độc nào trong <?php echo number_format($scanned); ?> file đã quét.
            </div>
        <?php else: ?>
            <div class="foxblock-malware-warning-note">
                <span class="dashicons dashicons-info"></span>
                Kết quả dựa trên phân tích token + taint analysis. Một số kết quả có thể là <strong>false positive</strong>. Hãy kiểm tra kỹ trước khi xóa.
            </div>

            <!-- Export Box -->
            <div class="foxblock-export-box" style="margin-top:15px;padding:15px;background:#f0f9ff;border:1px solid #0284c7;border-radius:8px;">
                <div style="display:flex;align-items:center;gap:12px;margin-bottom:10px;">
                    <span class="dashicons dashicons-media-text" style="font-size:24px;color:#0284c7;"></span>
                    <div style="flex:1;">
                        <h3 style="margin:0;font-size:14px;color:#1d2327;">Xuất báo cáo cho AI phân tích</h3>
                        <p style="margin:4px 0 0;font-size:12px;color:#646970;">
                            Tải xuống file .txt chứa chi tiết đầy đủ về các vấn đề phát hiện được. 
                            File này được format đặc biệt để AI (ChatGPT, Claude, v.v.) có thể phân tích chính xác và phân biệt mã độc thật với false positive.
                        </p>
                    </div>
                </div>
                <button type="button" class="button button-primary" id="foxblock-export-txt-btn" style="display:flex;align-items:center;gap:8px;">
                    <span class="dashicons dashicons-download" style="margin-top:3px;"></span>
                    <span>Tải xuống báo cáo (.txt)</span>
                </button>
            </div>

            <?php
            // Nhóm theo file
            $by_file = array();
            foreach ($all_findings as $f) {
                $by_file[$f['file']][] = $f;
            }
            ?>

            <div style="margin-top:15px;margin-bottom:10px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;">
                <span style="font-size:13px;color:#646970;font-weight:600;">
                    Tìm thấy <?php echo count($by_file); ?> file có vấn đề:
                </span>
                <button type="button" class="button button-small" onclick="foxblockExpandAll()">
                    <span class="dashicons dashicons-arrow-down-alt2" style="margin-top:3px;"></span> Mở tất cả
                </button>
                <button type="button" class="button button-small" onclick="foxblockCollapseAll()">
                    <span class="dashicons dashicons-arrow-up-alt2" style="margin-top:3px;"></span> Đóng tất cả
                </button>
            </div>

            <div class="foxblock-malware-file-list">
            <?php foreach ($by_file as $file => $findings): ?>
                <?php
                $max_risk  = self::get_max_risk($findings);
                $max_score = max(array_column($findings, 'score'));
                $risk_info = self::$risk_labels[$max_risk] ?? self::$risk_labels['low'];
                $file_id   = 'file-' . md5($file);
                ?>
                <div class="foxblock-malware-file-block" data-file-path="<?php echo esc_attr($file); ?>" data-file-id="<?php echo esc_attr($file_id); ?>">
                    <div class="foxblock-malware-file-header foxblock-malware-toggle" data-target="<?php echo esc_attr($file_id); ?>">
                        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;flex:1;">
                            <span class="foxblock-malware-badge <?php echo esc_attr($risk_info['class']); ?>">
                                <?php echo esc_html($risk_info['label']); ?>
                            </span>
                            <code class="foxblock-fim-path"><?php echo esc_html($file); ?></code>
                            <span class="foxblock-findings-count">(<?php echo count($findings); ?> vấn đề)</span>
                        </div>
                        <div style="display:flex;align-items:center;gap:10px;">
                            <?php echo self::render_file_type_badge($file); ?>
                            <span class="foxblock-malware-score-badge">
                                Điểm: <?php echo $max_score; ?>
                            </span>
                            <button type="button" class="foxblock-toggle-btn" aria-label="Toggle details">
                                <span class="dashicons dashicons-plus-alt2"></span>
                            </button>
                        </div>
                    </div>
                    <div class="foxblock-malware-details" id="<?php echo esc_attr($file_id); ?>" style="display:none;">
                        <div class="foxblock-table-responsive-2 foxblock-malware-inner-scroll">
                        <table class="foxblock-table foxblock-malware-inner-table">
                            <thead>
                                <tr>
                                    <th style="width:55px">Dòng</th>
                                    <th style="width:90px">Mức độ</th>
                                    <th style="width:80px">Điểm</th>
                                    <th>Phát hiện</th>
                                    <th>Đoạn mã</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($findings as $f):
                                    $ri = self::$risk_labels[$f['risk']] ?? self::$risk_labels['low'];
                                ?>
                                <tr class="foxblock-malware-row">
                                    <td style="text-align:center;"><?php echo intval($f['line']); ?></td>
                                    <td><span class="foxblock-malware-badge <?php echo esc_attr($ri['class']); ?>"><?php echo esc_html($ri['label']); ?></span></td>
                                    <td style="text-align:center;font-weight:700;color:<?php echo $f['score'] >= 7 ? '#d63638' : ($f['score'] >= 5 ? '#dba617' : '#646970'); ?>">
                                        <?php echo intval($f['score']); ?>
                                    </td>
                                    <td style="font-size:12px;"><?php echo esc_html($f['label']); ?></td>
                                    <td><code class="foxblock-malware-code"><?php echo esc_html($f['code']); ?></code></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        </div>
                    </div>
                    <div class="foxblock-ai-file-analysis" id="foxblock-ai-<?php echo esc_attr($file_id); ?>" style="display:none;">
                        <div class="foxblock-ai-file-analysis__header">
                            <span class="dashicons dashicons-superhero-alt"></span>
                            <strong>Phân tích AI cho file này</strong>
                        </div>
                        <div class="foxblock-ai-file-analysis__list"></div>
                    </div>
                </div>
            <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <?php
        return ob_get_clean();
    }

    private static function get_max_risk(array $findings): string
    {
        $order = array('high' => 3, 'medium' => 2, 'low' => 1);
        $max   = 'low';
        foreach ($findings as $f) {
            if (($order[$f['risk']] ?? 0) > ($order[$max] ?? 0)) {
                $max = $f['risk'];
            }
        }
        return $max;
    }

    /**
     * Generate detailed text report for AI analysis
     * 
     * @param array $all_findings All findings with file info
     * @param int $scanned Total files scanned
     * @return string Formatted text content
     */
    public static function generate_text_report(array $all_findings, int $scanned): string
    {
        $output = "";
        $output .= "================================================================================\n";
        $output .= "                    FOXBLOCK MALWARE SCAN REPORT\n";
        $output .= "                    Generated: " . date('Y-m-d H:i:s') . "\n";
        $output .= "================================================================================\n\n";
        
        $output .= "SUMMARY:\n";
        $output .= "--------\n";
        $output .= "Total files scanned: " . number_format($scanned) . "\n";
        $output .= "Total issues found: " . count($all_findings) . "\n";
        
        // Count by risk level
        $risk_counts = array('high' => 0, 'medium' => 0, 'low' => 0);
        foreach ($all_findings as $f) {
            $risk_counts[$f['risk']] = ($risk_counts[$f['risk']] ?? 0) + 1;
        }
        $output .= "  - High risk: " . $risk_counts['high'] . "\n";
        $output .= "  - Medium risk: " . $risk_counts['medium'] . "\n";
        $output .= "  - Low risk: " . $risk_counts['low'] . "\n\n";
        
        // Count by file type
        $type_counts = array();
        foreach ($all_findings as $f) {
            $ext = strtoupper(self::get_file_extension($f['file']));
            $type_counts[$ext] = ($type_counts[$ext] ?? 0) + 1;
        }
        $output .= "Issues by file type:\n";
        foreach ($type_counts as $ext => $count) {
            $output .= "  - $ext: $count\n";
        }
        $output .= "\n";
        
        $output .= "================================================================================\n";
        $output .= "                         DETAILED FINDINGS\n";
        $output .= "================================================================================\n\n";
        
        $output .= "INSTRUCTIONS FOR AI ANALYSIS:\n";
        $output .= "-----------------------------\n";
        $output .= "Please analyze each finding below and determine:\n";
        $output .= "1. Is this REAL MALWARE or a FALSE POSITIVE?\n";
        $output .= "2. If real malware, what is its purpose? (backdoor, data theft, spam, etc.)\n";
        $output .= "3. Severity level (Critical/High/Medium/Low)\n";
        $output .= "4. Recommended action (Delete/Quarantine/Review/Ignore)\n\n";
        $output .= "Consider these factors:\n";
        $output .= "- Context: Is this code in a legitimate plugin/theme?\n";
        $output .= "- Purpose: Does the code serve a legitimate function?\n";
        $output .= "- Obfuscation: Is the code intentionally hidden/encoded?\n";
        $output .= "- User input: Does it process untrusted data safely?\n";
        $output .= "- Remote connections: Are external URLs/IPs suspicious?\n\n";
        
        $output .= "================================================================================\n\n";
        
        // Group by file
        $by_file = array();
        foreach ($all_findings as $f) {
            $by_file[$f['file']][] = $f;
        }
        
        $file_num = 1;
        foreach ($by_file as $file => $findings) {
            $max_risk = self::get_max_risk($findings);
            $max_score = max(array_column($findings, 'score'));
            $ext = strtoupper(self::get_file_extension($file));
            
            $output .= "FILE #$file_num\n";
            $output .= str_repeat("=", 80) . "\n";
            $output .= "Path: $file\n";
            $output .= "Type: $ext\n";
            $output .= "Issues found: " . count($findings) . "\n";
            $output .= "Max risk level: " . strtoupper($max_risk) . "\n";
            $output .= "Max score: $max_score/10\n";
            $output .= str_repeat("-", 80) . "\n\n";
            
            $issue_num = 1;
            foreach ($findings as $f) {
                $output .= "  ISSUE #$issue_num:\n";
                $output .= "  " . str_repeat("-", 76) . "\n";
                $output .= "  • Line number: " . $f['line'] . "\n";
                $output .= "  • Risk level: " . strtoupper($f['risk']) . "\n";
                $output .= "  • Score: " . $f['score'] . "/10\n";
                $output .= "  • Detection method: " . $f['method'] . "\n";
                $output .= "  • Issue type: " . $f['label'] . "\n";
                $output .= "  • Code snippet:\n";
                $output .= "    " . str_repeat("-", 72) . "\n";
                
                // Wrap code snippet for better readability
                $code_lines = explode("\n", wordwrap($f['code'], 72, "\n", false));
                foreach ($code_lines as $line) {
                    $output .= "    " . $line . "\n";
                }
                
                $output .= "    " . str_repeat("-", 72) . "\n";
                $output .= "  • AI Analysis:\n";
                $output .= "    [ ] Real malware - Reason: _________________________________\n";
                $output .= "    [ ] False positive - Reason: _______________________________\n";
                $output .= "    Severity: [ ] Critical [ ] High [ ] Medium [ ] Low\n";
                $output .= "    Action: [ ] Delete [ ] Quarantine [ ] Review [ ] Ignore\n";
                $output .= "    Notes: ____________________________________________________\n";
                $output .= "\n";
                
                $issue_num++;
            }
            
            $output .= "\n";
            $file_num++;
        }
        
        $output .= "================================================================================\n";
        $output .= "                           END OF REPORT\n";
        $output .= "================================================================================\n";
        $output .= "\nGenerated by Foxblock Security Plugin\n";
        $output .= "For support: https://foxplugin.com\n";
        
        return $output;
    }
}
