<?php
/**
 * سودانا Sudanna Agent Console
 */
require_once '../config.php';
if (session_status() === PHP_SESSION_NONE) {
    // session path from SITE_URL via start_secure_session()
    session_start();
}
$u = current_user();
if (!$u) { header('Location: ' . url('?login=1&redirect=dashboard/')); exit; }
$userId   = (int)$u['id'];
$plan     = $u['plan_key'] ?? 'free';
$planName = match($plan) { 'pro'=>'Pro', 'plus'=>'Plus', default=>'Free' };

// Stats
$keys_count = 0; $agents_count = 0; $calls_today = 0; $calls_week = 0;
try { $st=db()->prepare("SELECT COUNT(*) FROM ai_api_keys WHERE user_id=? AND status='active'"); $st->execute([$userId]); $keys_count=(int)$st->fetchColumn(); } catch(Throwable $e){}
try { $st=db()->prepare("SELECT COUNT(*) FROM ai_agents WHERE user_id=? AND status='active'"); $st->execute([$userId]); $agents_count=(int)$st->fetchColumn(); } catch(Throwable $e){}
try { $st=db()->prepare("SELECT COUNT(*) FROM ai_usage WHERE user_id=? AND DATE(created_at)=CURDATE()"); $st->execute([$userId]); $calls_today=(int)$st->fetchColumn(); } catch(Throwable $e){}
try { $st=db()->prepare("SELECT COUNT(*) FROM ai_usage WHERE user_id=? AND created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)"); $st->execute([$userId]); $calls_week=(int)$st->fetchColumn(); } catch(Throwable $e){}
$limit_day = match($plan) { 'pro'=>5000, 'plus'=>500, default=>50 };
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>سودانا Sudanna Agent Console</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:Cairo,Arial,sans-serif;background:#060D09;color:#F5F2EC;min-height:100vh}
.nav{background:#0B1A12;border-bottom:1px solid rgba(245,242,236,.08);padding:14px 24px;display:flex;justify-content:space-between;align-items:center;position:sticky;top:0;z-index:100}
.nav-logo{font-weight:800;font-size:1.1rem;color:#2DC48F}
.nav-links{display:flex;gap:6px;align-items:center}
.nav-links a{color:rgba(245,242,236,.6);text-decoration:none;padding:6px 12px;border-radius:7px;font-size:.82rem;transition:.2s}
.nav-links a:hover,.nav-links a.active{background:rgba(29,158,117,.15);color:#2DC48F}
.nav-user{display:flex;align-items:center;gap:10px;font-size:.82rem;color:rgba(245,242,236,.5)}
.plan-badge{background:rgba(29,158,117,.2);color:#2DC48F;padding:2px 10px;border-radius:20px;font-size:.72rem;font-weight:700}
.main{max-width:1200px;margin:0 auto;padding:32px 24px}
.page-title{font-size:1.5rem;font-weight:800;margin-bottom:8px}
.page-sub{color:rgba(245,242,236,.5);margin-bottom:32px;font-size:.9rem}
.grid-4{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:32px}
.stat-card{background:#0B1A12;border:1px solid rgba(245,242,236,.08);border-radius:12px;padding:20px}
.stat-card .val{font-size:2rem;font-weight:800;color:#2DC48F}
.stat-card .lbl{font-size:.78rem;color:rgba(245,242,236,.5);margin-top:4px}
.stat-card .sub{font-size:.72rem;color:rgba(245,242,236,.35);margin-top:2px}
.progress-bar{height:4px;background:rgba(245,242,236,.08);border-radius:2px;margin-top:8px}
.progress-fill{height:100%;background:#2DC48F;border-radius:2px;transition:.3s}
.cards-row{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-bottom:32px}
.card{background:#0B1A12;border:1px solid rgba(245,242,236,.08);border-radius:14px;padding:24px}
.card-title{font-weight:700;margin-bottom:16px;font-size:.95rem;display:flex;justify-content:space-between;align-items:center}
.btn{padding:8px 18px;border-radius:8px;border:none;cursor:pointer;font-size:.82rem;font-weight:700;font-family:Cairo,Arial;transition:.2s;text-decoration:none;display:inline-flex;align-items:center;gap:6px}
.btn-green{background:#1D9E75;color:#fff}.btn-green:hover{background:#2DC48F}
.btn-ghost{background:rgba(245,242,236,.06);color:rgba(245,242,236,.7);border:1px solid rgba(245,242,236,.1)}
.btn-ghost:hover{background:rgba(245,242,236,.1)}
.btn-danger{background:rgba(220,38,38,.2);color:#f87171;border:1px solid rgba(220,38,38,.2)}
.list-item{padding:10px 0;border-bottom:1px solid rgba(245,242,236,.05);display:flex;justify-content:space-between;align-items:center;font-size:.82rem}
.list-item:last-child{border-bottom:none}
.code-block{background:rgba(245,242,236,.04);border:1px solid rgba(245,242,236,.08);border-radius:8px;padding:12px 14px;font-family:'Courier New',monospace;font-size:.78rem;color:#2DC48F;word-break:break-all;position:relative}
.badge{padding:2px 8px;border-radius:10px;font-size:.7rem;font-weight:700}
.b-active{background:rgba(29,158,117,.2);color:#2DC48F}
.b-paused{background:rgba(245,242,236,.08);color:rgba(245,242,236,.5)}
.upgrade-banner{background:linear-gradient(135deg,rgba(193,125,42,.15),rgba(224,154,66,.05));border:1px solid rgba(193,125,42,.2);border-radius:12px;padding:16px 20px;margin-bottom:24px;display:flex;justify-content:space-between;align-items:center}
.empty{text-align:center;padding:32px;color:rgba(245,242,236,.35);font-size:.85rem}
@media(max-width:768px){.grid-4{grid-template-columns:1fr 1fr}.cards-row{grid-template-columns:1fr}}
</style>
</head>
<body>
<?php include __DIR__ . '/partials/nav.php'; ?>
<nav class="nav">
  <span class="nav-logo">⚡ Sudanna Agent</span>
  <div class="nav-links">
    <a href="index.php" class="active">Dashboard</a>
    <a href="api.php">API Keys</a>
    <a href="agents.php">Agents</a>
    <a href="logs.php">Logs</a>
    <a href="billing.php">Billing</a>
    <a href="/" class="btn-ghost btn" style="margin-right:8px">← Platform</a>
  </div>
  <div class="nav-user">
    <span><?= htmlspecialchars($u['name']) ?></span>
    <span class="plan-badge"><?= $planName ?></span>
  </div>
</nav>

<div class="main">
  <div class="page-title">Sudanna Agent Console</div>
  <div class="page-sub">مرحباً <?= htmlspecialchars($u['name']) ?> — قم ببناء وتشغيل Sudanna Agents باستخدام Sudanna Engine</div>

  <?php if ($plan === 'free'): ?>
  <div class="upgrade-banner">
    <div>
      <strong>أنت على الخطة المجانية</strong>
      <div style="font-size:.8rem;color:rgba(245,242,236,.5);margin-top:3px">50 طلب/يوم · 2 Agents فقط. ارقَ للـ Plus للحصول على 500 طلب/يوم و10 Agents.</div>
    </div>
    <a href="billing.php" class="btn btn-green">Upgrade →</a>
  </div>
  <?php endif; ?>

  <div class="grid-4">
    <div class="stat-card">
      <div class="val"><?= $calls_today ?></div>
      <div class="lbl">API Calls Today</div>
      <div class="sub"><?= $limit_day - $calls_today ?> remaining</div>
      <div class="progress-bar"><div class="progress-fill" style="width:<?= min(100, round($calls_today/$limit_day*100)) ?>%"></div></div>
    </div>
    <div class="stat-card">
      <div class="val"><?= $calls_week ?></div>
      <div class="lbl">Calls This Week</div>
      <div class="sub">Last 7 days</div>
    </div>
    <div class="stat-card">
      <div class="val"><?= $agents_count ?></div>
      <div class="lbl">Active Agents</div>
      <div class="sub">Max <?= match($plan){'pro'=>50,'plus'=>10,default=>2} ?> on <?= $planName ?></div>
    </div>
    <div class="stat-card">
      <div class="val"><?= $keys_count ?></div>
      <div class="lbl">API Keys</div>
      <div class="sub">Max 5 keys</div>
    </div>
  </div>

  <div class="cards-row">
    <div class="card">
      <div class="card-title">
        🔑 Agent API Keys
        <a href="api.php" class="btn btn-green btn-sm">إدارة المفاتيح</a>
      </div>
      <?php
      $keys = [];
      try { $st=db()->prepare("SELECT key_prefix,label,calls_total,last_used_at FROM ai_api_keys WHERE user_id=? AND status='active' ORDER BY created_at DESC LIMIT 3"); $st->execute([$userId]); $keys=$st->fetchAll(); } catch(Throwable $e){}
      ?>
      <?php if($keys): foreach($keys as $k): ?>
      <div class="list-item">
        <div>
          <div style="font-family:monospace;color:#2DC48F"><?= htmlspecialchars($k['key_prefix']) ?>...</div>
          <div style="color:rgba(245,242,236,.4);font-size:.72rem"><?= htmlspecialchars($k['label']) ?> · <?= $k['calls_total'] ?> calls</div>
        </div>
        <span class="badge b-active">Active</span>
      </div>
      <?php endforeach; else: ?>
      <div class="empty">لا توجد مفاتيح — <a href="api.php" style="color:#2DC48F">أنشئ مفتاحاً الآن</a></div>
      <?php endif; ?>
    </div>

    <div class="card">
      <div class="card-title">
        🤖 Active Agents
        <a href="agents.php" class="btn btn-green btn-sm">إدارة الـ Agents</a>
      </div>
      <?php
      $agents = [];
      try { $st=db()->prepare("SELECT id,name,service,runs_total,last_run_at FROM ai_agents WHERE user_id=? AND status='active' ORDER BY runs_total DESC LIMIT 3"); $st->execute([$userId]); $agents=$st->fetchAll(); } catch(Throwable $e){}
      ?>
      <?php if($agents): foreach($agents as $ag): ?>
      <div class="list-item">
        <div>
          <div style="font-weight:600"><?= htmlspecialchars($ag['name']) ?></div>
          <div style="color:rgba(245,242,236,.4);font-size:.72rem"><?= $ag['service'] ?> · <?= $ag['runs_total'] ?> runs</div>
        </div>
        <span class="badge b-active">Active</span>
      </div>
      <?php endforeach; else: ?>
      <div class="empty">لا توجد Agents — <a href="agents.php" style="color:#2DC48F">أنشئ Agent الآن</a></div>
      <?php endif; ?>
    </div>
  </div>

  <div class="card" style="margin-bottom:24px">
    <div class="card-title">⚡ Quick Start</div>
    <div style="font-size:.82rem;color:rgba(245,242,236,.6);margin-bottom:12px">استخدم الـ API مباشرة:</div>
    <div class="code-block">curl -X POST https://sudanna.ai/api/engine/chat.php \<br>
     -H "Authorization: Bearer sdk_YOUR_API_KEY" \<br>
     -H "Content-Type: application/json" \<br>
     -d '{"message": "عندي ألم في الصدر"}'</div>
    <div style="margin-top:12px;font-size:.78rem;color:rgba(245,242,236,.4)">
      الرد: <code style="color:#2DC48F">{"success":true,"answer":"...","service":"medical","source":"ie"}</code>
    </div>
  </div>
</div>
</body>
</html>
