<?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.');

        if (headers_sent()) {
            wp_die('Cannot export PDF: headers already sent.');
        }

        // 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
                ]);
            }
        }


        exit;
    }

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

        if (headers_sent()) {
            wp_die('Cannot export PDF: headers already sent.');
        }

        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="<?php echo esc_url( $logo ); ?>" style="max-height:50px;margin-bottom:6px;" />
            <?php endif; ?>

            <h1>
                <?php echo esc_html( $company ); ?>™
                <?php echo esc_html( $title ); ?>
            </h1>

            </div>

            <p class="meta">
                <?php
                echo esc_html(
                    gmdate(
                        'Y-m-d H:i:s',
                        current_time( 'timestamp', true )
                    )
                );
                ?>
                </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><?php echo esc_html( $r->bot_name ); ?></td>
                                <td><?php echo esc_html( $r->url ); ?></td>
                                <td><?php echo esc_html( $r->ip_address ); ?></td>
                                <td><?php echo esc_html( $r->user_agent ); ?></td>
                                <td><?php echo 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">
                    <?php
                    printf(
                        /* translators: 1: total pages, 2: optimized pages, 3: pending pages */
                        esc_html__(
                            'Total Pages Scanned: %1$d | Optimized: %2$d | Pending: %3$d',
                            'searchshifter'
                        ),
                        (int) $total,
                        (int) $optimized,
                        (int) ($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><?php echo intval( $r->id ); ?></td>
                                <td><?php echo esc_html( $r->url ); ?></td>
                                <td><?php echo esc_html( ucfirst( $r->status ) ); ?></td>
                                <td><?php echo esc_html( $score ); ?></td>
                                <td><?php echo esc_html( $isOptimized ); ?></td>
                                <td><?php echo esc_html( $recommendations ); ?></td>
                                <td><?php echo 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();

        // 🔥 Generate PDF output manually instead of stream()
        $pdf_output = $dompdf->output();

        // Clean buffers AGAIN before sending headers
        while (ob_get_level() > 0) {
            ob_end_clean();
        }

        if (headers_sent()) {
            wp_die('PDF cannot be generated: headers already sent.');
        }

        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . sanitize_file_name($filename) . '"');
        header('Content-Length: ' . strlen($pdf_output));
        header('Pragma: no-cache');
        header('Expires: 0');
        
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $pdf_output;
        exit;

    }


    /**
     * Universal export buttons
     */
    public static function auto($page_slug) {

        $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>';
    }


    /**
 * 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();
}

public static function maybe_handle_export( $rows ) {

    if ( empty( $_SERVER['REQUEST_METHOD'] ) || $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
        return;
    }

    if ( empty( $_POST['_wpnonce'] ) ) {
        return;
    }

    $nonce = sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) );

    // ✅ CSV export
    /** @phpcs:disable WordPress.Security.NonceVerification.Missing */
    // Loop through POSTed export actions (nonce verified per action)
    foreach ( wp_unslash( $_POST ) as $key => $value ) {

        if ( strpos( $key, 'ss_export_csv_' ) === 0 ) {

            $slug = sanitize_key( str_replace( 'ss_export_csv_', '', $key ) );

            if ( ! wp_verify_nonce( $nonce, 'ss_export_' . $slug ) ) {
                wp_die( esc_html__( 'Security check failed.', 'searchshifter' ) );
            }

            self::csv( "{$slug}-report.csv", $rows );
        }
    }
    /** @phpcs:enable WordPress.Security.NonceVerification.Missing */


    // ✅ PDF export
    foreach ( $_POST as $key => $value ) {
        if ( strpos( $key, 'ss_export_pdf_' ) === 0 ) {
            $slug = str_replace( 'ss_export_pdf_', '', $key );

            if ( ! wp_verify_nonce( $nonce, 'ss_export_' . $slug ) ) {
                wp_die( esc_html__( 'Security check failed.', 'searchshifter' ) );
            }

            self::pdf( "{$slug}-report.pdf", $rows );
        }
    }
}




}
