<?php
/**
 * SEO Analyzer view: list of all public posts with their score + warnings.
 *
 * @package Brainwerk SEO Suite
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

global $wpdb;
$meta_t = Seoforge_Utils::table( 'meta' );
$blog   = Seoforge_Utils::current_blog_id();

$post_types = array_values( get_post_types( array( 'public' => true, 'show_ui' => true ) ) );
$placeholders = implode( ',', array_fill( 0, count( $post_types ), '%s' ) );
$args = array_merge( array( 'publish' ), $post_types );
// The meta table uses the %i identifier placeholder. {$placeholders} is a generated list of %s
// placeholders for the dynamic post_type IN-list (the documented prepare() exception — an IN() list
// cannot use %i); every post_type and value is bound via prepare().
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$posts = $post_types ? $wpdb->get_results( $wpdb->prepare(
    "SELECT p.ID, p.post_title, p.post_type, p.post_status, p.post_modified, m.score, m.score_payload, m.focus_keyword, m.seo_title, m.seo_description
     FROM {$wpdb->posts} p
     LEFT JOIN %i m ON ( m.post_id = p.ID AND m.blog_id = %d )
     WHERE p.post_status = %s AND p.post_type IN ( {$placeholders} )
     ORDER BY p.post_modified DESC LIMIT 100",
    array_merge( array( $meta_t, $blog ), $args )
), ARRAY_A ) : array();
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

$counts = array( 'good' => 0, 'ok' => 0, 'bad' => 0, 'unscored' => 0 );
foreach ( $posts as $p ) {
    if ( null === $p['score'] ) { $counts['unscored']++; continue; }
    $sc = (int) $p['score'];
    if ( $sc >= 80 )      $counts['good']++;
    elseif ( $sc >= 50 )  $counts['ok']++;
    else                  $counts['bad']++;
}
?>
<?php
if ( isset( $_GET['seoforge_sc'] ) && 'synced' === $_GET['seoforge_sc'] ) {
    echo '<div class="notice notice-success is-dismissible"><p>'
        . esc_html__( 'Search Console sync triggered.', 'brainwerk-seo-suite' ) . '</p></div>';
}
// Search Console performance — Pro only (the renderer is stripped from Free).
if ( class_exists( 'Seoforge_Pro_Search_Console' ) && class_exists( 'Seoforge_License' ) && Seoforge_License::is_pro() ) {
    echo Seoforge_Pro_Search_Console::render_card(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
} else {
    echo Seoforge_Pro::upsell( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        __( 'Search Console & Bing sync', 'brainwerk-seo-suite' ),
        __( 'See real clicks, impressions and average position from Google Search Console and Bing Webmaster Tools, right inside this dashboard.', 'brainwerk-seo-suite' )
    );
}
?>
<div class="seoforge-card">
    <h2><?php esc_html_e( 'On-page SEO scores', 'brainwerk-seo-suite' ); ?></h2>
    <ul class="seoforge-stats-grid">
        <li><strong><?php echo esc_html( $counts['good'] ); ?></strong>
            <span class="seoforge-pill seoforge-pill-good"><?php esc_html_e( 'Good (≥80)', 'brainwerk-seo-suite' ); ?></span></li>
        <li><strong><?php echo esc_html( $counts['ok'] ); ?></strong>
            <span class="seoforge-pill seoforge-pill-ok"><?php esc_html_e( 'OK (50–79)', 'brainwerk-seo-suite' ); ?></span></li>
        <li><strong><?php echo esc_html( $counts['bad'] ); ?></strong>
            <span class="seoforge-pill seoforge-pill-bad"><?php esc_html_e( 'Needs work (<50)', 'brainwerk-seo-suite' ); ?></span></li>
        <li><strong><?php echo esc_html( $counts['unscored'] ); ?></strong>
            <span><?php esc_html_e( 'Not analyzed', 'brainwerk-seo-suite' ); ?></span></li>
    </ul>
    <p style="margin-top:10px;">
        <button type="button" class="button" id="sf-backfill-scores">
            <?php esc_html_e( 'Recalculate all missing scores', 'brainwerk-seo-suite' ); ?>
        </button>
        <span id="sf-backfill-result" style="margin-left:10px;font-weight:600;"></span>
    </p>
    <p class="description"><?php esc_html_e( 'Analyzes every published post/page that has never been scored, in the background, and fills the SEO column. Already-scored posts are left untouched.', 'brainwerk-seo-suite' ); ?></p>
</div>

<div class="seoforge-card">
    <h2><?php esc_html_e( 'Posts & pages', 'brainwerk-seo-suite' ); ?></h2>
    <table class="widefat striped">
        <thead>
            <tr>
                <th><?php esc_html_e( 'Title', 'brainwerk-seo-suite' ); ?></th>
                <th><?php esc_html_e( 'Type', 'brainwerk-seo-suite' ); ?></th>
                <th><?php esc_html_e( 'Focus keyword', 'brainwerk-seo-suite' ); ?></th>
                <th><?php esc_html_e( 'Score', 'brainwerk-seo-suite' ); ?></th>
                <th><?php esc_html_e( 'Updated', 'brainwerk-seo-suite' ); ?></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <?php if ( empty( $posts ) ) : ?>
                <tr><td colspan="6"><?php esc_html_e( 'No public posts found.', 'brainwerk-seo-suite' ); ?></td></tr>
            <?php else : foreach ( $posts as $p ) :
                $score = $p['score'];
                $cls = 'unscored';
                if ( null !== $score ) {
                    $cls = ( $score >= 80 ) ? 'good' : ( ( $score >= 50 ) ? 'ok' : 'bad' );
                }
                $checks = ! empty( $p['score_payload'] ) ? json_decode( $p['score_payload'], true ) : array();
                ?>
                <tr>
                    <td><a href="<?php echo esc_url( get_edit_post_link( $p['ID'] ) ); ?>"><?php echo esc_html( $p['post_title'] ?: '(no title)' ); ?></a></td>
                    <td><?php echo esc_html( $p['post_type'] ); ?></td>
                    <td><?php echo esc_html( $p['focus_keyword'] ?: '—' ); ?></td>
                    <td>
                        <span class="seoforge-pill seoforge-pill-<?php echo esc_attr( $cls ); ?>">
                            <?php echo null === $score ? '—' : esc_html( $score ); ?>
                        </span>
                        <?php if ( ! empty( $checks ) && is_array( $checks ) ) : ?>
                            <details class="seoforge-check-breakdown">
                                <summary><?php esc_html_e( 'Breakdown', 'brainwerk-seo-suite' ); ?></summary>
                                <ul class="seoforge-checks">
                                    <?php foreach ( $checks as $key => $c ) : ?>
                                        <li class="seoforge-check seoforge-check-<?php echo esc_attr( $c['status'] ); ?>">
                                            <span class="seoforge-check-icon" aria-hidden="true"><?php echo esc_html( Seoforge_Post_Meta_Box::status_icon( $c['status'] ) ); ?></span>
                                            <strong><?php echo esc_html( ucwords( str_replace( '_', ' ', $key ) ) ); ?>:</strong>
                                            <?php echo esc_html( $c['message'] ); ?>
                                            <?php if ( ! empty( $c['tip'] ) && 'ok' !== $c['status'] ) : ?>
                                                <div class="seoforge-check-tip"><?php echo esc_html( $c['tip'] ); ?></div>
                                            <?php endif; ?>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </details>
                        <?php endif; ?>
                    </td>
                    <td><?php echo esc_html( mysql2date( get_option( 'date_format' ), $p['post_modified'] ) ); ?></td>
                    <td>
                        <button type="button" class="button button-small sf-analyze-btn" data-post="<?php echo (int) $p['ID']; ?>">
                            <?php esc_html_e( 'Analyze', 'brainwerk-seo-suite' ); ?>
                        </button>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
        </tbody>
    </table>
</div>
