<?php
/**
 * GT BOGO Engine — Dashboard (Enterprise)
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) return;

$is_pro  = function_exists('gt_bogo_has_pro') ? gt_bogo_has_pro() : false;
$version = defined('GT_BOGO_VERSION') ? GT_BOGO_VERSION : '3.11.0';

global $wpdb;

// ── Data ──────────────────────────────────────────────────────────────────
$rtbl      = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix.'gtbogo_rules'));
$atbl      = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix.'gtbogo_analytics'));
$ltbl      = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix.'gtbogo_logs'));

$rules_all    = $rtbl ? $wpdb->get_results("SELECT * FROM {$wpdb->prefix}gtbogo_rules ORDER BY priority DESC") : [];
$rules_active = array_filter($rules_all, fn($r) => $r->status === 'active');
$free_rule    = get_option('gtbogo_free_rule', []);

// Analytics — last 30 days
$analytics_30 = ['orders'=>0,'revenue'=>0,'discounts'=>0,'aov'=>0];
$analytics_7  = ['orders'=>0,'revenue'=>0,'discounts'=>0,'aov'=>0];
$sparkline    = [];
if ($atbl) {
    $a30 = $wpdb->get_row($wpdb->prepare(
        "SELECT COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue,
                COALESCE(SUM(discount_amount),0) AS discounts, COALESCE(AVG(order_total),0) AS aov
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created >= %s",
        date('Y-m-d H:i:s', strtotime('-30 days'))
    ), ARRAY_A);
    $a7 = $wpdb->get_row($wpdb->prepare(
        "SELECT COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created >= %s",
        date('Y-m-d H:i:s', strtotime('-7 days'))
    ), ARRAY_A);
    if ($a30) $analytics_30 = $a30;
    if ($a7)  $analytics_7  = $a7;

    // Sparkline — daily orders last 14 days
    for ($i=13; $i>=0; $i--) {
        $day   = date('Y-m-d', strtotime("-{$i} days"));
        $count = (int)$wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(DISTINCT order_id) FROM {$wpdb->prefix}gtbogo_analytics WHERE DATE(date_created)=%s", $day
        ));
        $sparkline[] = ['day' => date('M j', strtotime("-{$i} days")), 'orders' => $count];
    }
}

// Rule leaderboard — top 5 by orders
$leaderboard = [];
if ($atbl && $rtbl) {
    $leaderboard = $wpdb->get_results($wpdb->prepare(
        "SELECT rule_name, COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue, COALESCE(SUM(discount_amount),0) AS cost
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created >= %s GROUP BY rule_name ORDER BY orders DESC LIMIT 5",
        date('Y-m-d H:i:s', strtotime('-30 days'))
    ));
}

// Recent audit log entries
$recent_logs = [];
if ($ltbl) {
    $recent_logs = $wpdb->get_results(
        "SELECT * FROM {$wpdb->prefix}gtbogo_logs ORDER BY created_at DESC LIMIT 6"
    );
}

// Segments, Schedules
$segments  = get_option('gtbogo_segments', []);
$schedules = get_option('gtbogo_schedules', []);
$active_segs   = count(array_filter($segments,  fn($s) => !empty($s['enabled'])));
$active_scheds = count(array_filter($schedules, fn($s) => !empty($s['enabled'])));

// License
$license_key    = get_option('gtbogo_license_key', '');
$license_status = get_option('gtbogo_license_status', 'inactive');
$license_expiry = get_option('gtbogo_license_expiry', '');

// Upcoming schedules
$now_local = new DateTime('now', new DateTimeZone(wp_timezone_string()));
$upcoming_schedules = [];
foreach ($schedules as $sid => $sched) {
    if (!empty($sched['start_date'])) {
        $start = new DateTime($sched['start_date'].' '.($sched['start_time']??'00:00'), $now_local->getTimezone());
        if ($start > $now_local) $upcoming_schedules[] = ['name'=>$sched['name'],'start'=>$start->format('M j, g:ia')];
    }
}
usort($upcoming_schedules, fn($a,$b) => strtotime($a['start'])-strtotime($b['start']));

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

// Sparkline max
$spark_max = max(1, max(array_column($sparkline, 'orders')));
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">🏠 Dashboard</h1>
        <p class="gt-page-subtitle">GT BOGO Engine PRO — store performance at a glance</p>
    </div>
    <div style="display:flex;gap:8px;align-items:center">
        <span class="gt-badge <?php echo $is_pro?'gt-badge-active':'gt-badge-free'; ?>">
            <?php echo $is_pro?'● PRO Active':'Free'; ?>
        </span>
        <span class="gt-badge gt-badge-free">v<?php echo esc_html($version); ?></span>
    </div>
</div>

<!-- TOP METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
    <div class="gt-metric" style="--gt-metric-c:#e10000">
        <span class="gt-metric-icon">🛒</span>
        <div class="gt-metric-label">BOGO Orders (30d)</div>
        <div class="gt-metric-value"><?php echo number_format($analytics_30['orders']); ?></div>
        <div class="gt-metric-trend">Last 7d: <?php echo number_format($analytics_7['orders']); ?></div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#22c55e">
        <span class="gt-metric-icon">💰</span>
        <div class="gt-metric-label">Revenue Influenced (30d)</div>
        <div class="gt-metric-value" style="font-size:18px">$<?php echo number_format($analytics_30['revenue'],0); ?></div>
        <div class="gt-metric-trend">Last 7d: $<?php echo number_format($analytics_7['revenue'],0); ?></div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#f59e0b">
        <span class="gt-metric-icon">🏷️</span>
        <div class="gt-metric-label">Discount Given (30d)</div>
        <div class="gt-metric-value" style="font-size:18px">$<?php echo number_format($analytics_30['discounts'],0); ?></div>
        <div class="gt-metric-trend">Avg order value: $<?php echo number_format($analytics_30['aov'],2); ?></div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#8b5cf6">
        <span class="gt-metric-icon">📋</span>
        <div class="gt-metric-label">Active Rules</div>
        <div class="gt-metric-value"><?php echo count($rules_active) + (!empty($free_rule['enabled'])?1:0); ?></div>
        <div class="gt-metric-trend"><?php echo count($rules_all); ?> total configured</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#3b82f6">
        <span class="gt-metric-icon">👥</span>
        <div class="gt-metric-label">Active Segments</div>
        <div class="gt-metric-value"><?php echo $active_segs; ?></div>
        <div class="gt-metric-trend"><?php echo $active_scheds; ?> schedule<?php echo $active_scheds!==1?'s':''; ?> running</div>
    </div>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">

<!-- SPARKLINE CHART -->
<div class="gt-card gt-animate-in">
    <div class="gt-card-header"><h2 class="gt-card-title">📈 Orders — Last 14 Days</h2></div>
    <?php if (array_sum(array_column($sparkline,'orders'))>0): ?>
    <div style="display:flex;align-items:flex-end;gap:3px;height:80px;padding:0 4px">
        <?php foreach ($sparkline as $day): ?>
        <div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:4px;height:100%;justify-content:flex-end">
            <div title="<?php echo esc_attr($day['day'].': '.$day['orders'].' orders'); ?>"
                 style="width:100%;background:<?php echo $day['orders']>0?'var(--gt-red)':'rgba(255,255,255,0.04)'; ?>;border-radius:3px 3px 0 0;height:<?php echo $spark_max>0?round(($day['orders']/$spark_max)*72).'px':'4px'; ?>;transition:height 0.3s;min-height:3px"></div>
        </div>
        <?php endforeach; ?>
    </div>
    <div style="display:flex;justify-content:space-between;padding:6px 4px 0;font-size:10px;color:var(--gt-subtle)">
        <span><?php echo esc_html($sparkline[0]['day']); ?></span>
        <span><?php echo esc_html($sparkline[6]['day']); ?></span>
        <span><?php echo esc_html($sparkline[13]['day']); ?></span>
    </div>
    <?php else: ?>
    <div style="text-align:center;padding:32px 24px;color:var(--gt-subtle)">
        <div style="font-size:32px;margin-bottom:8px">📊</div>
        <div style="font-size:13px">No analytics data yet. Orders will appear here once BOGO rules start firing.</div>
    </div>
    <?php endif; ?>
</div>

<!-- RULE LEADERBOARD -->
<div class="gt-card gt-animate-in">
    <div class="gt-card-header"><h2 class="gt-card-title">🏆 Top Rules (30d)</h2><a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=analytics')); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">Full Analytics →</a></div>
    <?php if (!empty($leaderboard)): ?>
    <div style="display:flex;flex-direction:column;gap:8px">
        <?php foreach ($leaderboard as $i => $row):
            $pct = $leaderboard[0]->orders > 0 ? round(($row->orders/$leaderboard[0]->orders)*100) : 0;
        ?>
        <div>
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px">
                <div style="font-size:12px;color:<?php echo $i===0?'var(--gt-white)':'var(--gt-soft)'; ?>;font-weight:<?php echo $i===0?'700':'500'; ?>;max-width:220px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?php echo $i===0?'🥇 ':($i===1?'🥈 ':($i===2?'🥉 ':'')); ?><?php echo esc_html($row->rule_name); ?></div>
                <div style="font-size:11px;color:var(--gt-soft);font-family:'DM Mono',monospace"><?php echo number_format($row->orders); ?> orders · $<?php echo number_format($row->revenue,0); ?></div>
            </div>
            <div style="height:4px;border-radius:4px;background:rgba(255,255,255,0.04)"><div style="height:100%;width:<?php echo $pct; ?>%;background:var(--gt-red);border-radius:4px"></div></div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div style="text-align:center;padding:24px;color:var(--gt-subtle);font-size:13px">No rule performance data yet.</div>
    <?php endif; ?>
</div>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">

<!-- ACTIVE RULES PANEL -->
<div class="gt-card gt-animate-in">
    <div class="gt-card-header"><h2 class="gt-card-title">📋 Active Rules</h2><a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=pro-rules')); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">Manage →</a></div>
    <?php
    $dashboard_rules = [];
    if (!empty($free_rule['enabled'])) {
        $dashboard_rules[] = (object)['name'=>$free_rule['title']??'Free Core Rule','type'=>'free','buy_quantity'=>$free_rule['buy_quantity']??1,'get_quantity'=>$free_rule['get_quantity']??1,'discount_value'=>$free_rule['discount_value']??100,'status'=>'active'];
    }
    foreach ($rules_active as $r) $dashboard_rules[] = $r;

    if (!empty($dashboard_rules)):
    ?>
    <div style="display:flex;flex-direction:column;gap:6px">
        <?php foreach (array_slice($dashboard_rules,0,6) as $r): ?>
        <div style="display:flex;align-items:center;justify-content:space-between;padding:10px 14px;border-radius:8px;background:rgba(255,255,255,0.02);border:1px solid rgba(255,255,255,0.04)">
            <div>
                <div style="font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html($r->name); ?></div>
                <div style="font-size:11px;color:var(--gt-subtle)">Buy <?php echo $r->buy_quantity; ?> Get <?php echo $r->get_quantity; ?> — <?php echo $r->discount_value; ?>% off</div>
            </div>
            <span class="gt-badge gt-badge-active" style="font-size:10px">● Active</span>
        </div>
        <?php endforeach; ?>
        <?php if (count($dashboard_rules)>6): ?><div style="font-size:11px;color:var(--gt-subtle);text-align:center;padding:4px">+<?php echo count($dashboard_rules)-6; ?> more active rules</div><?php endif; ?>
    </div>
    <?php else: ?>
    <div style="text-align:center;padding:32px 24px">
        <div style="font-size:32px;margin-bottom:8px">📋</div>
        <div style="font-size:13px;color:var(--gt-subtle);margin-bottom:12px">No active rules.</div>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=free-rule')); ?>" class="gt-btn gt-btn-primary gt-btn-sm">Activate Free Rule</a>
    </div>
    <?php endif; ?>
</div>

<!-- STATUS PANEL -->
<div class="gt-card gt-animate-in">
    <div class="gt-card-header"><h2 class="gt-card-title">🔍 Status</h2><a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=system-status')); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">Full Status →</a></div>
    <div style="display:flex;flex-direction:column;gap:6px">
        <?php
        $checks = [
            ['PRO License',        $is_pro,                                          $is_pro?'Active':'Not activated'],
            ['Free Rule',          !empty($free_rule['enabled']),                    !empty($free_rule['enabled'])?'Active':'Inactive'],
            ['Analytics',          get_option('gtbogo_analytics_enabled', true),     get_option('gtbogo_analytics_enabled',true)?'Tracking':'Disabled'],
            ['Audit Log',          get_option('gtbogo_log_enabled', true),           get_option('gtbogo_log_enabled',true)?'Active':'Off'],
            ['Rule Cache',         get_option('gtbogo_cache_rules', true),           get_option('gtbogo_cache_rules',true)?'Enabled':'Off'],
            ['WP-Cron',            !defined('DISABLE_WP_CRON')||!DISABLE_WP_CRON,   !defined('DISABLE_WP_CRON')||!DISABLE_WP_CRON?'Running':'Disabled'],
            ['Debug Mode',         !get_option('gtbogo_debug_mode',false),           get_option('gtbogo_debug_mode',false)?'ON — disable in production':'Off'],
            ['Active Segments',    true,                                             $active_segs.' configured'],
            ['Active Schedules',   true,                                             $active_scheds.' running'],
        ];
        foreach ($checks as $c):
            $ok = $c[1];
        ?>
        <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 14px;border-radius:8px;background:rgba(255,255,255,0.015)">
            <span style="font-size:12px;color:var(--gt-soft)"><?php echo esc_html($c[0]); ?></span>
            <span style="font-size:11px;font-weight:700;color:<?php echo $ok?'#86efac':'#94a3b8'; ?>"><?php echo esc_html($c[2]); ?></span>
        </div>
        <?php endforeach; ?>
    </div>
    <?php if ($license_expiry && $is_pro):
        $days_left = (int)ceil((strtotime($license_expiry)-time())/86400);
        if ($days_left < 30 && $days_left > 0):
    ?>
    <div style="margin-top:12px;padding:10px 14px;background:rgba(245,158,11,0.08);border:1px solid rgba(245,158,11,0.2);border-radius:8px;font-size:12px;color:#fcd34d">
        ⚠ License expires in <?php echo $days_left; ?> days. <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=license')); ?>" style="color:#fcd34d;text-decoration:underline">Renew now →</a>
    </div>
    <?php endif; endif; ?>
</div>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">

<!-- UPCOMING SCHEDULES -->
<div class="gt-card gt-animate-in">
    <div class="gt-card-header"><h2 class="gt-card-title">⏰ Upcoming Schedules</h2><a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=scheduler')); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">Manage →</a></div>
    <?php if (!empty($upcoming_schedules)): ?>
    <div style="display:flex;flex-direction:column;gap:8px">
        <?php foreach (array_slice($upcoming_schedules,0,4) as $sch): ?>
        <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 14px;border-radius:8px;background:rgba(59,130,246,0.04);border:1px solid rgba(59,130,246,0.1)">
            <span style="font-size:13px;font-weight:600;color:var(--gt-white)"><?php echo esc_html($sch['name']); ?></span>
            <span style="font-size:11px;color:#93c5fd;font-family:'DM Mono',monospace"><?php echo esc_html($sch['start']); ?></span>
        </div>
        <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div style="text-align:center;padding:24px;color:var(--gt-subtle);font-size:13px">No upcoming schedules.</div>
    <?php endif; ?>
</div>

<!-- RECENT AUDIT LOG -->
<div class="gt-card gt-animate-in">
    <div class="gt-card-header"><h2 class="gt-card-title">📋 Recent Activity</h2><a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=audit-log')); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">Full Log →</a></div>
    <?php if (!empty($recent_logs)): ?>
    <div style="display:flex;flex-direction:column;gap:6px">
        <?php foreach ($recent_logs as $log):
            $colors = ['success'=>'#86efac','warn'=>'#fcd34d','error'=>'#fca5a5','info'=>'#93c5fd'];
            $icons  = ['success'=>'✓','warn'=>'⚠','error'=>'✕','info'=>'ℹ'];
            $lvl    = $log->level ?? 'info';
            $clr    = $colors[$lvl] ?? '#93c5fd';
            $icn    = $icons[$lvl] ?? 'ℹ';
        ?>
        <div style="display:flex;gap:10px;align-items:flex-start;padding:8px 14px;border-radius:8px;background:rgba(255,255,255,0.01)">
            <span style="font-size:11px;font-weight:700;color:<?php echo $clr; ?>;margin-top:1px"><?php echo $icn; ?></span>
            <div style="flex:1;min-width:0">
                <div style="font-size:12px;font-weight:600;color:var(--gt-white);white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?php echo esc_html($log->event ?? ''); ?></div>
                <div style="font-size:11px;color:var(--gt-subtle)"><?php echo esc_html(substr($log->details??'',0,60)); ?> · <?php echo esc_html(substr($log->created_at??'',0,16)); ?></div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div style="text-align:center;padding:24px;color:var(--gt-subtle);font-size:13px">No audit log entries yet.</div>
    <?php endif; ?>
</div>
</div>

<!-- QUICK ACTIONS -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">⚡ Quick Actions</h2></div>
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px">
        <?php
        $actions = [
            ['🎁','Free Rule',  admin_url('admin.php?page=gt-bogo-engine&tab=free-rule')],
            ['📋','PRO Rules',  admin_url('admin.php?page=gt-bogo-engine&tab=pro-rules')],
            ['📊','Analytics',  admin_url('admin.php?page=gt-bogo-engine&tab=analytics')],
            ['⏰','Scheduler',  admin_url('admin.php?page=gt-bogo-engine&tab=scheduler')],
            ['👥','Segments',   admin_url('admin.php?page=gt-bogo-engine&tab=segments')],
            ['🧪','A/B Tests',  admin_url('admin.php?page=gt-bogo-engine&tab=ab-testing')],
            ['📦','Export',     admin_url('admin.php?page=gt-bogo-engine&tab=import-export')],
            ['⚙️','Settings',   admin_url('admin.php?page=gt-bogo-engine&tab=settings')],
        ];
        foreach ($actions as $a):
        ?>
        <a href="<?php echo esc_url($a[2]); ?>" style="display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:20px 12px;border-radius:12px;border:1px solid var(--gt-border);background:rgba(255,255,255,0.02);text-decoration:none;transition:all 0.15s;color:var(--gt-white)" onmouseover="this.style.borderColor='var(--gt-red)';this.style.background='rgba(225,0,0,0.04)'" onmouseout="this.style.borderColor='var(--gt-border)';this.style.background='rgba(255,255,255,0.02)'">
            <span style="font-size:24px"><?php echo $a[0]; ?></span>
            <span style="font-size:12px;font-weight:700"><?php echo esc_html($a[1]); ?></span>
        </a>
        <?php endforeach; ?>
    </div>
</div>

<!-- BRAND FOOTER -->
<div style="text-align:center;padding:32px 24px;border-radius:16px;background:linear-gradient(135deg,rgba(225,0,0,0.06),rgba(7,12,28,0));border:1px solid rgba(225,0,0,0.1)">
    <div style="font-size:13px;font-weight:800;letter-spacing:2px;color:var(--gt-white);text-transform:uppercase;margin-bottom:4px">GRAPHIC T-SHIRTS</div>
    <div style="font-size:11px;color:var(--gt-subtle);margin-bottom:12px">GT BOGO Engine PRO v<?php echo esc_html($version); ?> — Enterprise BOGO Management for Premium Ecommerce</div>
    <a href="https://graphictshirts.shop" target="_blank" rel="noopener" style="font-size:11px;color:var(--gt-red);text-decoration:none">graphictshirts.shop →</a>
</div>

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