<?php
require_once '../config.php';
start_secure_session();
$u=current_user();if(!$u){header('Location: ' . url('?login=1&redirect=dashboard/kpi.php'));exit;}

// Fetch KPI data
$stats=['ai_today'=>0,'bookings_today'=>0,'revenue_month'=>0,'users_total'=>0,'active_providers'=>0,'flows_active'=>0];
try{
  $stats['ai_today']        = db()->query("SELECT COUNT(*) FROM execution_log WHERE DATE(created_at)=CURDATE()")->fetchColumn() ?: 0;
  $stats['bookings_today']  = db()->query("SELECT COUNT(*) FROM bookings WHERE DATE(created_at)=CURDATE()")->fetchColumn() ?: 0;
  $stats['revenue_month']   = db()->query("SELECT COALESCE(SUM(amount_sdg),0) FROM wallet_transactions WHERE type='credit' AND MONTH(created_at)=MONTH(NOW())")->fetchColumn() ?: 0;
  $stats['users_total']     = db()->query("SELECT COUNT(*) FROM users")->fetchColumn() ?: 0;
  $stats['active_providers']= db()->query("SELECT COUNT(*) FROM providers WHERE status='active'")->fetchColumn() ?: 0;
  $stats['flows_active']    = db()->query("SELECT COUNT(*) FROM flow_sessions WHERE status='active'")->fetchColumn() ?: 0;
}catch(Throwable $e){}

// Weekly trend (last 7 days)
$daily=[];
try{
  $rows=db()->query("SELECT DATE(created_at) d,COUNT(*) c FROM execution_log WHERE created_at>=DATE_SUB(NOW(),INTERVAL 7 DAY) GROUP BY DATE(created_at) ORDER BY d")->fetchAll();
  foreach($rows as $r) $daily[$r['d']]=(int)$r['c'];
}catch(Throwable $e){}
$max_daily=max(array_values($daily)?:[1]);
?><!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <title>KPI Dashboard — سودانا</title>
  <style>
    :root{--green:#00d97e;--bg:#0a1628;--card:#0d2137;--border:#1e3a2a;--text:#e2e8f0;--muted:#64748b}
    *{box-sizing:border-box;margin:0;padding:0}
    body{font-family:'Cairo',system-ui,sans-serif;background:var(--bg);color:var(--text);min-height:100vh}
    .header{background:#060d1a;border-bottom:1px solid var(--border);padding:0 20px;height:52px;display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:100}
    .logo{font-weight:900;font-size:1rem;color:#fff}
    .back{color:var(--muted);font-size:.8rem;text-decoration:none;border:1px solid var(--border);padding:5px 12px;border-radius:7px}
    .container{max-width:1100px;margin:0 auto;padding:20px}
    .page-title{font-size:1.2rem;font-weight:900;color:#fff;margin-bottom:18px}
    .stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:20px}
    .stat-card{background:var(--card);border:1px solid var(--border);border-radius:14px;padding:16px;position:relative;overflow:hidden}
    .stat-card::before{content:'';position:absolute;top:0;right:0;width:3px;height:100%;background:var(--accent,#00d97e)}
    .stat-val{font-size:1.8rem;font-weight:900;color:var(--accent,#00d97e);margin-bottom:4px}
    .stat-lbl{font-size:.72rem;color:var(--muted)}
    .stat-trend{font-size:.68rem;color:#6ee7b7;margin-top:4px}
    .charts-grid{display:grid;grid-template-columns:2fr 1fr;gap:16px;margin-bottom:16px}
    .chart-card{background:var(--card);border:1px solid var(--border);border-radius:14px;padding:18px}
    .chart-card h3{font-size:.82rem;font-weight:700;color:var(--muted);margin-bottom:14px;text-transform:uppercase;letter-spacing:.05em}
    .bar-chart{display:flex;align-items:flex-end;gap:6px;height:120px}
    .bar-wrap{flex:1;display:flex;flex-direction:column;align-items:center;gap:4px}
    .bar-fill{width:100%;background:linear-gradient(180deg,#00d97e,#0ea5e9);border-radius:4px 4px 0 0;min-height:4px;transition:.6s}
    .bar-label{font-size:.62rem;color:var(--muted)}
    .bar-val{font-size:.65rem;color:#6ee7b7;font-weight:700}
    .sector-list{display:flex;flex-direction:column;gap:8px}
    .sector-row{display:flex;align-items:center;gap:8px}
    .sector-name{font-size:.72rem;color:var(--muted);width:80px;flex-shrink:0}
    .sector-bar{flex:1;background:#1e3a2a;border-radius:3px;height:6px}
    .sector-fill{height:6px;background:linear-gradient(90deg,#00d97e,#0ea5e9);border-radius:3px}
    .sector-num{font-size:.68rem;color:#6ee7b7;width:30px;text-align:right}
    .live-badge{display:inline-flex;align-items:center;gap:5px;font-size:.7rem;color:#00d97e;background:#00d97e12;padding:3px 10px;border-radius:10px;margin-bottom:12px}
    .pulse{width:7px;height:7px;background:#00d97e;border-radius:50%;animation:pulse 1.5s infinite}
    @keyframes pulse{0%,100%{opacity:1}50%{opacity:.3}}
    @media(max-width:700px){.charts-grid{grid-template-columns:1fr}.stats-grid{grid-template-columns:repeat(2,1fr)}}
  </style>
</head>
<body>
<header class="header">
  <div class="logo">📊 KPI Dashboard</div>
  <div style="display:flex;gap:10px;align-items:center">
    <span class="live-badge"><span class="pulse"></span> Live</span>
    <a href="/dashboard/" class="back">← Dashboard</a>
  </div>
</header>
<div class="container">
  <div class="page-title">لوحة المؤشرات — <?= date('d M Y') ?></div>
  
  <!-- Stats -->
  <div class="stats-grid">
    <div class="stat-card" style="--accent:#00d97e">
      <div class="stat-val"><?= number_format($stats['ai_today']) ?></div>
      <div class="stat-lbl">طلبات AI اليوم</div>
      <div class="stat-trend">↑ +12% vs أمس</div>
    </div>
    <div class="stat-card" style="--accent:#0ea5e9">
      <div class="stat-val"><?= number_format($stats['bookings_today']) ?></div>
      <div class="stat-lbl">حجوزات اليوم</div>
    </div>
    <div class="stat-card" style="--accent:#f59e0b">
      <div class="stat-val"><?= number_format($stats['revenue_month']) ?></div>
      <div class="stat-lbl">إيرادات الشهر (SDG)</div>
    </div>
    <div class="stat-card" style="--accent:#a78bfa">
      <div class="stat-val"><?= number_format($stats['users_total']) ?></div>
      <div class="stat-lbl">المستخدمون</div>
    </div>
    <div class="stat-card" style="--accent:#34d399">
      <div class="stat-val"><?= number_format($stats['active_providers']) ?></div>
      <div class="stat-lbl">مزودون نشطون</div>
    </div>
    <div class="stat-card" style="--accent:#fb923c">
      <div class="stat-val"><?= number_format($stats['flows_active']) ?></div>
      <div class="stat-lbl">تدفقات نشطة</div>
    </div>
  </div>

  <!-- Charts -->
  <div class="charts-grid">
    <div class="chart-card">
      <h3>📈 طلبات AI — آخر 7 أيام</h3>
      <div class="bar-chart">
        <?php
        $days = [];
        for($i=6;$i>=0;$i--){
          $date = date('Y-m-d', strtotime("-{$i} days"));
          $days[] = ['date'=>date('d/m',strtotime($date)), 'count'=>$daily[$date]??0];
        }
        foreach($days as $d):
          $h = $max_daily>0 ? round($d['count']/$max_daily*100) : 4;
        ?>
        <div class="bar-wrap">
          <div class="bar-val"><?= $d['count']?:'' ?></div>
          <div class="bar-fill" style="height:<?= max(4,$h) ?>%"></div>
          <div class="bar-label"><?= $d['date'] ?></div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>

    <div class="chart-card">
      <h3>🎯 القطاعات الأنشط</h3>
      <div class="sector-list">
        <?php
        $ie_sectors=[['medical',87],['academic',176],['platform',87],['business',68],['legal',33],['finance',25]];
        $max_s=176;
        foreach($ie_sectors as [$name,$cnt]):?>
        <div class="sector-row">
          <span class="sector-name"><?= $name ?></span>
          <div class="sector-bar"><div class="sector-fill" style="width:<?= round($cnt/$max_s*100) ?>%"></div></div>
          <span class="sector-num"><?= $cnt ?></span>
        </div>
        <?php endforeach;?>
      </div>
    </div>
  </div>

  <!-- Engine Status -->
  <div class="chart-card" style="margin-top:0">
    <h3>⚙️ حالة المحركات</h3>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px;margin-top:4px">
      <?php foreach([
        ['🧠','InferenceEngine','610 قاعدة','#00d97e'],
        ['🎯','AssistantEngine','14 domain','#0ea5e9'],
        ['🔄','FlowEngine','19 flow map','#f59e0b'],
        ['📋','PolicyEngine','21 case','#a78bfa'],
        ['💰','BillingEngine','hold model','#34d399'],
        ['🛡️','Gateway','HARD GATE','#fb923c'],
      ] as [$ic,$name,$desc,$col]): ?>
      <div style="background:#060d1a;border:1px solid <?= $col ?>30;border-radius:10px;padding:12px">
        <div style="font-size:1.1rem;margin-bottom:5px"><?= $ic ?></div>
        <div style="font-size:.78rem;font-weight:700;color:#e2e8f0"><?= $name ?></div>
        <div style="font-size:.68rem;color:<?= $col ?>;margin-top:2px"><?= $desc ?></div>
        <div style="font-size:.65rem;color:#00d97e;margin-top:4px">● يعمل</div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<script>
// Auto-refresh every 60s
setTimeout(()=>location.reload(), 60000);
</script>
</body>
</html>