<?php
require_once '../config.php';
start_secure_session();
$u=current_user();if(!$u){header('Location: ' . url('?login=1'));exit;}
$userId=(int)$u['id'];

// Filters
$sector   = $_GET['sector']??'';
$action   = $_GET['action']??'';
$limit    = min((int)($_GET['limit']??20),100);

// Fetch logs
$logs=[];
try{
  $sql="SELECT * FROM execution_log WHERE user_id=?";
  $params=[$userId];
  if($sector){$sql.=" AND sector=?";$params[]=$sector;}
  if($action){$sql.=" AND assistant_action=?";$params[]=$action;}
  $sql.=" ORDER BY created_at DESC LIMIT ".$limit;
  $stmt=db()->prepare($sql);$stmt->execute($params);$logs=$stmt->fetchAll();
}catch(Throwable $e){}
?><!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <title>سجلات AI — سودانا</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)}
    .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}
    .back{color:var(--muted);font-size:.8rem;text-decoration:none;border:1px solid var(--border);padding:5px 12px;border-radius:7px}
    .container{max-width:1000px;margin:0 auto;padding:20px}
    .filters{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px}
    .filters select,.filters a{background:var(--card);border:1px solid var(--border);color:var(--text);padding:7px 12px;border-radius:8px;font-family:inherit;font-size:.78rem;text-decoration:none;cursor:pointer}
    .filters select:focus{outline:none;border-color:var(--green)}
    .log-table{width:100%;border-collapse:collapse;font-size:.76rem}
    .log-table th{padding:10px 12px;text-align:right;color:var(--muted);font-weight:600;border-bottom:1px solid var(--border);background:#060d1a;position:sticky;top:52px}
    .log-table td{padding:9px 12px;border-bottom:1px solid var(--border);vertical-align:middle}
    .log-table tr:hover{background:#0d2137}
    .badge{font-size:.65rem;padding:2px 7px;border-radius:9px;font-weight:700;display:inline-block}
    .badge.ai_answer{background:#00d97e15;color:#00d97e}
    .badge.execute_flow{background:#0ea5e915;color:#0ea5e9}
    .badge.execute_tool{background:#f59e0b15;color:#f59e0b}
    .sector-dot{width:8px;height:8px;border-radius:50%;display:inline-block;margin-left:6px}
    .conf-bar{height:4px;border-radius:2px;background:linear-gradient(90deg,#00d97e,#0ea5e9);display:inline-block}
    @media(max-width:600px){.log-table{font-size:.7rem}.container{padding:12px}}
  </style>
</head>
<body>
<header class="header">
  <div class="logo">📋 سجلات AI</div>
  <a href="/dashboard/" class="back">← Dashboard</a>
</header>
<div class="container">
  <!-- Filters -->
  <form method="GET" class="filters">
    <select name="sector" onchange="this.form.submit()">
      <option value="">كل القطاعات</option>
      <?php foreach(['medical','legal','education','finance','business','developer','platform','mental','career','community'] as $s): ?>
      <option value="<?= $s ?>" <?= $sector===$s?'selected':'' ?>><?= $s ?></option>
      <?php endforeach;?>
    </select>
    <select name="action" onchange="this.form.submit()">
      <option value="">كل الإجراءات</option>
      <option value="ai_answer" <?= $action==='ai_answer'?'selected':'' ?>>AI Answer</option>
      <option value="execute_flow" <?= $action==='execute_flow'?'selected':'' ?>>Flow</option>
      <option value="execute_tool" <?= $action==='execute_tool'?'selected':'' ?>>Tool</option>
    </select>
    <select name="limit" onchange="this.form.submit()">
      <option value="20" <?= $limit===20?'selected':'' ?>>20 آخر</option>
      <option value="50" <?= $limit===50?'selected':'' ?>>50 آخر</option>
      <option value="100" <?= $limit===100?'selected':'' ?>>100 آخر</option>
    </select>
    <a href="?">🔄 إعادة ضبط</a>
  </form>

  <!-- Logs table -->
  <div style="background:var(--card);border:1px solid var(--border);border-radius:14px;overflow:hidden">
    <?php if($logs): ?>
    <div style="overflow-x:auto">
    <table class="log-table">
      <thead><tr>
        <th>الوقت</th><th>القطاع</th><th>النية</th><th>الإجراء</th><th>الثقة</th><th>المدة</th>
      </tr></thead>
      <tbody>
      <?php foreach($logs as $l): ?>
      <tr>
        <td style="color:var(--muted);font-size:.7rem"><?= date('m/d H:i',strtotime($l['created_at']??'now')) ?></td>
        <td>
          <span class="sector-dot" style="background:<?= match($l['sector']??''){
            'medical'=>'#ef4444','legal'=>'#a78bfa','education'=>'#f59e0b',
            'finance'=>'#0ea5e9','business'=>'#60a5fa',default=>'#64748b'
          } ?>"></span>
          <?= htmlspecialchars($l['sector']??'—') ?>
        </td>
        <td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#94a3b8">
          <?= htmlspecialchars(substr($l['intent']??$l['question']??'—',0,50)) ?>
        </td>
        <td><span class="badge <?= $l['assistant_action']??'' ?>"><?= $l['assistant_action']??'—' ?></span></td>
        <td>
          <div style="display:flex;align-items:center;gap:5px">
            <div class="conf-bar" style="width:<?= round(($l['confidence']??0)*40) ?>px"></div>
            <span style="font-size:.68rem;color:var(--muted)"><?= number_format($l['confidence']??0,2) ?></span>
          </div>
        </td>
        <td style="color:var(--muted)"><?= $l['duration_ms']??'—' ?>ms</td>
      </tr>
      <?php endforeach;?>
      </tbody>
    </table>
    </div>
    <?php else:?>
    <div style="text-align:center;padding:32px;color:var(--muted)">لا توجد سجلات <?= $sector?'للقطاع '.$sector:'' ?></div>
    <?php endif;?>
  </div>
</div>
</body>
</html>