<?php
/**
 * Speed Analyzer – PDF Report Content
 * report.php - version: v0.046
 */

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

/**
 * Render a status message based on a numeric metric.
 *
 * @param int|null $metric     Numeric value in ms, or null on error.
 * @param array    $thresholds Array with 'green' and 'yellow' keys (ms cut-offs).
 * @param array    $msgs       Array with keys 'green','yellow','red','fallback'.
 * @return string              HTML <p>…</p> block.
 */
function wpsa_pdf_render_status( $metric, $thresholds, $msgs ) {
    if ( is_null( $metric ) ) {
        return '<p style="font-size:1.1em;font-style:italic;color:#c33;"><strong>'
             . esc_html( $msgs['fallback'] )
             . '</strong></p>';
    }
    if ( $metric <= $thresholds['green'] ) {
        return '<p style="font-size:1.1em;color:#388e3c;"><strong>'
             . esc_html( $msgs['green'] )
             . '</strong></p>';
    }
    if ( $metric <= $thresholds['yellow'] ) {
        return '<p style="font-size:1.1em;color:#f9a825;"><strong>'
             . esc_html( $msgs['yellow'] )
             . '</strong></p>';
    }
    return '<p style="font-size:1.1em;color:#d32f2f;"><strong>'
         . esc_html( $msgs['red'] )
         . '</strong></p>';
}

/* ===== 1.16.3: read one test (latest or specific #) from the results log ===== */
function wpsa_pdf_pick_test_from_log( $results_log, $test_no = 0 ) {
    if ( ! $results_log || ! file_exists( $results_log ) ) return null;

    $lines = file( $results_log, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
    if ( ! $lines ) return null;

    // If test_no given, find that header; otherwise take the last header line.
    $header_idx = -1;
    if ( $test_no > 0 ) {
        $re = '/^\s*Test\s+#' . preg_quote( (string) $test_no, '/' ) . '\b/i';
        foreach ( $lines as $i => $ln ) {
            if ( preg_match( $re, $ln ) ) { $header_idx = $i; break; }
        }
        if ( $header_idx === -1 ) return null;
    } else {
        for ( $i = count( $lines ) - 1; $i >= 0; $i-- ) {
            if ( preg_match( '/^\s*Test\s+#\d+\b/i', $lines[$i] ) ) { $header_idx = $i; break; }
        }
        if ( $header_idx === -1 ) return null;
    }

    // Parse header line like:
    // "Test #12 | URL: ... | Region: X | Cache: HIT | ... TTFB: 234 ms"
    $hdr = $lines[ $header_idx ];
    if ( ! preg_match(
        '/^\s*Test\s+#(?P<num>\d+).+?\|\s*URL:\s*(?P<url>[^\|]+)\|\s*Region:\s*(?P<region>[^\|]+)\|\s*Cache:\s*(?P<cache>[^\|]+)\|.*?\bTTFB:\s*(?P<ttfb>\d+)\s*ms/i',
        $hdr, $m
    ) ) return null;

    return array(
        'num'    => (int) $m['num'],
        'url'    => trim( $m['url'] ),
        'region' => sanitize_text_field( $m['region'] ),
        'cache'  => sanitize_text_field( $m['cache'] ),
        'ttfb'   => (int) $m['ttfb'],
    );
}


function wpsa_pdf_report_content( $tested_url, $debug_log, $results_log, $test_no = 0 ) {
    // 5A) Pull effective Customize-PDF config (server-side)
    //     header_text / remove_cta / custom_summary_enabled / custom_summary_text
    $cfg = function_exists('wpsa_get_pdf_effective_config')
        ? wpsa_get_pdf_effective_config()
        : [
            'header_text'            => ( defined('SAWP_VERSION') ? 'Generated by Speed Analyzer ' . SAWP_VERSION : 'Generated by Speed Analyzer' ),
            'remove_cta'             => false,
            'custom_summary_enabled' => false,
            'custom_summary_text'    => '',
        ];

    // Read the *main* results log for loaded tests (ttfb-results-log.txt)
    $upload_dir       = wp_upload_dir();
    $results_log_main = trailingslashit( $upload_dir['basedir'] ) . 'speed-analyzer/ttfb-results-log.txt';

    // Force fresh libxml + DOM state every run
    libxml_clear_errors();
    libxml_use_internal_errors( true );


    // — HEADER —
    $logo_url = plugin_dir_url( __FILE__ ) . 'SAWP-logo.svg';
    $ver      = defined( 'WPSA_VERSION' ) ? WPSA_VERSION : 'unknown';
    ?>
    <div id="pdf-header" style="position:fixed; top:10px; left:20px; right:20px;
        display:flex; align-items:center; padding:0 10px; background:#fff;
        box-sizing:border-box; /* border-bottom removed for PDF to avoid bleed */ 
        z-index:1000; max-height:50px;">
      <img src="<?php echo esc_url( $logo_url ); ?>" alt="Logo" style="height:40px; margin-right:10px;">
      <div style="font-size:150%; line-height:1.2; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
       <!-- Use dynamic header text from Customize PDF (no engine/version tag) -->
        <span id="pdf-header-text"><?php echo esc_html( $cfg['header_text'] ); ?></span>
      </div>
    </div>

    <!-- BODY -->
    <div id="pdf-body" style="margin:80px 20px 80px; page-break-after:auto;">

      <?php
        // 5B) Provide a JSON mirror of the config in the DOM for report-scripts.js
        //     (If your JS already uses wp_localize_script data, this is a no-op fallback.)
        $json_cfg = array(
            'headerText'    => (string) $cfg['header_text'],
            'removeCta'     => (bool) $cfg['remove_cta'],
            'customSummary' => array(
                'enabled' => (bool) $cfg['custom_summary_enabled'],
                'text'    => (string) $cfg['custom_summary_text'],
            ),
        );
      ?>
      <script type="application/json" id="wpsa-pdf-config-json"><?php
        echo wp_kses_post( wp_json_encode( $json_cfg ) );
      ?></script>

      <?php
        // ── CAPTURE MODULE 1 HTML FOR LATER ──
        ob_start();
        wpsa_module1_ttfb( $tested_url, $debug_log, $results_log );
        $mod1_html = ob_get_clean();
      ?>

      <!-- Title -->
      <h1 style="text-align:center; margin-bottom:8px; padding-top:24px;">Speed analysis of the website</h1>

      <!-- Tested URL -->
      <p style="text-align:center; color:#333; margin:0 0 12px;">
        Tested URL: <a href="<?php echo esc_url( $tested_url ); ?>">
          <?php echo esc_html( $tested_url ); ?>
        </a>
      </p>

           <!-- Introduction -->
      <h2 style="text-align:center; margin:30px 0 8px;">Introduction</h2>
      <?php
        // Pick the requested test (#N) from the main results log; fallback to latest if not found.
        $picked = wpsa_pdf_pick_test_from_log( $results_log_main, (int) $test_no );
        $loc    = $picked ? $picked['region'] : '';
        $ttfb   = $picked ? (int) $picked['ttfb'] : null;

        
      ?>
      <p style="font-size:1.1em; line-height:1.4em; color:#333; margin:0 20px 44px;">
        This report outputs Time-to-First-Byte (TTFB) from a nearby edge node, some of the PSI speed-related core metrics, plus other vital speed-related information to give you a clear picture of site performance.<br>
        Speed Analyzer API automatically chose the closest server → <em><b><?php echo esc_html( $loc ); ?></b></em>.
      </p>

      <!-- Module 1 -->
      <div id="pdf-module-1" style="page-break-inside:avoid; margin:40px auto 0; max-width:700px; box-sizing:border-box;">
        <h2 style="margin:0 0 12px; font-size:16px; text-align:left;">1. Server performance test</h2>
        <?php
       $doc = new DOMDocument();
    $doc->loadHTML( mb_convert_encoding( $mod1_html, 'HTML-ENTITIES', 'UTF-8' ) );
    libxml_clear_errors();
    
    $table_html = '';
    $note_html  = '';
    $bg_row     = '#dddddd'; // neutral fallback
    
    // Find the Module-1 table
    $tbl_node = null;
    foreach ( $doc->getElementsByTagName( 'table' ) as $tbl ) {
        if ( $tbl->getAttribute( 'class' ) === 'widefat wpsa-module1-table' ) {
            $tbl_node = $tbl;
            break;
        }
    }
    
    if ( $tbl_node ) {
        // --- 1) Replace Region / Cache / TTFB texts
        $tbody = $tbl_node->getElementsByTagName('tbody')->item(0);
        if ( $tbody ) {
            $row = $tbody->getElementsByTagName('tr')->item(0);
            if ( $row ) {
                $cells = $row->getElementsByTagName('td');
                if ( $cells->length >= 3 ) {
                    if ( $picked ) {
                        // Use the loaded test values
                        $cells->item(0)->nodeValue = $picked['region'];
                        $cells->item(1)->nodeValue = $picked['cache'];
                        $cells->item(2)->nodeValue = $picked['ttfb'] . ' ms';
                        $ttfb = (int) $picked['ttfb'];
                    } else {
                        // Fallback: parse TTFB from existing cell
                        $raw = trim( $cells->item(2)->textContent );
                        if ( preg_match( '/(\d+)/', $raw, $mm ) ) {
                            $ttfb = (int) $mm[1];
                        } else {
                            $ttfb = null;
                        }
                    }
                }
    
                // --- 2) Re-color the table row to match the (loaded) TTFB
                $bg_row = is_null($ttfb)
                    ? '#dddddd'
                    : ( $ttfb <= 300 ? '#c6f7c3' : ( $ttfb <= 700 ? '#fff4c3' : '#ffdddd' ) );
    
                // Remove any prior inline background and set ours
                $style = (string) $row->getAttribute('style');
                $style = preg_replace('/background\s*:[^;]+;?/i', '', $style);
                $row->setAttribute('style', trim("background: {$bg_row}; {$style}"));
            }
        }
    
        // Save updated table HTML (now with corrected row color)
        $table_html = $doc->saveHTML( $tbl_node );
    }
    
    // --- 3) Update the confirmation box under the table (bg + text)
    $xpath      = new DOMXPath( $doc );
    $note_nodes = $xpath->query( '//table[@class="widefat wpsa-module1-table"]/following-sibling::div[1]' );
    if ( $note_nodes->length ) {
    $note = $note_nodes->item(0);

    // Sync background with the row
    $nstyle = (string) $note->getAttribute('style');
    $nstyle = preg_replace('/background\s*:[^;]+;?/i', '', $nstyle);
    $note->setAttribute('style', trim("background: {$bg_row}; {$nstyle}"));

    // Rewrite the first paragraph text to match the loaded TTFB
    $p0 = $note->getElementsByTagName('p')->item(0);
    if ( $p0 ) {
        if ( is_null($ttfb) ) {
            $p0->nodeValue = 'The test did not finish properly. Please, run it again.';
        } else {
            $label = ( $ttfb <= 300 ) ? 'Fast ✅' : ( $ttfb <= 700 ? 'OK ⚠️' : 'Slow 🔴' );
            $p0->nodeValue = "This test confirms that your server TTFB is {$label}.";
        }
    }

    $note_html = $doc->saveHTML( $note );
}


        $thresholds = [ 'green' => 300, 'yellow' => 700 ];
        $msgs = [
          'green'    => sprintf('Your server is blazing fast (%d ms)! No action needed.', $ttfb ),
          'yellow'   => sprintf('Your server is OK but could be faster (%d ms), consider small optimizations.', $ttfb ),
          'red'      => sprintf('Your server response is slow (%d ms), investigate hosting or caching.', $ttfb ),
          'fallback' => 'The test did not finish properly. Please, run it again.',
        ];
        ?>
        <div style="width:100%; margin:0 auto;"><?php echo wp_kses_post( $table_html ); ?></div>
        <div style="margin-top:0px;"><?php echo wp_kses_post( $note_html ); ?></div>
        <p style="text-align:center; font-size:0.85em; color:#666; margin:8px 0 0;">Figure 1 – Server performance test</p>
        <div style="margin-top:25px;">
          <?php
            // wrap the rendered status in kses too
            echo wp_kses_post( wpsa_pdf_render_status( $ttfb, $thresholds, $msgs ) );
          ?>
        </div>
        <p style="font-size:1.1em; color:#333; margin-top:8px;">*Ensure that your website uses a fast CDN for the best possible results, especially for those visitors further away from your web host server.</p>
        <div style="margin-top:40px; font-size:0.95em; font-style:italic; line-height:1.4em; color:#333;">
          <ul style="padding-left:1.2em; margin:0;">
            <li><strong>What is TTFB?</strong> Time to First Byte (TTFB) is the duration from when a client makes an HTTP request until it receives the first byte of the response.</li>
            <li><strong>What influences TTFB?</strong> DNS lookup, TCP connection setup, network latency, server processing, and caching layers all affect TTFB.</li>
            <li><strong>How to improve TTFB?</strong> Use <a href="https://wpservice.pro/tools-of-the-trade/wordpress-hosting-services-compared/" target="_blank" rel="noopener">fast hosting</a>, a CDN, server-side caching, optimize backend/database performance, and minimize redirects.</li>
          </ul>
        </div>
      </div><!-- #pdf-module-1 -->
    </div><!-- #pdf-body -->

    <!-- FOOTER -->
    <div id="pdf-footer" style="position:fixed; bottom:20px; left:20px; right:20px;
        display:flex; justify-content:space-between; padding:0 10px; background:#fff;
        box-sizing:border-box; border-top:1px solid #ccc; font-size:0.85em; color:#666; max-height:20px;">
      <span id="pdf-footer-date">Loading date...</span>
      <span id="pdf-footer-page">Page 1</span>
    </div>

    <!-- Page 2 placeholder and content -->
    <div style="page-break-before: always;"></div>
    <div style="margin-top:30px; padding-bottom:30px; max-width:700px; margin-left:auto; margin-right:auto;">
      <h2 style="margin:0 0 12px; font-size:16px; text-align:left;">2. Page asset summary</h2>
      <h3 style="margin:20px 0 8px; font-size:14px;">2.1. Mobile results</h3>
      <div id="pdf-module2-mobile-placeholder"></div>
      <h3 style="margin:20px 0 8px; font-size:14px;">2.2. Desktop results</h3>
      <div id="pdf-module2-desktop-placeholder"></div>
      <div style="margin:30px 0; font-size:0.95em; font-style:italic; line-height:1.4em; color:#333;">
        <p>The Page Asset Summary measures the total number of HTTP requests your page makes (scripts, styles, images, etc.) and the combined gzip-compressed size of all assets in KB. Lower request counts and smaller payloads load faster and use less bandwidth.</p>
        <p>To improve these values, combine or defer non-critical assets, minify and compress files, lazy-load offscreen images, and remove unused resources whenever possible.</p>
      </div>
    </div>

    <!-- Page 3 – Performance & Diagnostics (Module 5) -->
    <div id="pdf-module-5" style="page-break-before:always; margin-top:30px; max-width:700px; margin:0 auto;">
      <?php wpsa_module5_performance_diagnostics( $tested_url, $results_log ); ?>
    </div>
<?php
}