<?php
require_once '../config.php';
start_secure_session();
$u = current_user(); if (!$u) { header('Location: ' . url('?login=1&redirect=dashboard/api.php')); exit; }
$userId = (int)$u['id'];
$newKey = null; $error = null;
// FIX 3: CSRF protection
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'generate') {
    if (($_POST['csrf'] ?? '') !== $_SESSION['csrf']) { http_response_code(403); exit('Invalid CSRF'); }
    require_once '../engine/AIEngine.php';
    $label = mb_substr(trim($_POST['label'] ?? 'Default Key'), 0, 100);
    $raw   = AIEngine::generateKey($userId, $label);
    if ($raw) $newKey = $raw;
    else $error = 'وصلت للحد الأقصى (5 مفاتيح). احذف مفتاحاً قبل إنشاء جديد.';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'revoke') {
    if (($_POST['csrf'] ?? '') !== $_SESSION['csrf']) { http_response_code(403); exit('Invalid CSRF'); }
    $id = (int)($_POST['key_id'] ?? 0);
    try { db()->prepare("UPDATE ai_api_keys SET status='revoked' WHERE id=? AND user_id=?")->execute([$id, $userId]); } catch(Throwable $e){}
}

$keys = [];
try { $st=db()->prepare("SELECT id,key_prefix,label,status,calls_today,calls_total,last_used_at,created_at FROM ai_api_keys WHERE user_id=? ORDER BY created_at DESC"); $st->execute([$userId]); $keys=$st->fetchAll(); } catch(Throwable $e){}
?>
<!DOCTYPE html><html lang="ar" dir="rtl"><head><meta charset="UTF-8"><title>Agent API Keys — سودانا</title>
<?php include __DIR__ . '/partials/nav.php'; ?>
<div class="main">
  <div class="page-title">🔑 Agent API Keys</div>
  <div class="page-sub">مفاتيحك للوصول إلى Sudanna Agent API</div>

  <?php if ($newKey): ?>
  <div style="background:rgba(29,158,117,.1);border:1px solid rgba(29,158,117,.3);border-radius:10px;padding:16px 20px;margin-bottom:24px">
    <strong style="color:#2DC48F">✅ تم إنشاء المفتاح — احفظه الآن، لن يُعرض مرة أخرى</strong>
    <div class="code-block" style="margin-top:10px;font-size:.9rem"><?= htmlspecialchars($newKey) ?></div>
  </div>
  <?php endif; ?>
  <?php if ($error): ?>
  <div style="background:rgba(220,38,38,.1);border:1px solid rgba(220,38,38,.2);border-radius:10px;padding:12px 16px;margin-bottom:24px;color:#f87171"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <div class="card" style="margin-bottom:24px">
    <div class="card-title">إنشاء مفتاح جديد</div>
    <form method="POST" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap">
      <div style="flex:1;min-width:200px"><label style="display:block;font-size:.8rem;margin-bottom:6px;color:rgba(245,242,236,.6)">اسم المفتاح</label>
      <input type="text" name="label" value="Production Key" style="width:100%;padding:9px 12px;border-radius:8px;background:rgba(245,242,236,.06);border:1px solid rgba(245,242,236,.1);color:#F5F2EC;font-family:Cairo,Arial;font-size:.85rem"></div>
      <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf) ?>">
      <input type="hidden" name="action" value="generate">
      <button type="submit" class="btn btn-green">+ إنشاء مفتاح</button>
    </form>
  </div>

  <div class="card">
    <div class="card-title">مفاتيحك (<?= count($keys) ?>/5)</div>
    <?php if ($keys): ?>
    <table style="width:100%;border-collapse:collapse;font-size:.82rem">
    <tr style="border-bottom:1px solid rgba(245,242,236,.08)"><th style="text-align:right;padding:8px 4px;color:rgba(245,242,236,.5);font-weight:600">المفتاح</th><th style="text-align:right;padding:8px 4px;color:rgba(245,242,236,.5)">الاسم</th><th style="padding:8px 4px;color:rgba(245,242,236,.5)">Calls Today</th><th style="padding:8px 4px;color:rgba(245,242,236,.5)">Total</th><th style="padding:8px 4px;color:rgba(245,242,236,.5)">آخر استخدام</th><th></th></tr>
    <?php foreach($keys as $k): ?>
    <tr style="border-bottom:1px solid rgba(245,242,236,.04)">
      <td style="padding:10px 4px;font-family:monospace;color:#2DC48F"><?= htmlspecialchars($k['key_prefix']) ?>...</td>
      <td style="padding:10px 4px"><?= htmlspecialchars($k['label']) ?></td>
      <td style="padding:10px 4px;text-align:center"><?= $k['calls_today'] ?></td>
      <td style="padding:10px 4px;text-align:center"><?= $k['calls_total'] ?></td>
      <td style="padding:10px 4px;font-size:.72rem;color:rgba(245,242,236,.4)"><?= $k['last_used_at'] ? substr($k['last_used_at'],0,16) : 'Never' ?></td>
      <td style="padding:10px 4px">
        <?php if ($k['status']==='active'): ?>
        <form method="POST" style="display:inline" onsubmit="return confirm('إلغاء هذا المفتاح؟')">
          <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf) ?>">
          <input type="hidden" name="action" value="revoke"><input type="hidden" name="key_id" value="<?= $k['id'] ?>">
          <button class="btn btn-danger" style="font-size:.72rem;padding:4px 10px">Revoke</button>
        </form>
        <?php else: ?><span style="color:rgba(245,242,236,.3);font-size:.75rem">Revoked</span><?php endif; ?>
      </td>
    </tr>
    <?php endforeach; ?>
    </table>
    <?php else: ?><div class="empty">لا توجد مفاتيح بعد</div><?php endif; ?>
  </div>
</div></body></html>
