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

$license_system = class_exists('GT_BOGO_License_System') ? GT_BOGO_License_System::instance() : null;
$license_active = get_option('gtbogo_license_status') === 'active';
$wc_active     = class_exists('WooCommerce');
$php_version   = PHP_VERSION;
$wp_version    = get_bloginfo('version');
$wc_version    = defined('WC_VERSION') ? WC_VERSION : 'Not installed';
$memory_limit  = ini_get('memory_limit');
$max_execution = ini_get('max_execution_time');
$upload_max    = ini_get('upload_max_filesize');
$server_sw     = isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'])) : 'Unknown';
global $wpdb;
$mysql_version   = $wpdb->db_version();
$settings        = get_option('gt_bogo_engine_settings', []);
$free_rule_on    = !empty($settings['enabled']);
$rules_table     = $wpdb->prefix . 'gtbogo_rules';
$licenses_table  = $wpdb->prefix . 'gtbogo_licenses';
$rules_exists    = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $rules_table))    === $rules_table;
$licenses_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $licenses_table)) === $licenses_table;
$php_ok    = version_compare($php_version, '7.4', '>=');
$wp_ok     = version_compare($wp_version,  '5.8', '>=');
$wc_ok     = $wc_active && version_compare($wc_version, '6.0', '>=');
$memory_ok = (int)$memory_limit >= 128;
$all_green = $php_ok && $wp_ok && $wc_ok && $memory_ok && $rules_exists && $licenses_exists;
$total_rules  = $rules_exists ? (int)$wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}gtbogo_rules") : 0;
$active_rules = $rules_exists ? (int)$wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}gtbogo_rules WHERE status='active'") : 0;
$active_plugins = (array)get_option('active_plugins', []);
$plugin_version = defined('GT_BOGO_VERSION') ? GT_BOGO_VERSION : GT_BOGO_VERSION;
require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">🖥️ System Status</h1>
        <p class="gt-page-subtitle">Environment health, plugin diagnostics, and server configuration at a glance</p>
    </div>
    <span class="gt-badge <?php echo esc_html( $all_green ) ? 'gt-badge-active' : 'gt-badge-warn'; ?>">
        <?php echo esc_html( $all_green ) ? '✓ All Systems Operational' : '⚠️ Issues Detected'; ?>
    </span>
</div>

<div class="gt-metrics gt-animate-in" style="margin-bottom:24px">
    <div class="gt-metric" style="--gt-metric-c:<?php echo esc_html( $license_active ) ? '#22c55e' : '#64748b'; ?>">
        <span class="gt-metric-icon"><?php echo esc_html( $license_active ) ? '🔑' : '🔒'; ?></span>
        <div class="gt-metric-label">License</div>
        <div class="gt-metric-value"><?php echo esc_html( $license_active ) ? 'PRO' : 'Free'; ?></div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:var(--gt-red)">
        <span class="gt-metric-icon">⚡</span>
        <div class="gt-metric-label">Active Rules</div>
        <div class="gt-metric-value"><?php echo esc_html( $active_rules ); ?>/15</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:<?php echo esc_html( $all_green ) ? '#22c55e' : '#f59e0b'; ?>">
        <span class="gt-metric-icon"><?php echo esc_html( $all_green ) ? '✅' : '⚠️'; ?></span>
        <div class="gt-metric-label">Requirements</div>
        <div class="gt-metric-value"><?php echo esc_html( $all_green ) ? 'Pass' : 'Issues'; ?></div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#3b82f6">
        <span class="gt-metric-icon">🐘</span>
        <div class="gt-metric-label">PHP</div>
        <div class="gt-metric-value"><?php echo esc_html($php_version); ?></div>
    </div>
</div>

<?php if (!$all_green): ?>
<div class="gt-notice gt-notice-warn gt-animate-in" style="margin-bottom:20px">
    ⚠️ One or more requirements are not met. Review the Requirements card below and contact your host if needed.
</div>
<?php endif; ?>

<div class="gt-feature-grid gt-feature-grid--2col gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card">
        <div class="gt-card-header"><h2 class="gt-card-title">🎯 Core Status</h2></div>
        <div style="display:flex;flex-direction:column">
        <?php
        $core_rows = [
            ['Plugin Version', $plugin_version, 'gt-badge-active'],
            ['License', $license_active ? 'PRO Active' : 'Free Version', $license_active ? 'gt-badge-active' : 'gt-badge-free'],
            ['Free Rule', $free_rule_on ? 'Enabled' : 'Disabled', $free_rule_on ? 'gt-badge-active' : 'gt-badge-free'],
            ['Rules Table', $rules_exists ? 'Installed' : 'Missing', $rules_exists ? 'gt-badge-active' : 'gt-badge-warn'],
            ['Licenses Table', $licenses_exists ? 'Installed' : 'Missing', $licenses_exists ? 'gt-badge-active' : 'gt-badge-warn'],
            ['Total Rules', $total_rules . ' created · ' . esc_html( $active_rules ) . ' active', 'gt-badge-active'],
        ];
        foreach ($core_rows as $i => $row): ?>
        <div style="display:flex;align-items:center;justify-content:space-between;padding:13px 0;<?php echo $i < count($core_rows)-1 ? 'border-bottom:1px solid rgba(255,255,255,0.05)' : ''; ?>">
            <span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html($row[0]); ?></span>
            <span class="gt-badge <?php echo esc_attr($row[2]); ?>"><?php echo esc_html($row[1]); ?></span>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
    <div class="gt-card">
        <div class="gt-card-header"><h2 class="gt-card-title">⚙️ Requirements</h2></div>
        <div style="display:flex;flex-direction:column">
        <?php
        $req_rows = [
            ['PHP 7.4+', $php_version . ($php_ok ? '' : ' — requires 7.4+'), $php_ok],
            ['WordPress 5.8+', $wp_version . ($wp_ok ? '' : ' — requires 5.8+'), $wp_ok],
            ['WooCommerce 6.0+', $wc_active ? ($wc_version . ($wc_ok ? '' : ' — update recommended')) : 'Not installed', $wc_ok],
            ['Memory ≥ 128M', $memory_limit . ($memory_ok ? '' : ' — 128M+ recommended'), $memory_ok],
        ];
        foreach ($req_rows as $i => $row): ?>
        <div style="display:flex;align-items:center;justify-content:space-between;padding:13px 0;<?php echo $i < count($req_rows)-1 ? 'border-bottom:1px solid rgba(255,255,255,0.05)' : ''; ?>">
            <span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html($row[0]); ?></span>
            <span class="gt-badge <?php echo esc_html( $row[2] ) ? 'gt-badge-active' : 'gt-badge-warn'; ?>"><?php echo esc_html( $row[2] ) ? '✓ ' : '⚠ '; echo esc_html($row[1]); ?></span>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>

<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🖥️ Server Information</h2>
        <span class="gt-text-soft" style="font-size:13px">Read-only environment details</span>
    </div>
    <div class="gt-feature-grid gt-feature-grid--2col" style="gap:12px">
    <?php foreach ([
        ['Server Software', $server_sw],
        ['MySQL Version',   $mysql_version],
        ['Max Execution',   $max_execution . 's'],
        ['Upload Max Size', $upload_max],
        ['WP Site URL',     get_site_url()],
        ['Admin Email',     get_option('admin_email')],
    ] as $row): ?>
    <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:14px 16px">
        <div style="font-size:13px;text-transform:uppercase;letter-spacing:0.6px;color:var(--gt-subtle);font-weight:600;margin-bottom:6px"><?php echo esc_html($row[0]); ?></div>
        <div style="font-size:13px;font-weight:600;color:var(--gt-white);word-break:break-all"><?php echo esc_html($row[1]); ?></div>
    </div>
    <?php endforeach; ?>
    </div>
</div>

<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🔌 Active Plugins</h2>
        <span class="gt-badge gt-badge-active"><?php echo count($active_plugins); ?> active</span>
    </div>
    <div style="display:flex;flex-wrap:wrap;gap:8px">
    <?php foreach ($active_plugins as $plugin):
        $slug  = dirname($plugin);
        $is_gt = strpos($plugin,'gt-bogo') !== false;
        $is_wc = strpos($plugin,'woocommerce') !== false;
    ?>
    <span style="font-size:13px;font-weight:600;padding:4px 12px;border-radius:50px;
        background:<?php echo esc_html( $is_gt )?'rgba(225,0,0,0.1)':($is_wc?'rgba(102,0,255,0.1)':'rgba(255,255,255,0.04)'); ?>;
        border:1px solid <?php echo esc_html( $is_gt )?'rgba(225,0,0,0.3)':($is_wc?'rgba(102,0,255,0.2)':'var(--gt-border)'); ?>;
        color:<?php echo esc_html( $is_gt )?'var(--gt-red)':($is_wc?'#a78bfa':'var(--gt-soft)'); ?>">
        <?php echo esc_html($slug === '.' ? $plugin : $slug); ?>
    </span>
    <?php endforeach; ?>
    </div>
</div>

<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
    <div class="gt-card-header">
        <h2 class="gt-card-title">💡 Production Readiness Checklist</h2>
        <span class="gt-text-soft" style="font-size:13px">Recommended configuration for live stores</span>
    </div>
    <div class="gt-feature-grid gt-feature-grid--2col" style="gap:12px">
    <?php foreach ([
        ['PHP 8.0+',               version_compare($php_version,'8.0','>='),  'Improves performance and future compatibility. Ask your host to upgrade.'],
        ['WooCommerce 8.0+',       version_compare($wc_version,'8.0','>='),   'Ensures latest cart hooks and HPOS support. Keep WooCommerce current.'],
        ['Memory Limit ≥ 256M',    (int)$memory_limit >= 256,                 'Prevents exhaustion during complex multi-rule cart evaluations.'],
        ['PRO License Active',     $license_active,                           'Unlocks unlimited rules, all 200 PRO packs, and every enterprise feature.'],
        ['Free Rule Configured',   $free_rule_on,                             'Your first BOGO deal is live. Go to Free Rule to configure it.'],
        ['Both DB Tables Present', $rules_exists && $licenses_exists,         'Required for rule storage and license validation. Reinstall if missing.'],
    ] as $item): ?>
    <div style="display:flex;align-items:flex-start;gap:12px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:14px">
        <span style="font-size:18px;flex-shrink:0;margin-top:1px"><?php echo esc_html( $item[1] ) ? '✅' : '⬜'; ?></span>
        <div>
            <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:3px"><?php echo esc_html($item[0]); ?></div>
            <div style="font-size:13px;color:var(--gt-subtle);line-height:1.4"><?php echo esc_html($item[2]); ?></div>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
</div>

<div class="gt-card gt-animate-in">
    <div class="gt-card-header"><h2 class="gt-card-title">🔧 Quick Actions</h2></div>
    <div style="display:flex;gap:12px;flex-wrap:wrap">
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=license')); ?>" class="gt-btn gt-btn-primary">🔑 Manage License</a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=free-rule')); ?>" class="gt-btn gt-btn-ghost">⚙️ Free Rule</a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=settings')); ?>" class="gt-btn gt-btn-ghost">⚙️ Settings</a>
        <a href="<?php echo esc_url(admin_url('plugins.php')); ?>" class="gt-btn gt-btn-ghost">🔌 Plugins</a>
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-ghost">🌐 GT BOGO Website ↗</a>
    </div>
</div>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
