<?php
if (!defined('ABSPATH')) exit;

use Dompdf\Dompdf;
use Dompdf\Options;

class SS_Export {

    /**
     * Export clean CSV (Excel-safe)
     */
    public static function csv($filename, $rows, $report_type) {
        if (empty($rows)) wp_die('No data available to export.');

        // Clean any output buffers before starting CSV
        while (ob_get_level()) ob_end_clean();

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . sanitize_file_name($filename) . '"');
        header('Pragma: no-cache');
        header('Expires: 0');

        $out = fopen('php://output', 'w');

        // Detect data type
        $first = reset($rows);
        $isCrawler = isset($first->bot_name);

        // Headers
        if ($isCrawler) {
            fputcsv($out, ['Bot Name', 'Visited URL', 'IP Address', 'User Agent', 'Detected At']);
            foreach ($rows as $r) {
                fputcsv($out, [
                    $r->bot_name,
                    $r->url,
                    $r->ip_address,
                    $r->user_agent,
                    $r->hit_time
                ]);
            }
        } else {
            fputcsv($out, ['ID', 'URL', 'Status', 'Score', 'Optimized', 'Recommendations', 'Finished At']);
            foreach ($rows as $r) {
                preg_match('/Score:\s*(\d+\/\d+)/', $r->log ?? '', $match);
                $score = $match[1] ?? 'N/A';
                $isOptimized = (stripos($r->log, 'fix applied') !== false) ? 'Yes' : 'No';
                $recs = [];

                if (stripos($r->log, 'add structured data') === false) $recs[] = 'Add structured data';
                if (stripos($r->log, 'add a q&a section') === false) $recs[] = 'Add Q&A section';
                if (stripos($r->log, 'link to glossary terms') === false) $recs[] = 'Link glossary terms';

                $recommendations = !empty($recs) ? implode(', ', $recs) : 'All Good';

                fputcsv($out, [
                    intval($r->id),
                    $r->url,
                    ucfirst($r->status),
                    $score,
                    $isOptimized,
                    $recommendations,
                    $r->finished_at
                ]);
            }
        }

        fclose($out);
        exit;
    }

    /**
     * Export clean PDF (Dompdf)
     */
    public static function pdf($filename, $rows, $report_type, $branding = []) {
        if (empty($rows)) wp_die('No data available to export.');

        require_once SEARCHSHIFTER_PLUGIN_DIR . 'vendor/autoload.php';

        $first = reset($rows);
        $isCrawler = isset($first->bot_name);
        $title = $isCrawler ? 'AI Crawler Monitor Report' : 'AI Visibility Scanner Report';

        $options = new \Dompdf\Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isRemoteEnabled', true);
        $dompdf = new \Dompdf\Dompdf($options);

        // Prevent buffer leaks
        while (ob_get_level()) ob_end_clean();

        ob_start();
        ?>
        <html>
        <head>
            <meta charset="utf-8">
            <style>
                body { font-family: Arial, sans-serif; font-size: 12px; color: #333; margin: 30px; }
                h1 { color: #2271b1; font-size: 20px; text-align: center; margin-bottom: 10px; }
                table { border-collapse: collapse; width: 100%; margin-top: 10px; }
                th, td { border: 1px solid #ddd; padding: 6px 8px; text-align: left; }
                th { background: #f3f6fa; font-weight: bold; }
                tr:nth-child(even) { background: #fafafa; }
                p.meta { text-align:center;font-size:11px;margin:0 0 10px; }
            </style>
        </head>
        <body>
          <?php
// Default branding (used everywhere else)
$company = 'SearchShifter';
$logo    = '';

// Apply white-label ONLY when branding is explicitly passed (Advanced Reporting)
if (!empty($branding) && is_array($branding)) {
    if (!empty($branding['company'])) {
        $company = $branding['company'];
    }
    if (!empty($branding['logo'])) {
        $logo = $branding['logo'];
    }
}
?>

<div style="text-align:center;margin-bottom:12px;">
    <?php if ($logo): ?>
        <img src="<?= esc_url($logo) ?>" style="max-height:50px;margin-bottom:6px;" />
    <?php endif; ?>
    <h1><?= esc_html($company) ?>™ <?= esc_html($title) ?></h1>
</div>

            <p class="meta">Generated on <?= esc_html(date('Y-m-d H:i:s')) ?></p>

            <?php if ($isCrawler): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Bot Name</th>
                            <th>Visited URL</th>
                            <th>IP Address</th>
                            <th>User Agent</th>
                            <th>Detected At</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rows as $r): ?>
                            <tr>
                                <td><?= esc_html($r->bot_name) ?></td>
                                <td><?= esc_html($r->url) ?></td>
                                <td><?= esc_html($r->ip_address) ?></td>
                                <td><?= esc_html($r->user_agent) ?></td>
                                <td><?= esc_html($r->hit_time) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <?php
                $total = count($rows);
                $optimized = 0;
                foreach ($rows as $r) {
                    if (stripos($r->log, 'fix applied') !== false) $optimized++;
                }
                ?>
                <p class="meta">Total Pages Scanned: <?= $total ?> | Optimized: <?= $optimized ?> | Pending: <?= $total - $optimized ?></p>

                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>URL</th>
                            <th>Status</th>
                            <th>Score</th>
                            <th>Optimized</th>
                            <th>Recommendations</th>
                            <th>Finished At</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rows as $r):
                            preg_match('/Score:\s*(\d+\/\d+)/', $r->log ?? '', $match);
                            $score = $match[1] ?? 'N/A';
                            $isOptimized = (stripos($r->log, 'fix applied') !== false) ? 'Yes' : 'No';
                            $recs = [];
                            if (stripos($r->log, 'add structured data') === false) $recs[] = 'Add structured data';
                            if (stripos($r->log, 'add a q&a section') === false) $recs[] = 'Add Q&A section';
                            if (stripos($r->log, 'link to glossary terms') === false) $recs[] = 'Link glossary terms';
                            $recommendations = !empty($recs) ? implode(', ', $recs) : '✅ All Good';
                        ?>
                            <tr>
                                <td><?= intval($r->id) ?></td>
                                <td><?= esc_html($r->url) ?></td>
                                <td><?= esc_html(ucfirst($r->status)) ?></td>
                                <td><?= esc_html($score) ?></td>
                                <td><?= $isOptimized ?></td>
                                <td><?= esc_html($recommendations) ?></td>
                                <td><?= esc_html($r->finished_at) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </body>
        </html>
        <?php
        $html = ob_get_clean();

        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();
        $dompdf->stream($filename, ['Attachment' => true]);
        exit;
    }


    /**
     * Universal export buttons
     */
    public static function auto($page_slug, $rows) {
        $slug = sanitize_title($page_slug);
        $csv_key = "ss_export_csv_{$slug}";
        $pdf_key = "ss_export_pdf_{$slug}";

        echo '<form method="post" style="margin:15px 0;">';
        wp_nonce_field('ss_export_' . $slug);
        echo '<button class="button button-primary" name="' . esc_attr($csv_key) . '">📊 Export CSV</button> ';
        echo '<button class="button" name="' . esc_attr($pdf_key) . '">🧾 Export PDF</button>';
        echo '</form>';

        if (isset($_POST[$csv_key])) self::csv("{$slug}-report.csv", $rows);
        if (isset($_POST[$pdf_key])) self::pdf("{$slug}-report.pdf", $rows);
    }

    /**
 * Preview table for Advanced Reporting (AJAX preview)
 */
public static function preview_table($type, $rows) {

    if (empty($rows)) {
        return '<p>No data found.</p>';
    }

    ob_start();

    echo '<table class="widefat striped">';
    echo '<thead><tr>';

    if ($type === 'crawler') {
        echo '<th>ID</th><th>Bot</th><th>URL</th><th>IP</th><th>Time</th>';
    }
    elseif ($type === 'recommendations') {
        echo '<th>ID</th><th>URL</th><th>Category</th><th>Created</th>';
    }
    else { // scans
        echo '<th>ID</th><th>URL</th><th>Status</th><th>Finished</th>';
    }

    echo '</tr></thead><tbody>';

    foreach ($rows as $r) {
        echo '<tr>';

        if ($type === 'crawler') {
            echo '<td>'.esc_html($r->id).'</td>';
            echo '<td>'.esc_html($r->bot_name).'</td>';
            echo '<td>'.esc_html($r->url).'</td>';
            echo '<td>'.esc_html($r->ip_address).'</td>';
            echo '<td>'.esc_html($r->hit_time).'</td>';
        }
        elseif ($type === 'recommendations') {
            echo '<td>'.esc_html($r->id).'</td>';
            echo '<td>'.esc_html($r->url).'</td>';
            echo '<td>'.esc_html($r->category).'</td>';
            echo '<td>'.esc_html($r->created_at).'</td>';
        }
        else {
            echo '<td>'.esc_html($r->id).'</td>';
            echo '<td>'.esc_html($r->url).'</td>';
            echo '<td>'.esc_html($r->status).'</td>';
            echo '<td>'.esc_html($r->finished_at).'</td>';
        }

        echo '</tr>';
    }

    echo '</tbody></table>';

    return ob_get_clean();
}

}
