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

$is_pro = function_exists('gt_bogo_has_pro') ? gt_bogo_has_pro() : false;

// Date range
$days  = isset($_GET['days']) ? (int)$_GET['days'] : 30;
$days  = in_array($days, [7,14,30,60,90], true) ? $days : 30;
$start = date('Y-m-d H:i:s', strtotime("-{$days} days"));
$prev  = date('Y-m-d H:i:s', strtotime("-" . ($days * 2) . " days"));

// Handle CSV export
if (isset($_GET['gtbogo_export_csv']) && check_admin_referer('gtbogo_export_csv')) {
    $atbl = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix.'gtbogo_analytics'));
    $rows = $atbl ? $wpdb->get_results($wpdb->prepare(
        "SELECT date_created, order_id, rule_id, rule_name, order_total, discount_amount FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s ORDER BY date_created DESC", $start), ARRAY_A) : [];
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="gt-bogo-analytics-' . date('Y-m-d') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Date', 'Order ID', 'Rule ID', 'Rule Name', 'Order Total', 'Discount Amount']);
    foreach ($rows as $row) fputcsv($out, $row);
    fclose($out);
    exit;
}

// Analytics data
$atbl = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix.'gtbogo_analytics'));
if ($atbl) {
    $stats = $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,
                COALESCE(MAX(order_total),0) AS max_order,
                COALESCE(MIN(order_total),0) AS min_order
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s", $start), ARRAY_A);
    $prev_stats = $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 AND date_created<%s", $prev, $start), ARRAY_A);
    $daily = $wpdb->get_results($wpdb->prepare(
        "SELECT DATE(date_created) AS d, COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue, COALESCE(SUM(discount_amount),0) AS discounts
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s GROUP BY DATE(date_created) ORDER BY d ASC", $start));
    $top_rules = $wpdb->get_results($wpdb->prepare(
        "SELECT rule_name, COUNT(DISTINCT order_id) AS fires, COALESCE(SUM(order_total),0) AS revenue, COALESCE(SUM(discount_amount),0) AS discount_cost
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s GROUP BY rule_id, rule_name ORDER BY fires DESC LIMIT 10", $start));
    $hourly = $wpdb->get_results($wpdb->prepare(
        "SELECT HOUR(date_created) AS hr, COUNT(DISTINCT order_id) AS orders
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s GROUP BY HOUR(date_created) ORDER BY hr ASC", $start));
} else {
    $stats      = ['orders'=>0,'revenue'=>0,'discounts'=>0,'aov'=>0,'max_order'=>0,'min_order'=>0];
    $prev_stats = ['orders'=>0,'revenue'=>0];
    $daily = []; $top_rules = []; $hourly = [];
}

// Trend calc
function gt_trend($now, $prev) {
    if (!$prev || $prev == 0) return ['pct'=>0,'dir'=>'flat'];
    $pct = round((($now - $prev) / $prev) * 100, 1);
    return ['pct'=>abs($pct),'dir'=>$pct>0?'up':($pct<0?'down':'flat')];
}
$rev_trend   = gt_trend($stats['revenue'], $prev_stats['revenue']);
$order_trend = gt_trend($stats['orders'], $prev_stats['orders']);

// Analytics settings save
$message = '';
if (isset($_POST['gtbogo_save_analytics_settings']) && check_admin_referer('gtbogo_analytics_settings')) {
    update_option('gtbogo_analytics_enabled',        isset($_POST['analytics_enabled']));
    update_option('gtbogo_analytics_track_guests',   isset($_POST['track_guests']));
    update_option('gtbogo_analytics_retention_days', intval($_POST['retention_days'] ?? 365));
    update_option('gtbogo_analytics_exclude_roles',  array_map('sanitize_text_field', (array)($_POST['exclude_roles'] ?? [])));
    $message = 'Analytics settings saved.';
}
$a_enabled   = get_option('gtbogo_analytics_enabled', true);
$a_guests    = get_option('gtbogo_analytics_track_guests', true);
$a_retention = get_option('gtbogo_analytics_retention_days', 365);
$a_excl      = get_option('gtbogo_analytics_exclude_roles', []);
$wp_roles    = wp_roles()->get_names();

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
  <div>
    <h1 class="gt-page-title">📈 Analytics</h1>
    <p class="gt-page-subtitle">Enterprise campaign performance — revenue influence, rule leaderboard, and time-of-day intelligence</p>
  </div>
  <div class="gt-page-actions" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
    <?php foreach ([7=>'7D',14=>'14D',30=>'30D',60=>'60D',90=>'90D'] as $d=>$l): ?>
    <a href="?page=gt-bogo-engine&tab=analytics&days=<?php echo $d; ?>" class="gt-btn <?php echo $days===$d?'gt-btn-primary':'gt-btn-ghost'; ?> gt-btn-sm"><?php echo esc_html($l); ?></a>
    <?php endforeach; ?>
    <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['gtbogo_export_csv'=>1,'days'=>$days,'page'=>'gt-bogo-engine','tab'=>'analytics'], admin_url('admin.php')), 'gtbogo_export_csv')); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">⬇ Export CSV</a>
  </div>
</div>
<?php if ($message): ?><div class="gt-notice gt-notice-success gt-animate-in">✓ <?php echo esc_html($message); ?></div><?php endif; ?>

<?php if (!$a_enabled && $is_pro): ?>
<div class="gt-notice gt-animate-in" style="background:rgba(245,158,11,0.08);border-color:rgba(245,158,11,0.3);color:#fcd34d">⚠ Analytics tracking is currently disabled. Enable it in the Settings section below.</div>
<?php endif; ?>

<!-- METRICS -->
<div class="gt-metrics" style="margin-bottom:20px">
  <?php
  $trend_icon = ['up'=>'↑','down'=>'↓','flat'=>'→'];
  $trend_col  = ['up'=>'#86efac','down'=>'#fca5a5','flat'=>'#94a3b8'];
  foreach ([
    ['💰','Revenue Influenced', '$'.number_format((float)$stats['revenue'],2), '#22c55e', $rev_trend,   'Total cart value of orders where a BOGO rule fired'],
    ['🛒','BOGO Orders',        number_format((int)$stats['orders']),           '#e10000', $order_trend,  'Unique orders with at least one BOGO discount applied'],
    ['🏷️','Discount Given',    '$'.number_format((float)$stats['discounts'],2),'#f59e0b', null,          'Sum of all BOGO discounts applied in this period'],
    ['💵','Avg Order Value',   '$'.number_format((float)$stats['aov'],2),       '#3b82f6', null,          'Mean order value for BOGO-influenced orders'],
    ['📦','Largest Order',     '$'.number_format((float)$stats['max_order'],2),'#8b5cf6', null,          'Highest single order value in this period'],
    ['📊','Discount Rate',     (($stats['revenue']>0)?round(($stats['discounts']/$stats['revenue'])*100,1):0).'%','#64748b',null,'Discounts as a % of influenced revenue — keep under 25%'],
  ] as $m): ?>
  <div class="gt-metric gt-animate-in" style="--gt-metric-c:<?php echo $m[3]; ?>;position:relative" title="<?php echo esc_attr($m[5]); ?>">
    <span class="gt-metric-icon"><?php echo $m[0]; ?></span>
    <div class="gt-metric-label"><?php echo esc_html($m[1]); ?></div>
    <div class="gt-metric-value"><?php echo esc_html($m[2]); ?></div>
    <?php if ($m[4]): ?>
    <div class="gt-metric-trend" style="color:<?php echo $trend_col[$m[4]['dir']]; ?>">
      <?php echo $trend_icon[$m[4]['dir']]; ?> <?php echo $m[4]['pct']; ?>% vs prior period
    </div>
    <?php else: ?>
    <div class="gt-metric-trend">Last <?php echo $days; ?> days</div>
    <?php endif; ?>
  </div>
  <?php endforeach; ?>
</div>

<!-- DAILY CHART -->
<?php if (!empty($daily)): ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
  <div class="gt-card-header">
    <h2 class="gt-card-title">📊 Daily Performance</h2>
    <div style="display:flex;gap:8px">
      <button onclick="gtChart('revenue')" id="btn-rev" class="gt-btn gt-btn-primary gt-btn-sm">Revenue</button>
      <button onclick="gtChart('orders')" id="btn-ord" class="gt-btn gt-btn-ghost gt-btn-sm">Orders</button>
      <button onclick="gtChart('discounts')" id="btn-disc" class="gt-btn gt-btn-ghost gt-btn-sm">Discounts</button>
    </div>
  </div>
  <canvas id="gt-main-chart" height="80"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
  <script>
  var gtDays    = <?php echo wp_json_encode(array_column((array)$daily,'d')); ?>;
  var gtRev     = <?php echo wp_json_encode(array_map('floatval', array_column((array)$daily,'revenue'))); ?>;
  var gtOrd     = <?php echo wp_json_encode(array_map('intval', array_column((array)$daily,'orders'))); ?>;
  var gtDisc    = <?php echo wp_json_encode(array_map('floatval', array_column((array)$daily,'discounts'))); ?>;
  var gtChartObj= null;
  function gtChart(type) {
    var sets = {
      revenue:  {data:gtRev,  label:'Revenue ($)',   color:'#e10000', prefix:'$'},
      orders:   {data:gtOrd,  label:'Orders',        color:'#3b82f6', prefix:''},
      discounts:{data:gtDisc, label:'Discounts ($)',  color:'#f59e0b', prefix:'$'},
    };
    var s = sets[type];
    document.querySelectorAll('#btn-rev,#btn-ord,#btn-disc').forEach(b=>b.className='gt-btn gt-btn-ghost gt-btn-sm');
    var map={'revenue':'btn-rev','orders':'btn-ord','discounts':'btn-disc'};
    document.getElementById(map[type]).className='gt-btn gt-btn-primary gt-btn-sm';
    if (gtChartObj) gtChartObj.destroy();
    var ctx = document.getElementById('gt-main-chart').getContext('2d');
    gtChartObj = new Chart(ctx, {
      type:'line',
      data:{labels:gtDays,datasets:[{label:s.label,data:s.data,borderColor:s.color,backgroundColor:s.color.replace(')',',0.08)').replace('rgb','rgba'),borderWidth:2,fill:true,tension:0.4,pointBackgroundColor:s.color,pointRadius:3,pointHoverRadius:5}]},
      options:{responsive:true,plugins:{legend:{display:false},tooltip:{callbacks:{label:function(c){return s.prefix+c.parsed.y.toFixed(s.prefix?2:0);}}}},scales:{x:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{color:'#64748b',font:{size:11}}},y:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{color:'#64748b',font:{size:11},callback:function(v){return s.prefix+v;}}}}}
    });
  }
  gtChart('revenue');
  </script>
</div>
<?php endif; ?>

<!-- RULE LEADERBOARD + HOURLY HEATMAP -->
<div style="display:grid;grid-template-columns:1.4fr 1fr;gap:20px;margin-bottom:20px">

<!-- Rule Leaderboard -->
<div class="gt-card gt-animate-in">
  <div class="gt-card-header"><h2 class="gt-card-title">🏆 Rule Performance Leaderboard</h2><span class="gt-text-soft gt-text-sm">Last <?php echo $days; ?> days</span></div>
  <?php if (!empty($top_rules)): ?>
  <div style="overflow-x:auto">
    <table class="gt-table">
      <thead><tr><th>#</th><th>Rule</th><th>Fires</th><th>Revenue</th><th>Discount</th><th>Efficiency</th></tr></thead>
      <tbody>
      <?php foreach ($top_rules as $i => $rule):
        $efficiency = $rule->revenue > 0 ? round(($rule->revenue - $rule->discount_cost) / $rule->revenue * 100, 1) : 0;
        $eff_color = $efficiency > 80 ? '#86efac' : ($efficiency > 60 ? '#fcd34d' : '#fca5a5');
      ?>
      <tr>
        <td style="font-weight:800;color:<?php echo $i===0?'#fcd34d':($i===1?'#94a3b8':($i===2?'#d97706':'var(--gt-subtle)')); ?>"><?php echo $i+1; ?></td>
        <td style="font-weight:600;color:var(--gt-white)"><?php echo esc_html($rule->rule_name ?: 'Unnamed Rule'); ?></td>
        <td style="font-family:'DM Mono',monospace;color:var(--gt-white)"><?php echo number_format($rule->fires); ?></td>
        <td style="font-family:'DM Mono',monospace;color:#86efac">$<?php echo number_format($rule->revenue, 2); ?></td>
        <td style="font-family:'DM Mono',monospace;color:#fca5a5">-$<?php echo number_format($rule->discount_cost, 2); ?></td>
        <td><span style="font-size:12px;font-weight:700;color:<?php echo $eff_color; ?>"><?php echo $efficiency; ?>%</span></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <div style="margin-top:12px;padding:10px 14px;background:rgba(59,130,246,0.05);border-radius:8px;font-size:12px;color:var(--gt-soft)">
    💡 <strong style="color:var(--gt-white)">Efficiency</strong> = (Revenue − Discount) ÷ Revenue. Above 80% is excellent. Below 60% means the discount is too aggressive for the volume it drives.
  </div>
  <?php else: ?>
  <div style="text-align:center;padding:40px 24px">
    <div style="font-size:40px;margin-bottom:12px">🏆</div>
    <p class="gt-text-soft gt-text-sm">No rule data yet. Rules will appear here once customers trigger BOGO discounts.</p>
  </div>
  <?php endif; ?>
</div>

<!-- Time-of-Day Heatmap -->
<div class="gt-card gt-animate-in">
  <div class="gt-card-header"><h2 class="gt-card-title">⏰ Peak Hours</h2><span class="gt-text-soft gt-text-sm">Orders by hour</span></div>
  <?php if (!empty($hourly)):
    $max_h = max(array_column((array)$hourly,'orders')) ?: 1;
    $hrs = array_column((array)$hourly,'hr');
    $ord = array_column((array)$hourly,'orders');
  ?>
  <div style="display:flex;flex-direction:column;gap:6px">
    <?php foreach ($hourly as $h):
      $pct = round(($h->orders / $max_h) * 100);
      $label = sprintf('%02d:00', $h->hr);
      $is_peak = $h->orders == $max_h;
    ?>
    <div style="display:flex;align-items:center;gap:10px">
      <span style="font-size:11px;font-family:'DM Mono',monospace;color:var(--gt-subtle);min-width:40px"><?php echo esc_html($label); ?></span>
      <div style="flex:1;height:18px;background:rgba(255,255,255,0.04);border-radius:4px;overflow:hidden">
        <div style="height:100%;width:<?php echo $pct; ?>%;background:<?php echo $is_peak?'#e10000':'rgba(225,0,0,0.4)'; ?>;border-radius:4px;transition:width 0.8s"></div>
      </div>
      <span style="font-size:11px;font-family:'DM Mono',monospace;color:<?php echo $is_peak?'#fff':'var(--gt-soft)'; ?>;min-width:24px;text-align:right"><?php echo $h->orders; ?></span>
      <?php if ($is_peak): ?><span style="font-size:10px;color:#e10000;font-weight:700">PEAK</span><?php endif; ?>
    </div>
    <?php endforeach; ?>
  </div>
  <div style="margin-top:16px;padding:10px 14px;background:rgba(255,255,255,0.03);border-radius:8px;font-size:12px;color:var(--gt-soft)">
    💡 Use peak hours to time your Campaign Scheduler — schedule flash deals to start 2 hours before your peak and expire at peak end for maximum urgency.
  </div>
  <?php else: ?>
  <div style="text-align:center;padding:40px 24px">
    <div style="font-size:40px;margin-bottom:12px">⏰</div>
    <p class="gt-text-soft gt-text-sm">Hourly data will populate once orders start coming in.</p>
  </div>
  <?php endif; ?>
</div>
</div>

<!-- ANALYTICS SETTINGS -->
<?php if ($is_pro): ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">⚙️ Analytics Configuration</h2></div>
  <form method="post" action="">
    <?php wp_nonce_field('gtbogo_analytics_settings'); ?>
    <div class="gt-setting-row">
      <div><div class="gt-setting-label">Enable Analytics Tracking</div><div class="gt-setting-desc">Record order data when BOGO rules fire. Disable only if you use a separate analytics platform and want to reduce DB writes.</div></div>
      <label class="gt-toggle"><input type="checkbox" name="analytics_enabled" value="1" <?php checked($a_enabled); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>
    <div class="gt-setting-row">
      <div><div class="gt-setting-label">Track Guest Orders</div><div class="gt-setting-desc">Include guest checkout orders in analytics. Disable to track logged-in customers only.</div></div>
      <label class="gt-toggle"><input type="checkbox" name="track_guests" value="1" <?php checked($a_guests); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>
    <div class="gt-setting-row">
      <div><div class="gt-setting-label">Data Retention (Days)</div><div class="gt-setting-desc">Analytics records older than this are automatically purged. Recommended: 365 days. Minimum: 30 days.</div></div>
      <input type="number" name="retention_days" class="gt-input" style="width:100px" value="<?php echo esc_attr($a_retention); ?>" min="30" max="1825">
    </div>
    <div class="gt-setting-row" style="border:none">
      <div><div class="gt-setting-label">Exclude User Roles from Tracking</div><div class="gt-setting-desc">Orders placed by these roles will not be recorded in analytics. Useful for excluding admin test orders.</div></div>
      <div style="display:flex;gap:10px;flex-wrap:wrap">
        <?php foreach ($wp_roles as $role_slug => $role_name): ?>
        <label style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--gt-soft);cursor:pointer">
          <input type="checkbox" name="exclude_roles[]" value="<?php echo esc_attr($role_slug); ?>" <?php checked(in_array($role_slug, (array)$a_excl)); ?> style="accent-color:var(--gt-red)">
          <?php echo esc_html($role_name); ?>
        </label>
        <?php endforeach; ?>
      </div>
    </div>
    <div style="margin-top:20px;text-align:right">
      <button type="submit" name="gtbogo_save_analytics_settings" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Analytics Settings</button>
    </div>
  </form>
</div>
<?php endif; ?>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="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">🧠 How to Read These Numbers</h2></div>
  <div class="gt-feature-grid gt-feature-grid--2col">
    <div>
      <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Revenue Influenced vs Incremental Revenue</div>
      <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Revenue Influenced tracks all orders where a rule fired — including orders that may have happened without the promotion. To isolate true incremental lift, compare BOGO order volume to your baseline period in the prior month using the prior-period trend arrows above.</div>
    </div>
    <div>
      <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">The Discount Rate Warning Zone</div>
      <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">A discount rate above 25% means you are giving away more than a quarter of every influenced sale. This is only sustainable if your gross margin exceeds 50%. If your margin is 35–40%, keep discount rate under 18% to remain profitable on promotion-influenced orders.</div>
    </div>
    <div>
      <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Rule Efficiency Score</div>
      <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">The leaderboard Efficiency % measures how much revenue survives after discounts. An 85% efficiency on a rule that fires 200 times beats a 95% efficiency rule that fires 10 times. Prioritise volume × efficiency, not efficiency alone.</div>
    </div>
    <div>
      <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Acting on Peak Hour Data</div>
      <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">If your peak is consistently between 7pm–9pm, schedule flash deals to start at 6pm and expire at 10pm. Customers who were already shopping in that window will see the deal as serendipitous rather than manufactured, which dramatically improves conversion rates compared to campaigns that run all day.</div>
    </div>
  </div>
</div>

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