<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- View template, variables are locally scoped.
// ── Live Stats ──────────────────────────────────────────
global $wpdb;

    // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Admin-only stats queries, intentional direct DB access.
    $stat_posts    = (int) $wpdb->get_var("SELECT COUNT(pm.post_id) FROM $wpdb->postmeta pm JOIN $wpdb->posts p ON p.ID=pm.post_id WHERE pm.meta_key='_sbpai_post' AND pm.meta_value='1' AND p.post_type='post'");
    $stat_pages    = (int) $wpdb->get_var("SELECT COUNT(pm.post_id) FROM $wpdb->postmeta pm JOIN $wpdb->posts p ON p.ID=pm.post_id WHERE pm.meta_key='_sbpai_post' AND pm.meta_value='1' AND p.post_type='page'");
    $stat_products = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->postmeta WHERE meta_key='_sbpai_product' AND meta_value='1'");
    $stat_users    = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key='_sbpai_user' AND meta_value='1'");
$stat_orders = 0;
if ( class_exists('WooCommerce') ) {
    if ( class_exists('Automattic\WooCommerce\Utilities\OrderUtil') && Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
        $stat_orders = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}wc_orders_meta WHERE meta_key='_sbpai_order' AND meta_value='1'");
    } else {
        $stat_orders = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->postmeta WHERE meta_key='_sbpai_order' AND meta_value='1'");
    }
}
$stat_coupons  = (int) $wpdb->get_var("SELECT COUNT(pm.post_id) FROM $wpdb->postmeta pm JOIN $wpdb->posts p ON p.ID=pm.post_id WHERE pm.meta_key='_sbpai_post' AND pm.meta_value='1' AND p.post_type='shop_coupon'");
$stat_media    = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->postmeta WHERE meta_key='_sbpai_media' AND meta_value='1'");
    // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value

    $stat_total = $stat_posts + $stat_pages + $stat_products + $stat_users + $stat_orders + $stat_coupons + $stat_media;
    $wc_active  = class_exists('WooCommerce');

// Action scheduler pending count
$pending_jobs = 0;
if ( function_exists('as_get_scheduled_actions') ) {
    $pending_jobs = count( as_get_scheduled_actions( array('status' => 'pending', 'group' => 'sbpai_dummy_data', 'per_page' => 9999) ) );
}

$niche = get_option('sbpai_active_niche', 'General');
?>
<div class="sbpai-view-header">
    <h2>SandboxPress AI — Dashboard</h2>
    <p>Live analytics of all generated dummy data across your WordPress installation.</p>
</div>

<!-- ── Stat Cards ─────────────────────────────────────── -->
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(175px, 1fr)); gap: 16px; margin-bottom: 28px;">

    <?php
    $cards = [
        ['label'=>'Total Generated',  'value'=>number_format($stat_total),    'icon'=>'📦', 'color'=>'#6366f1'],
        ['label'=>'Posts / Articles', 'value'=>number_format($stat_posts),    'icon'=>'📝', 'color'=>'#10b981'],
        ['label'=>'WC Products',      'value'=>number_format($stat_products), 'icon'=>'🛍️', 'color'=>'#f59e0b'],
        ['label'=>'WC Orders',        'value'=>number_format($stat_orders),   'icon'=>'🧾', 'color'=>'#ef4444'],
        ['label'=>'Users Created',    'value'=>number_format($stat_users),    'icon'=>'👥', 'color'=>'#8b5cf6'],
        ['label'=>'Coupons',          'value'=>number_format($stat_coupons),  'icon'=>'🎟️', 'color'=>'#ec4899'],
        ['label'=>'Media Uploaded',   'value'=>number_format($stat_media),    'icon'=>'🖼️', 'color'=>'#14b8a6'],
        ['label'=>'Queue Pending',    'value'=>number_format($pending_jobs),  'icon'=>'⏳', 'color'=>'#f97316'],
    ];
    foreach ( $cards as $card ) :
    ?>
    <div style="background:#fff; border:1px solid #e5e7eb; border-radius:12px; padding:18px 16px; box-shadow:0 1px 4px rgba(0,0,0,.04);">
        <div style="font-size:26px; margin-bottom:6px;"><?php echo esc_html( $card['icon'] ); ?></div>
        <div style="font-size:28px; font-weight:700; color:<?php echo esc_attr( $card['color'] ); ?>; line-height:1.1;"><?php echo esc_html( $card['value'] ); ?></div>
        <div style="font-size:12px; color:#6b7280; margin-top:4px; font-weight:500;"><?php echo esc_html($card['label']); ?></div>
    </div>
    <?php endforeach; ?>

</div>

<!-- ── Quick Links ────────────────────────────────────── -->
<div style="display:grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap:16px; margin-bottom:28px;">

    <div class="sbpai-card" style="border-left: 4px solid #10b981;">
        <h3 style="margin-top:0;">📝 Content Generation</h3>
        <p style="color:#6b7280; font-size:13px;">Posts, Pages, and custom post types using Faker + optional AI titles.</p>
        <a href="?page=sbpai-content" class="sbpai-btn sbpai-btn-primary" style="background:#10b981; font-size:13px; padding:6px 14px;">Open →</a>
    </div>

    <div class="sbpai-card" style="border-left: 4px solid #f59e0b; <?php echo !$wc_active ? 'opacity:0.5;' : ''; ?>">
        <h3 style="margin-top:0;">🛍️ WooCommerce Generator</h3>
        <p style="color:#6b7280; font-size:13px;">
            <?php echo $wc_active ? 'Products, Orders, Coupons, and Reviews.' : '⚠️ WooCommerce not active.'; ?>
        </p>
        <?php if ( $wc_active ) : ?>
        <a href="?page=sbpai-woocommerce" class="sbpai-btn sbpai-btn-primary" style="background:#f59e0b; font-size:13px; padding:6px 14px;">Open →</a>
        <?php endif; ?>
    </div>

    <div class="sbpai-card" style="border-left: 4px solid #8b5cf6;">
        <h3 style="margin-top:0;">👥 User Generator</h3>
        <p style="color:#6b7280; font-size:13px;">Create users per-role with avatars, WC billing, and a shared default password.</p>
        <a href="?page=sbpai-users" class="sbpai-btn sbpai-btn-primary" style="background:#8b5cf6; font-size:13px; padding:6px 14px;">Open →</a>
    </div>

    <div class="sbpai-card" style="border-left: 4px solid #6366f1;">
        <h3 style="margin-top:0;">⚙️ Settings</h3>
        <p style="color:#6b7280; font-size:13px;">Current Niche: <strong><?php echo esc_html($niche); ?></strong>. Configure AI, delete all dummy data.</p>
        <a href="?page=sbpai-settings" class="sbpai-btn sbpai-btn-primary" style="background:#6366f1; font-size:13px; padding:6px 14px;">Open →</a>
    </div>

</div>

<!-- ── System Status ───────────────────────────────────── -->
<div class="sbpai-card">
    <h3 style="margin-top:0;">⚡ System Status</h3>
    <table style="width:100%; border-collapse:collapse; font-size:13px;">
        <?php
        $checks = [
            ['Action Scheduler',  function_exists('as_enqueue_async_action'),  'Required for background generation'],
            ['FakerPHP Library',  class_exists('Faker\Factory'),                'Required for realistic content'],
            ['WooCommerce',       class_exists('WooCommerce'),                  'Required for WC module'],
            ['ACF (Optional)',    class_exists('ACF'),                          'For auto-populating custom fields'],
            ['PHP ' . PHP_VERSION, version_compare(PHP_VERSION, '7.4', '>='),  'Minimum PHP 7.4 required'],
        ];
        foreach ( $checks as $check ) :
            $status_icon  = $check[1] ? '✅' : '❌';
            $status_color = $check[1] ? '#065f46' : '#7f1d1d';
            $bg           = $check[1] ? '#ecfdf5'  : '#fef2f2';
        ?>
        <tr style="border-bottom:1px solid #f3f4f6;">
            <td style="padding:8px 12px; font-weight:600;"><?php echo esc_html($check[0]); ?></td>
            <td style="padding:8px 12px;">
                <span style="background:<?php echo esc_attr( $bg ); ?>; color:<?php echo esc_attr( $status_color ); ?>; padding:2px 10px; border-radius:20px; font-size:12px; font-weight:600;">
                    <?php echo esc_html( $status_icon ) . ' ' . ( $check[1] ? esc_html__( 'Active', 'sandboxpress-ai' ) : esc_html__( 'Inactive', 'sandboxpress-ai' ) ); ?>
                </span>
            </td>
            <td style="padding:8px 12px; color:#9ca3af; font-size:12px;"><?php echo esc_html($check[2]); ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>
