<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum
/**
 * GT BOGO Engine — Store Status & Go Live Command Center
 *
 * Enterprise store readiness dashboard:
 *   - Animated health score gauge (0–100)
 *   - GT_BOGO_Go_Live::get_status() — 8-step setup checklist
 *   - GT_BOGO_Store_Health_Monitor::get_results() — 15 automated checks
 *   - Complete DB table inventory with row counts and sizes
 *   - WP Cron job health (all GT BOGO crons, last run, next run)
 *   - PHP + WordPress environment panel
 *   - Cache layer detection (WP Rocket, LiteSpeed, Redis, OPcache)
 *   - Signal Bus last-write timestamps
 *   - License sync status
 *   - AI Engine status
 *   - One-click fix buttons via AJAX
 *   - Force rescan button
 *   - Export diagnostic report
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! current_user_can( 'manage_options' ) ) {
    wp_die( esc_html__( 'Insufficient permissions.', 'gt-bogo-engine' ) );
}

global $wpdb;

$version = defined( 'GT_BOGO_VERSION' ) ? GT_BOGO_VERSION : '5.0.0';
$is_pro  = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$nonce   = wp_create_nonce( 'gtbogo_store_status' );

/* ── Store Health Monitor results ─────────────────────────────────────────── */
$health_results = [];
$health_score   = 100;
$health_crits   = 0;
$health_warns   = 0;
$health_scanned = '';

if ( class_exists( 'GT_BOGO_Store_Health_Monitor' ) ) {
    $hr           = GT_BOGO_Store_Health_Monitor::get_results();
    $health_score = (int) ( $hr['score']     ?? 100 );
    $health_crits = (int) ( $hr['criticals'] ?? 0 );
    $health_warns = (int) ( $hr['warnings']  ?? 0 );
    $health_scanned = $hr['scanned_at'] ?? '';
    foreach ( $hr['checks'] ?? [] as $chk ) {
        $health_results[] = $chk;
    }
}

/* ── Go Live status ───────────────────────────────────────────────────────── */
$go_live_checks = [];
if ( class_exists( 'GT_BOGO_Go_Live' ) ) {
    $go_live_checks = GT_BOGO_Go_Live::instance()->get_status();
}
$go_live_pass  = count( array_filter( $go_live_checks, fn($c) => $c['pass'] ) );
$go_live_total = count( $go_live_checks );

/* ── DB table inventory ───────────────────────────────────────────────────── */
$gt_tables = [
    'gtbogo_rules'           => 'Rules Engine',
    'gtbogo_analytics'       => 'Analytics Log',
    'gtbogo_owned_packs'     => 'Owned Packs',
    'gtbogo_licenses'        => 'License Records',
    'gtbogo_customers'       => 'Customer Profiles',
    'gtbogo_bundles'         => 'Bundle Intelligence',
    'gtbogo_outcomes'        => 'Outcome Capture',
    'gtbogo_decisions'       => 'Decision Provenance',
    'gtbogo_email_log'       => 'Email Log',
    'gtbogo_ab_tests'        => 'A/B Tests',
    'gtbogo_ab_assignments'  => 'A/B Assignments',
    'gtbogo_audit_log'       => 'Audit Log',
    'gtbogo_geo_rules'       => 'Geo Rules',
    'gtbogo_sp_impressions'  => 'SP Impressions',
    'gtbogo_stock_velocity'  => 'Stock Velocity',
    'gtbogo_association_rules' => 'Association Rules',
    'gtbogo_lifecycle_events'  => 'Lifecycle Events',
    'gtbogo_customer_profiles' => 'Customer Profiles v2',
    'gtbogo_ai_log'          => 'AI Audit Log',
];

$table_data = [];
foreach ( $gt_tables as $tbl => $label ) {
    $full  = $wpdb->prefix . $tbl;
    $exists = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $full ) ); // phpcs:ignore
    $rows   = 0;
    $size_kb = 0;
    if ( $exists ) {
        $rows    = (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$full}`" ); // phpcs:ignore
        $size_row = $wpdb->get_row( $wpdb->prepare( // phpcs:ignore
            "SELECT ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024, 1) AS size_kb
             FROM information_schema.TABLES
             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s",
            $full
        ), ARRAY_A );
        $size_kb = (float) ( $size_row['size_kb'] ?? 0 );
    }
    $table_data[] = [
        'name'    => $full,
        'label'   => $label,
        'exists'  => $exists,
        'rows'    => $rows,
        'size_kb' => $size_kb,
    ];
}

/* ── WP Cron jobs ─────────────────────────────────────────────────────────── */
$gt_crons = [
    'gtbogo_expire_outcomes'       => 'Expire Outcomes',
    'gtbogo_ai_gap_analysis'       => 'AI Gap Analysis',
    'gtbogo_stock_velocity_scan'   => 'Stock Velocity Scan',
    'gtbogo_association_scan'      => 'Association Mining Scan',
    'gtbogo_health_scan'           => 'Store Health Scan',
    'gtbogo_sync_queue'            => 'Sync Queue',
    'gtbogo_ltv_update'            => 'LTV Update',
    'gtbogo_cron_coordinator'      => 'Cron Coordinator',
    'gtbogo_ai_performance_coach'  => 'AI Performance Coach',
];

$cron_data = [];
$all_crons = _get_cron_array() ?: [];
foreach ( $gt_crons as $hook => $label ) {
    $next_run   = wp_next_scheduled( $hook );
    $registered = false;
    $schedule   = '';
    foreach ( $all_crons as $timestamp => $jobs ) {
        if ( isset( $jobs[ $hook ] ) ) {
            $registered = true;
            $job_data   = reset( $jobs[ $hook ] );
            $schedule   = $job_data['schedule'] ?? 'single';
            break;
        }
    }
    $overdue = $next_run && $next_run < time() - 300;
    $cron_data[] = [
        'hook'       => $hook,
        'label'      => $label,
        'registered' => $registered,
        'schedule'   => $schedule,
        'next_run'   => $next_run,
        'overdue'    => $overdue,
    ];
}

/* ── PHP / WP environment ─────────────────────────────────────────────────── */
$php_ver    = phpversion();
$wp_ver     = get_bloginfo( 'version' );
$wc_ver     = defined( 'WC_VERSION' ) ? WC_VERSION : 'Not detected';
$mem_limit  = ini_get( 'memory_limit' );
$max_exec   = (int) ini_get( 'max_execution_time' );
$ssl        = is_ssl() || strpos( home_url(), 'https://' ) === 0;
$debug_on   = defined( 'WP_DEBUG' ) && WP_DEBUG;
$hpos       = class_exists( 'Automattic\WooCommerce\Utilities\OrderUtil' );

$php_exts = [
    'sodium'   => extension_loaded( 'sodium' ),
    'mbstring' => extension_loaded( 'mbstring' ),
    'curl'     => extension_loaded( 'curl' ),
    'json'     => extension_loaded( 'json' ),
    'zip'      => extension_loaded( 'zip' ),
    'redis'    => extension_loaded( 'redis' ) || class_exists( 'Redis' ),
    'intl'     => extension_loaded( 'intl' ),
    'openssl'  => extension_loaded( 'openssl' ),
];

/* ── Signal Bus last writes ───────────────────────────────────────────────── */
$signal_snapshot = [];
if ( class_exists( 'GT_BOGO_Signal_Bus' ) ) {
    $signals = GT_BOGO_Signal_Bus::get_all_as_array();
    foreach ( $signals as $key => $val ) {
        $signal_snapshot[ $key ] = [
            'value'  => $val,
            'status' => abs( (float) $val ) > 0 ? 'active' : 'idle',
        ];
    }
}

/* ── AI Engine status ─────────────────────────────────────────────────────── */
$ai_key_set    = class_exists( 'GT_BOGO_AI_Engine' ) && ! empty( GT_BOGO_AI_Engine::get_api_key() );
$ai_rate_used  = (int) get_transient( 'gtbogo_ai_rate_count' ) ?: 0;
$ai_rate_limit = 100;

/* ── License status ───────────────────────────────────────────────────────── */
$lic_key     = get_option( 'gtbogo_license_key', '' );
$lic_status  = get_option( 'gtbogo_license_status', 'inactive' );
$lic_expires = get_option( 'gtbogo_license_expires', '' );
$lic_days    = 0;
if ( $lic_expires ) {
    $lic_days = (int) ceil( ( strtotime( $lic_expires ) - time() ) / DAY_IN_SECONDS );
}

/* ── Score gauge colour ───────────────────────────────────────────────────── */
$gauge_color = $health_score >= 80 ? '#22c55e' : ( $health_score >= 60 ? '#f59e0b' : '#ef4444' );
$gauge_label = $health_score >= 80 ? 'Excellent' : ( $health_score >= 60 ? 'Needs Attention' : 'Critical Issues' );

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     PAGE HEADER
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-page-header gt-animate-in" style="align-items:flex-start">
    <div>
        <h1 class="gt-page-title">SYSTEM STATUS</h1>
        <p class="gt-page-subtitle">
            Store readiness, system health, database integrity, and infrastructure
            monitoring for GT BOGO Engine PRO v<?php echo esc_html( $version ); ?>.
        </p>
    </div>
    <div style="display:flex;gap:10px;flex-wrap:wrap">
        <button type="button" class="gt-btn gt-btn-primary"
            onclick="gtSsRescan('<?php echo esc_js( $nonce ); ?>')"
            id="gt-ss-rescan-btn">
            ↻ Force Rescan
        </button>
        <button type="button" class="gt-btn gt-btn-ghost"
            onclick="gtSsExportDiagnostic('<?php echo esc_js( $nonce ); ?>')">
            ↓ Export Diagnostic
        </button>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TOP METRICS ROW — Score Gauge + Go Live Progress + Critical / Warnings
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:auto 1fr 1fr 1fr;gap:16px;margin-bottom:20px;align-items:stretch">

    <!-- ── Health Score Gauge ─────────────────────────────────────────── -->
    <div class="gt-card" style="padding:24px 32px;text-align:center;min-width:180px">
        <div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:12px">
            Store Health Score
        </div>
        <div style="position:relative;width:120px;height:120px;margin:0 auto 12px">
            <svg viewBox="0 0 120 120" style="width:120px;height:120px;transform:rotate(-90deg)">
                <!-- Track -->
                <circle cx="60" cy="60" r="50" fill="none" stroke="rgba(255,255,255,0.06)" stroke-width="10"/>
                <!-- Score arc -->
                <circle cx="60" cy="60" r="50" fill="none"
                    stroke="<?php echo esc_attr( $gauge_color ); ?>"
                    stroke-width="10"
                    stroke-linecap="round"
                    stroke-dasharray="<?php echo esc_attr( (string) round( $health_score * 3.14159 ) ); ?> 314"
                    id="gt-ss-gauge-arc"
                    style="transition:stroke-dasharray 1.4s cubic-bezier(.4,0,.2,1)"/>
            </svg>
            <div style="position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center">
                <div style="font-size:30px;font-weight:900;color:<?php echo esc_attr( $gauge_color ); ?>;line-height:1" id="gt-ss-score-num">
                    <?php echo esc_html( (string) $health_score ); ?>
                </div>
                <div style="font-size:10px;color:var(--gt-subtle);font-weight:600">/100</div>
            </div>
        </div>
        <div style="font-size:13px;font-weight:700;color:<?php echo esc_attr( $gauge_color ); ?>">
            <?php echo esc_html( $gauge_label ); ?>
        </div>
        <?php if ( $health_scanned ) : ?>
        <div style="font-size:10px;color:var(--gt-subtle);margin-top:4px">
            Scanned <?php echo esc_html( gmdate( 'H:i', strtotime( $health_scanned ) ) ); ?> UTC
        </div>
        <?php endif; ?>
    </div>

    <!-- ── Go Live Progress ───────────────────────────────────────────── -->
    <div class="gt-card" style="padding:20px 24px">
        <div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:10px">
            Go Live Checklist — <?php echo esc_html( $go_live_pass ); ?> / <?php echo esc_html( $go_live_total ); ?> Complete
        </div>
        <div style="height:6px;background:rgba(255,255,255,0.06);border-radius:3px;overflow:hidden;margin-bottom:14px">
            <?php $gl_pct = $go_live_total > 0 ? round( $go_live_pass / $go_live_total * 100 ) : 0; ?>
            <div style="height:100%;width:<?php echo esc_attr( (string) $gl_pct ); ?>%;background:<?php echo $gl_pct >= 100 ? '#22c55e' : 'var(--gt-red)'; ?>;border-radius:3px;transition:width 1s ease"></div>
        </div>
        <div style="display:flex;flex-direction:column;gap:6px">
        <?php foreach ( array_slice( $go_live_checks, 0, 6 ) as $glc ) : ?>
        <div style="display:flex;align-items:center;justify-content:space-between;gap:10px">
            <span style="font-size:12px;color:<?php echo $glc['pass'] ? 'var(--gt-subtle)' : 'var(--gt-white)'; ?>">
                <?php echo $glc['pass'] ? '✓' : '○'; ?> <?php echo esc_html( $glc['label'] ); ?>
            </span>
            <?php if ( ! $glc['pass'] && ! empty( $glc['action'] ) ) : ?>
            <a href="<?php echo esc_url( $glc['action'] ); ?>"
               style="font-size:10px;color:var(--gt-red);font-weight:700;text-decoration:none;white-space:nowrap;flex-shrink:0">
                <?php echo esc_html( $glc['action_label'] ?? 'Fix →' ); ?>
            </a>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
        </div>
        <?php if ( count( $go_live_checks ) > 6 ) : ?>
        <button type="button" onclick="gtSsToggleChecklist()" id="gt-ss-gl-more"
                style="margin-top:10px;background:none;border:none;color:var(--gt-red);cursor:pointer;font-size:12px;font-family:inherit;padding:0">
            + <?php echo esc_html( (string) ( count( $go_live_checks ) - 6 ) ); ?> more steps
        </button>
        <div id="gt-ss-gl-extra" style="display:none;margin-top:8px">
        <?php foreach ( array_slice( $go_live_checks, 6 ) as $glc ) : ?>
        <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:5px">
            <span style="font-size:12px;color:<?php echo $glc['pass'] ? 'var(--gt-subtle)' : 'var(--gt-white)'; ?>">
                <?php echo $glc['pass'] ? '✓' : '○'; ?> <?php echo esc_html( $glc['label'] ); ?>
            </span>
            <?php if ( ! $glc['pass'] && ! empty( $glc['action'] ) ) : ?>
            <a href="<?php echo esc_url( $glc['action'] ); ?>"
               style="font-size:10px;color:var(--gt-red);font-weight:700;text-decoration:none;white-space:nowrap">
                <?php echo esc_html( $glc['action_label'] ?? 'Fix →' ); ?>
            </a>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- ── Critical Issues ────────────────────────────────────────────── -->
    <div class="gt-card" style="padding:20px 24px;border-color:<?php echo $health_crits > 0 ? 'rgba(239,68,68,0.25)' : 'var(--gt-border)'; ?>">
        <div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:8px">
            Critical Issues
        </div>
        <div style="font-size:48px;font-weight:900;color:<?php echo $health_crits > 0 ? '#ef4444' : '#22c55e'; ?>;line-height:1;margin-bottom:6px">
            <?php echo esc_html( (string) $health_crits ); ?>
        </div>
        <div style="font-size:12px;color:var(--gt-subtle)">
            <?php echo $health_crits === 0 ? 'No critical issues detected' : 'Require immediate action'; ?>
        </div>
        <?php if ( $health_crits > 0 ) : ?>
        <a href="#gt-ss-health-checks" style="display:inline-block;margin-top:10px;font-size:11px;color:var(--gt-red);text-decoration:none;font-weight:700">
            View issues ↓
        </a>
        <?php endif; ?>
    </div>

    <!-- ── Warnings ───────────────────────────────────────────────────── -->
    <div class="gt-card" style="padding:20px 24px;border-color:<?php echo $health_warns > 0 ? 'rgba(245,158,11,0.25)' : 'var(--gt-border)'; ?>">
        <div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:8px">
            Warnings
        </div>
        <div style="font-size:48px;font-weight:900;color:<?php echo $health_warns > 0 ? '#f59e0b' : '#22c55e'; ?>;line-height:1;margin-bottom:6px">
            <?php echo esc_html( (string) $health_warns ); ?>
        </div>
        <div style="font-size:12px;color:var(--gt-subtle)">
            <?php echo $health_warns === 0 ? 'No warnings detected' : 'Should be addressed soon'; ?>
        </div>
        <?php if ( $health_warns > 0 ) : ?>
        <a href="#gt-ss-health-checks" style="display:inline-block;margin-top:10px;font-size:11px;color:#f59e0b;text-decoration:none;font-weight:700">
            View warnings ↓
        </a>
        <?php endif; ?>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     HEALTH CHECKS — All 15 Automated Checks
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px" id="gt-ss-health-checks">
    <div class="gt-card-header">
        <h2 class="gt-card-title">⚕ Automated Health Checks</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Runs every 6 hours · <button onclick="gtSsRescan('<?php echo esc_js($nonce); ?>')" style="background:none;border:none;color:var(--gt-red);cursor:pointer;font-size:12px;font-family:inherit">Force rescan</button></span>
    </div>

    <?php if ( empty( $health_results ) ) : ?>
    <div style="padding:32px 24px;text-align:center;color:var(--gt-subtle)">
        <div style="font-size:32px;margin-bottom:10px">🔍</div>
        GT_BOGO_Store_Health_Monitor not available. Ensure the plugin is fully activated.
    </div>
    <?php else : ?>

    <!-- Severity filter tabs -->
    <div style="display:flex;gap:2px;border-bottom:1px solid var(--gt-border);padding:0 20px">
        <?php
        $sev_tabs = [ 'all' => 'All', 'critical' => 'Critical', 'warning' => 'Warning', 'info' => 'Info', 'ok' => 'OK' ];
        foreach ( $sev_tabs as $sv => $sl ) :
        ?>
        <button class="gt-ss-sev-tab" data-sev="<?php echo esc_attr($sv); ?>"
            onclick="gtSsFilterSev('<?php echo esc_js($sv); ?>')"
            style="padding:10px 16px;background:none;border:none;border-bottom:2px solid <?php echo $sv==='all'?'var(--gt-red)':'transparent'; ?>;
                   color:<?php echo $sv==='all'?'var(--gt-white)':'var(--gt-subtle)'; ?>;cursor:pointer;font-family:inherit;
                   font-size:12px;font-weight:700;transition:color .15s;margin-bottom:-1px">
            <?php echo esc_html($sl); ?>
        </button>
        <?php endforeach; ?>
    </div>

    <div id="gt-ss-checks-container">
    <?php
    $sev_icons  = [ 'critical' => '🔴', 'warning' => '🟡', 'info' => '🔵', 'ok' => '✅' ];
    $sev_colors = [ 'critical' => '#ef4444', 'warning' => '#f59e0b', 'info' => '#3b82f6', 'ok' => '#22c55e' ];

    foreach ( $health_results as $check ) :
        $sev    = $check['severity'] ?? 'info';
        $status = $check['status']   ?? 'ok';
        $is_ok  = $status === 'ok';
        $icon   = $sev_icons[ $is_ok ? 'ok' : $status ] ?? '🔵';
        $color  = $sev_colors[ $is_ok ? 'ok' : $status ] ?? '#3b82f6';
        $has_fix = ! empty( $check['fix_id'] ) && ! $is_ok;
    ?>
    <div class="gt-ss-check-row"
         data-sev="<?php echo esc_attr( $is_ok ? 'ok' : $sev ); ?>"
         style="border-bottom:1px solid var(--gt-border);padding:0">

        <!-- Summary row (always visible) -->
        <div onclick="gtSsToggleCheck(this)"
             style="display:flex;align-items:center;gap:14px;padding:14px 20px;cursor:pointer;
                    transition:background .15s"
             onmouseover="this.style.background='rgba(255,255,255,0.02)'"
             onmouseout="this.style.background=''">

            <span style="font-size:18px;flex-shrink:0"><?php echo esc_html($icon); ?></span>

            <div style="flex:1;min-width:0">
                <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
                    <span style="font-size:13px;font-weight:700;color:var(--gt-white)">
                        <?php echo esc_html( $check['title'] ?? $check['id'] ); ?>
                    </span>
                    <span style="padding:2px 8px;border-radius:20px;font-size:10px;font-weight:800;
                                 text-transform:uppercase;letter-spacing:.06em;
                                 background:<?php echo esc_attr($color); ?>15;
                                 color:<?php echo esc_attr($color); ?>">
                        <?php echo esc_html( $is_ok ? 'OK' : strtoupper($sev) ); ?>
                    </span>
                    <?php if ( ! empty( $check['current'] ) && ! $is_ok ) : ?>
                    <span style="font-size:11px;color:var(--gt-subtle);font-family:'DM Mono','Courier New',monospace">
                        Current: <?php echo esc_html( $check['current'] ); ?>
                    </span>
                    <?php endif; ?>
                </div>
                <?php if ( ! $is_ok ) : ?>
                <div style="font-size:12px;color:var(--gt-subtle);margin-top:3px;line-height:1.4">
                    <?php echo esc_html( $check['message'] ?? '' ); ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- Fix button -->
            <?php if ( $has_fix ) : ?>
            <button type="button"
                onclick="event.stopPropagation();gtSsFix('<?php echo esc_js($check['fix_id']); ?>','<?php echo esc_js($nonce); ?>',this)"
                style="padding:6px 14px;background:var(--gt-red);color:#fff;border:none;border-radius:6px;
                       font-size:11px;font-weight:700;cursor:pointer;font-family:inherit;flex-shrink:0;
                       transition:opacity .15s"
                onmouseover="this.style.opacity='.8'"
                onmouseout="this.style.opacity='1'">
                <?php echo esc_html( $check['fix_label'] ?? 'Fix' ); ?>
            </button>
            <?php endif; ?>

            <span class="gt-ss-check-arrow" style="color:var(--gt-subtle);font-size:12px;flex-shrink:0">▸</span>
        </div>

        <!-- Expanded detail (hidden) -->
        <div class="gt-ss-check-detail" style="display:none;padding:0 20px 16px 52px">
            <div style="font-size:12px;color:var(--gt-subtle);line-height:1.6;background:rgba(255,255,255,0.02);
                        border-radius:6px;padding:12px 14px;border:1px solid var(--gt-border)">
                <?php echo esc_html( $check['message'] ?? 'No additional details available.' ); ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     DATABASE TABLE INVENTORY
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🗄 Database Table Inventory</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">
            <?php echo esc_html( (string) count( array_filter( $table_data, fn($t) => $t['exists'] ) ) ); ?> /
            <?php echo esc_html( (string) count( $table_data ) ); ?> tables present
        </span>
    </div>
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead>
                <tr style="border-bottom:1px solid var(--gt-border)">
                    <?php foreach ( ['Table Name','Module','Status','Row Count','Size'] as $col ) : ?>
                    <th style="padding:9px 14px;text-align:left;font-size:10px;font-weight:800;
                               letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">
                        <?php echo esc_html($col); ?>
                    </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
            <?php foreach ( $table_data as $t ) : ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
                <td style="padding:9px 14px;font-family:'DM Mono','Courier New',monospace;font-size:11px;color:var(--gt-subtle)">
                    <?php echo esc_html( $t['name'] ); ?>
                </td>
                <td style="padding:9px 14px;color:var(--gt-white);font-size:12px">
                    <?php echo esc_html( $t['label'] ); ?>
                </td>
                <td style="padding:9px 14px">
                    <?php if ( $t['exists'] ) : ?>
                    <span style="color:#22c55e;font-weight:700;font-size:11px">✓ Present</span>
                    <?php else : ?>
                    <span style="color:#ef4444;font-weight:700;font-size:11px">✗ Missing</span>
                    <?php endif; ?>
                </td>
                <td style="padding:9px 14px;color:<?php echo $t['rows'] > 0 ? 'var(--gt-white)' : 'var(--gt-subtle)'; ?>;font-variant-numeric:tabular-nums">
                    <?php echo $t['exists'] ? esc_html( number_format( $t['rows'] ) ) : '—'; ?>
                </td>
                <td style="padding:9px 14px;color:var(--gt-subtle)">
                    <?php echo $t['exists'] && $t['size_kb'] > 0 ? esc_html( $t['size_kb'] . ' KB' ) : '—'; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     WP CRON JOB HEALTH
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">⏱ WP-Cron Job Health</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">All GT BOGO scheduled events</span>
    </div>
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead>
                <tr style="border-bottom:1px solid var(--gt-border)">
                    <?php foreach ( ['Cron Job','Hook','Schedule','Next Run','Status'] as $col ) : ?>
                    <th style="padding:9px 14px;text-align:left;font-size:10px;font-weight:800;
                               letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">
                        <?php echo esc_html($col); ?>
                    </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
            <?php foreach ( $cron_data as $cron ) :
                $c_color = ! $cron['registered'] ? '#ef4444' : ( $cron['overdue'] ? '#f59e0b' : '#22c55e' );
                $c_label = ! $cron['registered'] ? 'Not Registered' : ( $cron['overdue'] ? 'Overdue' : 'Healthy' );
                $next_fmt = $cron['next_run'] ? human_time_diff( $cron['next_run'] ) . ' from now' : 'Not scheduled';
                if ( $cron['next_run'] && $cron['next_run'] < time() ) {
                    $next_fmt = human_time_diff( $cron['next_run'] ) . ' ago (overdue)';
                }
            ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
                <td style="padding:9px 14px;font-weight:600;color:var(--gt-white)"><?php echo esc_html($cron['label']); ?></td>
                <td style="padding:9px 14px;font-family:'DM Mono','Courier New',monospace;font-size:11px;color:var(--gt-subtle)"><?php echo esc_html($cron['hook']); ?></td>
                <td style="padding:9px 14px;color:var(--gt-subtle)"><?php echo esc_html($cron['schedule'] ?: '—'); ?></td>
                <td style="padding:9px 14px;color:<?php echo $cron['overdue'] ? '#f59e0b' : 'var(--gt-subtle)'; ?>;font-size:11px"><?php echo esc_html($next_fmt); ?></td>
                <td style="padding:9px 14px">
                    <span style="padding:2px 8px;border-radius:20px;font-size:10px;font-weight:800;
                                 background:<?php echo esc_attr($c_color); ?>15;color:<?php echo esc_attr($c_color); ?>">
                        <?php echo esc_html($c_label); ?>
                    </span>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     PHP + WORDPRESS ENVIRONMENT
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px">

    <!-- PHP Environment -->
    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">🐘 PHP Environment</h2>
        </div>
        <?php
        $env_rows = [
            [ 'PHP Version',         $php_ver,         version_compare($php_ver,'8.0','>=') ],
            [ 'Memory Limit',        $mem_limit,        in_array($mem_limit,['256M','512M','1G','-1'],true) ],
            [ 'Max Execution Time',  $max_exec.'s',     $max_exec >= 60 || $max_exec === 0 ],
            [ 'HTTPS',               $ssl?'Enabled':'Disabled', $ssl ],
            [ 'WP Debug Mode',       $debug_on?'ON — disable on production':'OFF', ! $debug_on ],
            [ 'HPOS (WC Orders)',     $hpos?'Available':'Legacy tables', true ],
        ];
        foreach ( $env_rows as $row ) :
            $rc = $row[2] ? '#22c55e' : '#ef4444';
        ?>
        <div style="display:flex;justify-content:space-between;align-items:center;padding:9px 0;border-bottom:1px solid rgba(255,255,255,0.04)">
            <span style="font-size:12px;color:var(--gt-soft)"><?php echo esc_html($row[0]); ?></span>
            <span style="font-size:12px;font-weight:700;color:<?php echo esc_attr($rc); ?>"><?php echo esc_html($row[1]); ?></span>
        </div>
        <?php endforeach; ?>

        <!-- PHP Extensions -->
        <div style="margin-top:12px">
            <div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:8px">PHP Extensions</div>
            <div style="display:flex;flex-wrap:wrap;gap:6px">
            <?php foreach ( $php_exts as $ext => $loaded ) : ?>
            <span style="padding:3px 10px;border-radius:20px;font-size:10px;font-weight:700;
                         background:<?php echo $loaded?'rgba(34,197,94,0.08)':'rgba(239,68,68,0.08)'; ?>;
                         color:<?php echo $loaded?'#22c55e':'#ef4444'; ?>;
                         border:1px solid <?php echo $loaded?'rgba(34,197,94,0.3)':'rgba(239,68,68,0.2)'; ?>">
                <?php echo esc_html($ext); ?>
            </span>
            <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- WordPress / WooCommerce -->
    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">🔵 WordPress & WooCommerce</h2>
        </div>
        <?php
        $wp_rows = [
            [ 'WordPress Version',   $wp_ver,  version_compare($wp_ver,'6.0','>=') ],
            [ 'WooCommerce Version', $wc_ver,  $wc_ver !== 'Not detected' ],
            [ 'GT BOGO Version',     $version, true ],
            [ 'License Status',      ucfirst($lic_status), $lic_status === 'active' ],
            [ 'License Expiry',      $lic_expires ?: 'N/A', $lic_days > 30 || $lic_days === 0 ],
            [ 'AI Engine',           $ai_key_set?'API Key Configured':'No API Key', $ai_key_set ],
        ];
        foreach ( $wp_rows as $row ) :
            $rc = $row[2] ? '#22c55e' : '#ef4444';
        ?>
        <div style="display:flex;justify-content:space-between;align-items:center;padding:9px 0;border-bottom:1px solid rgba(255,255,255,0.04)">
            <span style="font-size:12px;color:var(--gt-soft)"><?php echo esc_html($row[0]); ?></span>
            <span style="font-size:12px;font-weight:700;color:<?php echo esc_attr($rc); ?>"><?php echo esc_html($row[1]); ?></span>
        </div>
        <?php endforeach; ?>

        <!-- License expiry banner -->
        <?php if ( $lic_status === 'active' && $lic_days > 0 && $lic_days <= 30 ) : ?>
        <div style="margin-top:12px;padding:10px 12px;background:rgba(239,68,68,0.06);border:1px solid rgba(239,68,68,0.2);border-radius:6px">
            <div style="font-size:12px;color:#fca5a5;font-weight:700">
                ⚠ License expires in <?php echo esc_html( (string) $lic_days ); ?> days
            </div>
            <a href="<?php echo esc_url( admin_url('admin.php?page=gt-bogo-engine&tab=license') ); ?>"
               style="font-size:11px;color:var(--gt-red);font-weight:700;text-decoration:none">
                Renew now →
            </a>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     AI ENGINE + SIGNAL BUS STATUS
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px">

    <!-- AI Engine Status -->
    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">✦ AI Engine Status</h2>
        </div>
        <div style="display:flex;align-items:center;gap:14px;padding:14px 0;border-bottom:1px solid rgba(255,255,255,0.04)">
            <div style="width:10px;height:10px;border-radius:50%;background:<?php echo $ai_key_set?'#22c55e':'#ef4444'; ?>;
                        box-shadow:0 0 8px <?php echo $ai_key_set?'#22c55e':'#ef4444'; ?>;flex-shrink:0"></div>
            <div>
                <div style="font-size:13px;font-weight:700;color:var(--gt-white)">
                    <?php echo $ai_key_set ? 'API Key Configured' : 'No API Key'; ?>
                </div>
                <div style="font-size:11px;color:var(--gt-subtle)">
                    <?php echo $ai_key_set ? 'Claude claude-sonnet-4-6 connected' : 'Add key in AI Intelligence tab'; ?>
                </div>
            </div>
        </div>
        <?php if ( $ai_key_set ) : ?>
        <!-- Rate limit meter -->
        <div style="padding:12px 0">
            <div style="display:flex;justify-content:space-between;margin-bottom:6px">
                <span style="font-size:12px;color:var(--gt-subtle)">Daily API Usage</span>
                <span style="font-size:12px;font-weight:700;color:var(--gt-white)"><?php echo esc_html($ai_rate_used); ?> / <?php echo esc_html($ai_rate_limit); ?></span>
            </div>
            <?php $rate_pct = round($ai_rate_used / $ai_rate_limit * 100); ?>
            <div style="height:6px;background:rgba(255,255,255,0.06);border-radius:3px;overflow:hidden">
                <div style="height:100%;width:<?php echo esc_attr((string)$rate_pct); ?>%;
                            background:<?php echo $rate_pct>80?'#ef4444':($rate_pct>60?'#f59e0b':'#22c55e'); ?>;
                            border-radius:3px;transition:width 1s ease"></div>
            </div>
            <div style="font-size:10px;color:var(--gt-subtle);margin-top:4px">Resets at midnight UTC</div>
        </div>
        <?php endif; ?>
        <div style="font-size:11px;color:var(--gt-subtle);padding-top:8px">
            Features: Pack Recommender · Gap Analyzer · Copywriter · Performance Coach · Cart Intelligence · Dynamic Copy
        </div>
    </div>

    <!-- Signal Bus snapshot -->
    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">📡 Signal Bus Snapshot</h2>
            <span style="font-size:11px;color:var(--gt-subtle)"><?php echo esc_html( (string) count($signal_snapshot) ); ?> signals</span>
        </div>
        <?php if ( empty($signal_snapshot) ) : ?>
        <div style="padding:14px 0;font-size:12px;color:var(--gt-subtle)">
            Signal Bus not populated yet. Signals are written when customers browse the cart.
        </div>
        <?php else : ?>
        <div style="max-height:220px;overflow-y:auto">
        <?php foreach ( array_slice($signal_snapshot, 0, 15) as $sig_key => $sig ) :
            $sv = (float) $sig['value'];
            $sb = min( 100, abs($sv) / 5 * 100 );
            $sc = $sv > 3 ? '#ef4444' : ($sv > 1.5 ? '#f59e0b' : '#22c55e');
        ?>
        <div style="display:flex;align-items:center;gap:8px;padding:5px 0;border-bottom:1px solid rgba(255,255,255,0.03)">
            <span style="font-size:10px;color:var(--gt-subtle);width:140px;flex-shrink:0;
                         font-family:'DM Mono','Courier New',monospace;overflow:hidden;text-overflow:ellipsis">
                <?php echo esc_html($sig_key); ?>
            </span>
            <div style="flex:1;height:4px;background:rgba(255,255,255,0.06);border-radius:2px;overflow:hidden">
                <div style="height:100%;width:<?php echo esc_attr((string)$sb); ?>%;background:<?php echo esc_attr($sc); ?>;border-radius:2px"></div>
            </div>
            <span style="font-size:10px;font-weight:700;color:<?php echo esc_attr($sc); ?>;width:28px;text-align:right;flex-shrink:0">
                <?php echo esc_html(number_format($sv,1)); ?>
            </span>
        </div>
        <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     NOTIFICATION AREA
════════════════════════════════════════════════════════════════════════════ -->
<div id="gt-ss-notification" style="display:none" class="gt-notice"></div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     JAVASCRIPT
════════════════════════════════════════════════════════════════════════════ -->
<script>
(function() {
'use strict';

/* ── Go Live checklist toggle ─────────────────────────────────────────── */
window.gtSsToggleChecklist = function() {
    var extra = document.getElementById('gt-ss-gl-extra');
    var btn   = document.getElementById('gt-ss-gl-more');
    if (!extra) return;
    var open = extra.style.display !== 'none';
    extra.style.display = open ? 'none' : 'block';
    if (btn) btn.textContent = open ? '+ show more steps' : '− hide extra steps';
};

/* ── Check row accordion ──────────────────────────────────────────────── */
window.gtSsToggleCheck = function(header) {
    var row    = header.closest('.gt-ss-check-row');
    var detail = row.querySelector('.gt-ss-check-detail');
    var arrow  = row.querySelector('.gt-ss-check-arrow');
    if (!detail) return;
    var open = detail.style.display !== 'none';
    detail.style.display = open ? 'none' : 'block';
    if (arrow) arrow.textContent = open ? '▸' : '▾';
};

/* ── Severity filter tabs ─────────────────────────────────────────────── */
window.gtSsFilterSev = function(sev) {
    /* Update tab styles */
    document.querySelectorAll('.gt-ss-sev-tab').forEach(function(tab) {
        var active = tab.getAttribute('data-sev') === sev;
        tab.style.borderBottomColor = active ? 'var(--gt-red)' : 'transparent';
        tab.style.color             = active ? 'var(--gt-white)' : 'var(--gt-subtle)';
    });
    /* Filter rows */
    document.querySelectorAll('.gt-ss-check-row').forEach(function(row) {
        var rs = row.getAttribute('data-sev') || '';
        row.style.display = (sev === 'all' || rs === sev) ? '' : 'none';
    });
};

/* ── One-click Fix ────────────────────────────────────────────────────── */
window.gtSsFix = function(fixId, nonce, btn) {
    btn.textContent = 'Applying…';
    btn.disabled    = true;

    var fd = new FormData();
    fd.append('action',  'gtbogo_ss_apply_fix');
    fd.append('nonce',   nonce);
    fd.append('fix_id',  fixId);

    fetch(ajaxurl, { method:'POST', body:fd })
        .then(function(r) { return r.json(); })
        .then(function(resp) {
            if (resp.success) {
                btn.textContent  = '✓ Applied';
                btn.style.background = '#22c55e';
                gtSsNotify('success', resp.data.message || 'Fix applied. Rescanning…');
                setTimeout(function() { gtSsRescan(nonce); }, 1500);
            } else {
                btn.textContent = 'Fix';
                btn.disabled    = false;
                gtSsNotify('error', resp.data || 'Fix failed.');
            }
        })
        .catch(function() {
            btn.textContent = 'Fix';
            btn.disabled    = false;
            gtSsNotify('error', 'Network error.');
        });
};

/* ── Force Rescan ─────────────────────────────────────────────────────── */
window.gtSsRescan = function(nonce) {
    var btn = document.getElementById('gt-ss-rescan-btn');
    if (btn) { btn.textContent = 'Scanning…'; btn.disabled = true; }

    var fd = new FormData();
    fd.append('action', 'gtbogo_store_health_rescan');
    fd.append('nonce',  nonce);

    fetch(ajaxurl, { method:'POST', body:fd })
        .then(function(r) { return r.json(); })
        .then(function(resp) {
            if (resp.success) {
                gtSsNotify('success', 'Scan complete. Reloading…');
                setTimeout(function() { location.reload(); }, 1000);
            } else {
                if (btn) { btn.textContent = '↻ Force Rescan'; btn.disabled = false; }
                gtSsNotify('error', resp.data || 'Scan failed.');
            }
        })
        .catch(function() {
            if (btn) { btn.textContent = '↻ Force Rescan'; btn.disabled = false; }
            gtSsNotify('error', 'Network error during rescan.');
        });
};

/* ── Export Diagnostic ────────────────────────────────────────────────── */
window.gtSsExportDiagnostic = function(nonce) {
    window.open(
        ajaxurl + '?action=gtbogo_ss_export_diagnostic&nonce=' + encodeURIComponent(nonce),
        '_blank'
    );
};

/* ── Notification ─────────────────────────────────────────────────────── */
function gtSsNotify(type, msg) {
    var el  = document.getElementById('gt-ss-notification');
    if (!el) return;
    el.className = 'gt-notice gt-notice-' + (type === 'error' ? 'error' : 'success');
    el.textContent = msg;
    el.style.display = 'block';
    el.scrollIntoView({ behavior:'smooth', block:'center' });
    clearTimeout(gtSsNotify._t);
    gtSsNotify._t = setTimeout(function() { el.style.display = 'none'; }, 6000);
}

/* ── Score gauge animation ────────────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', function() {
    var arc = document.getElementById('gt-ss-gauge-arc');
    if (arc) {
        var target = <?php echo esc_js( (string) $health_score ); ?>;
        arc.setAttribute('stroke-dasharray', '0 314');
        setTimeout(function() {
            arc.setAttribute('stroke-dasharray', Math.round(target * 3.14159) + ' 314');
        }, 200);
    }

    /* Animate funnel bars */
    document.querySelectorAll('[style*="transition:width"]').forEach(function(el) {
        var w = el.style.width;
        el.style.width = '0%';
        setTimeout(function() { el.style.width = w; }, 300);
    });

    /* Auto-refresh every 60 seconds */
    setInterval(function() {
        var now = new Date();
        var ts  = document.getElementById('gt-ss-last-refresh');
        if (ts) ts.textContent = 'Auto-checked ' + now.getUTCHours() + ':' + String(now.getUTCMinutes()).padStart(2,'0') + ' UTC';
    }, 60000);
});

})();
</script>

<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
