<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../inc/layout.php';

if (empty($_SESSION['user_id'])) {
    header('Location: ' . u('index.html?e=1'));
    exit;
}

if (!in_array(current_role(), ['OWNER', 'ADMIN', 'LAWYER', 'STAFF'], true)) {
    http_response_code(403);
    exit('غير مصرح');
}

function ai_hist_h($v): string
{
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

function ai_hist_table_exists(PDO $pdo, string $table): bool
{
    static $cache = [];
    if (isset($cache[$table])) {
        return $cache[$table];
    }

    try {
        $st = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = ?
        ");
        $st->execute([$table]);
        $cache[$table] = ((int)$st->fetchColumn() > 0);
        return $cache[$table];
    } catch (Throwable $e) {
        return false;
    }
}

function ai_hist_columns(PDO $pdo, string $table): array
{
    static $cache = [];

    if (isset($cache[$table])) {
        return $cache[$table];
    }

    if (!ai_hist_table_exists($pdo, $table)) {
        $cache[$table] = [];
        return [];
    }

    try {
        $st = $pdo->prepare("
            SELECT COLUMN_NAME
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = ?
        ");
        $st->execute([$table]);
        $cols = $st->fetchAll(PDO::FETCH_COLUMN);
        $cache[$table] = is_array($cols) ? array_map('strtolower', $cols) : [];
        return $cache[$table];
    } catch (Throwable $e) {
        return [];
    }
}

function ai_hist_has_col(PDO $pdo, string $table, string $column): bool
{
    return in_array(strtolower($column), ai_hist_columns($pdo, $table), true);
}

function ai_hist_pick_col(PDO $pdo, string $table, array $candidates): ?string
{
    foreach ($candidates as $c) {
        if (ai_hist_has_col($pdo, $table, $c)) {
            return $c;
        }
    }
    return null;
}

function ai_hist_clean(string $text): string
{
    $text = trim($text);
    $text = str_replace(["\r\n", "\r"], "\n", $text);
    $text = preg_replace('/[ \t]+/u', ' ', $text);
    $text = preg_replace("/\n{3,}/u", "\n\n", $text);
    return trim((string)$text);
}

function ai_hist_excerpt(?string $text, int $limit = 220): string
{
    $text = ai_hist_clean((string)$text);
    if (mb_strlen($text) <= $limit) {
        return $text;
    }
    return mb_substr($text, 0, $limit) . '...';
}

function ai_hist_like_escape(string $s): string
{
    return str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $s);
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| أسماء الجداول المحتملة
|--------------------------------------------------------------------------
*/
$historyTable = null;
foreach (['legal_ai_history', 'ai_chat_history', 'legal_ai_logs', 'legal_ai_conversations'] as $tbl) {
    if (ai_hist_table_exists($pdo, $tbl)) {
        $historyTable = $tbl;
        break;
    }
}

$msg = '';
$err = '';

$role     = current_role();
$userId   = (int)($_SESSION['user_id'] ?? 0);
$branchId = current_branch_id();

$q        = trim((string)($_GET['q'] ?? ''));
$type     = trim((string)($_GET['type'] ?? ''));
$page     = max(1, (int)($_GET['page'] ?? 1));
$perPage  = 12;
$offset   = ($page - 1) * $perPage;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $historyTable !== null) {
    try {
        $idCol       = ai_hist_pick_col($pdo, $historyTable, ['id']);
        $userIdCol   = ai_hist_pick_col($pdo, $historyTable, ['user_id', 'created_by']);
        $branchCol   = ai_hist_pick_col($pdo, $historyTable, ['branch_id']);
        $createdCol  = ai_hist_pick_col($pdo, $historyTable, ['created_at', 'created_on', 'log_date']);

        if (!$idCol) {
            throw new RuntimeException('تعذر تحديد المفتاح الأساسي لجدول السجل.');
        }

        if (isset($_POST['delete_one'])) {
            $deleteId = (int)($_POST['delete_id'] ?? 0);
            if ($deleteId > 0) {
                $where = ["`{$idCol}` = ?"];
                $params = [$deleteId];

                if (!in_array($role, ['OWNER', 'ADMIN'], true)) {
                    if ($userIdCol) {
                        $where[] = "`{$userIdCol}` = ?";
                        $params[] = $userId;
                    } elseif ($branchCol) {
                        $where[] = "`{$branchCol}` = ?";
                        $params[] = $branchId;
                    }
                }

                $sql = "DELETE FROM `{$historyTable}` WHERE " . implode(' AND ', $where) . " LIMIT 1";
                $st  = $pdo->prepare($sql);
                $st->execute($params);

                $msg = 'تم حذف السجل بنجاح.';
            }
        }

        if (isset($_POST['delete_all']) && in_array($role, ['OWNER', 'ADMIN'], true)) {
            $where = [];
            $params = [];

            if ($branchCol && !is_owner()) {
                $where[] = "`{$branchCol}` = ?";
                $params[] = $branchId;
            }

            $sql = "DELETE FROM `{$historyTable}`";
            if ($where) {
                $sql .= " WHERE " . implode(' AND ', $where);
            }

            $st = $pdo->prepare($sql);
            $st->execute($params);
            $msg = 'تم حذف جميع السجلات المسموح بها بنجاح.';
        }
    } catch (Throwable $e) {
        $err = 'تعذر تنفيذ العملية: ' . $e->getMessage();
    }
}

render_layout_start('سجل محادثات الذكاء القانوني');
?>

<style>
.hist-page{
  width:100%;
  max-width:100%;
}
.hist-hero{
  border:1px solid rgba(255,255,255,.08);
  background:linear-gradient(135deg, rgba(0,106,122,.35), rgba(0,66,79,.18));
  border-radius:22px;
  padding:24px;
  margin-bottom:18px;
  box-shadow:0 10px 30px rgba(0,0,0,.14);
}
.hist-hero h1{
  margin:0 0 8px;
  font-size:28px;
  line-height:1.3;
}
.hist-hero p{
  margin:0;
  color:rgba(255,255,255,.78);
  line-height:1.8;
  font-size:14px;
}
.hist-toolbar{
  border:1px solid var(--line);
  background:rgba(255,255,255,.04);
  border-radius:18px;
  padding:16px;
  margin-bottom:16px;
}
.hist-form{
  display:grid;
  grid-template-columns:1.2fr .7fr auto auto;
  gap:12px;
  align-items:end;
}
.hist-label{
  display:block;
  margin-bottom:8px;
  font-size:13px;
  color:var(--muted);
  font-weight:700;
}
.hist-grid{
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(320px,1fr));
  gap:16px;
}
.hist-card{
  border:1px solid var(--line);
  background:rgba(255,255,255,.04);
  border-radius:18px;
  padding:16px;
  min-width:0;
  box-shadow:0 8px 24px rgba(0,0,0,.08);
}
.hist-card-top{
  display:flex;
  justify-content:space-between;
  gap:10px;
  align-items:flex-start;
  flex-wrap:wrap;
  margin-bottom:12px;
}
.hist-title{
  font-weight:800;
  font-size:16px;
  line-height:1.7;
}
.hist-meta{
  color:var(--muted);
  font-size:12px;
  line-height:1.8;
}
.hist-badges{
  display:flex;
  gap:8px;
  flex-wrap:wrap;
}
.hist-badge{
  display:inline-block;
  padding:6px 10px;
  border-radius:999px;
  border:1px solid var(--line);
  background:rgba(0,0,0,.10);
  font-size:12px;
  color:var(--muted);
}
.hist-sec{
  margin-bottom:12px;
}
.hist-sec:last-child{
  margin-bottom:0;
}
.hist-sec .k{
  font-size:12px;
  color:var(--muted);
  margin-bottom:6px;
  font-weight:700;
}
.hist-sec .v{
  line-height:1.95;
  color:rgba(255,255,255,.92);
  white-space:pre-wrap;
  word-break:break-word;
}
.hist-actions{
  display:flex;
  gap:10px;
  flex-wrap:wrap;
  margin-top:14px;
}
.hist-empty{
  border:1px dashed var(--line);
  background:rgba(255,255,255,.03);
  border-radius:18px;
  padding:24px;
  color:var(--muted);
  line-height:1.9;
}
.hist-pagination{
  display:flex;
  gap:10px;
  justify-content:center;
  flex-wrap:wrap;
  margin-top:18px;
}
.hist-page-link{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:44px;
  min-height:44px;
  padding:8px 14px;
  border-radius:14px;
  border:1px solid var(--line);
  background:rgba(255,255,255,.04);
  color:var(--text);
  text-decoration:none;
  font-weight:800;
}
.hist-page-link.active{
  background:linear-gradient(180deg, rgba(0,106,122,.35), rgba(0,66,79,.18));
  border-color:rgba(0,106,122,.45);
}
@media (max-width: 980px){
  .hist-form{
    grid-template-columns:1fr 1fr;
  }
}
@media (max-width: 640px){
  .hist-form{
    grid-template-columns:1fr;
  }
}
</style>

<div class="hist-page">
  <div class="hist-hero">
    <h1>سجل محادثات الذكاء القانوني</h1>
    <p>عرض واسترجاع محادثات الموظفين مع الذكاء القانوني، مع إمكانية البحث والفلترة والمراجعة الإدارية.</p>
  </div>

  <?php if ($msg !== ''): ?>
    <div class="msg ok"><?= ai_hist_h($msg) ?></div>
  <?php endif; ?>

  <?php if ($err !== ''): ?>
    <div class="msg err"><?= ai_hist_h($err) ?></div>
  <?php endif; ?>

  <?php if ($historyTable === null): ?>
    <div class="hist-empty">
      لم يتم العثور على جدول سجل المحادثات.
      <br><br>
      أنشئ جدولًا مثل: <code>legal_ai_history</code> ثم أعد تحميل الصفحة.
    </div>
  <?php else: ?>

    <?php
    $idCol        = ai_hist_pick_col($pdo, $historyTable, ['id']);
    $questionCol  = ai_hist_pick_col($pdo, $historyTable, ['question', 'message', 'user_message', 'prompt']);
    $replyCol     = ai_hist_pick_col($pdo, $historyTable, ['reply', 'response', 'assistant_reply', 'answer']);
    $typeCol      = ai_hist_pick_col($pdo, $historyTable, ['type', 'intent', 'category']);
    $userIdCol    = ai_hist_pick_col($pdo, $historyTable, ['user_id', 'created_by']);
    $userNameCol  = ai_hist_pick_col($pdo, $historyTable, ['user_name', 'username', 'created_by_name', 'name']);
    $branchCol    = ai_hist_pick_col($pdo, $historyTable, ['branch_id']);
    $createdCol   = ai_hist_pick_col($pdo, $historyTable, ['created_at', 'created_on', 'log_date']);
    $keywordsCol  = ai_hist_pick_col($pdo, $historyTable, ['keywords']);
    $sessionCol   = ai_hist_pick_col($pdo, $historyTable, ['session_id', 'chat_id', 'conversation_id']);

    $where = [];
    $params = [];

    if ($q !== '') {
        $safe = '%' . ai_hist_like_escape($q) . '%';
        $parts = [];

        foreach (array_filter([$questionCol, $replyCol, $keywordsCol, $userNameCol, $typeCol]) as $col) {
            $parts[] = "`{$col}` LIKE ?";
            $params[] = $safe;
        }

        if ($parts) {
            $where[] = '(' . implode(' OR ', $parts) . ')';
        }
    }

    if ($type !== '' && $typeCol) {
        $where[] = "`{$typeCol}` = ?";
        $params[] = $type;
    }

    if (!in_array($role, ['OWNER', 'ADMIN'], true)) {
        if ($userIdCol) {
            $where[] = "`{$userIdCol}` = ?";
            $params[] = $userId;
        } elseif ($branchCol) {
            $where[] = "`{$branchCol}` = ?";
            $params[] = $branchId;
        }
    } elseif ($branchCol && !is_owner()) {
        $where[] = "`{$branchCol}` = ?";
        $params[] = $branchId;
    }

    $countSql = "SELECT COUNT(*) FROM `{$historyTable}`";
    if ($where) {
        $countSql .= " WHERE " . implode(' AND ', $where);
    }

    $stCount = $pdo->prepare($countSql);
    $stCount->execute($params);
    $totalRows = (int)$stCount->fetchColumn();
    $totalPages = max(1, (int)ceil($totalRows / $perPage));

    if ($page > $totalPages) {
        $page = $totalPages;
        $offset = ($page - 1) * $perPage;
    }

    $selectCols = [];
    foreach ([$idCol, $questionCol, $replyCol, $typeCol, $userIdCol, $userNameCol, $branchCol, $createdCol, $keywordsCol, $sessionCol] as $c) {
        if ($c) {
            $selectCols[] = "`{$c}`";
        }
    }

    $orderCol = $createdCol ?: $idCol;

    $sql = "SELECT " . implode(', ', array_unique($selectCols)) . "
            FROM `{$historyTable}`";
    if ($where) {
        $sql .= " WHERE " . implode(' AND ', $where);
    }
    $sql .= " ORDER BY `" . $orderCol . "` DESC LIMIT " . (int)$perPage . " OFFSET " . (int)$offset;

    $st = $pdo->prepare($sql);
    $st->execute($params);
    $rows = $st->fetchAll();

    $types = [];
    if ($typeCol) {
        try {
            $sqlTypes = "SELECT DISTINCT `{$typeCol}` AS t FROM `{$historyTable}` WHERE `{$typeCol}` IS NOT NULL AND `{$typeCol}` <> '' ORDER BY `{$typeCol}` ASC";
            $stTypes = $pdo->query($sqlTypes);
            $types = $stTypes->fetchAll(PDO::FETCH_COLUMN);
            if (!is_array($types)) {
                $types = [];
            }
        } catch (Throwable $e) {
            $types = [];
        }
    }
    ?>

    <div class="hist-toolbar">
      <form method="get" class="hist-form">
        <div>
          <label class="hist-label">بحث</label>
          <input class="input" type="text" name="q" value="<?= ai_hist_h($q) ?>" placeholder="ابحث في السؤال أو الرد أو الكلمات المفتاحية">
        </div>

        <div>
          <label class="hist-label">النوع</label>
          <select class="input" name="type">
            <option value="">الكل</option>
            <?php foreach ($types as $t): ?>
              <option value="<?= ai_hist_h((string)$t) ?>" <?= $type === (string)$t ? 'selected' : '' ?>>
                <?= ai_hist_h((string)$t) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div>
          <button class="btn" type="submit">بحث</button>
        </div>

        <?php if (in_array($role, ['OWNER', 'ADMIN'], true)): ?>
          <div>
            <form method="post" onsubmit="return confirm('هل أنت متأكد من حذف جميع السجلات المسموح بها؟');">
              <button class="btn danger" type="submit" name="delete_all" value="1">حذف الكل</button>
            </form>
          </div>
        <?php endif; ?>
      </form>
    </div>

    <?php if (!$rows): ?>
      <div class="hist-empty">
        لا توجد محادثات مطابقة للفلترة الحالية.
      </div>
    <?php else: ?>
      <div class="hist-grid">
        <?php foreach ($rows as $r): ?>
          <?php
          $rowId     = (int)($idCol ? ($r[$idCol] ?? 0) : 0);
          $question  = $questionCol ? (string)($r[$questionCol] ?? '') : '';
          $reply     = $replyCol ? (string)($r[$replyCol] ?? '') : '';
          $rowType   = $typeCol ? (string)($r[$typeCol] ?? '') : '';
          $rowUser   = $userNameCol ? (string)($r[$userNameCol] ?? '') : '';
          $rowDate   = $createdCol ? (string)($r[$createdCol] ?? '') : '';
          $rowKw     = $keywordsCol ? (string)($r[$keywordsCol] ?? '') : '';
          $rowSess   = $sessionCol ? (string)($r[$sessionCol] ?? '') : '';
          $rowBranch = $branchCol ? (string)($r[$branchCol] ?? '') : '';
          ?>
          <div class="hist-card">
            <div class="hist-card-top">
              <div>
                <div class="hist-title">محادثة #<?= (int)$rowId ?></div>
                <div class="hist-meta">
                  <?= $rowDate !== '' ? ai_hist_h($rowDate) : '-' ?>
                  <?php if ($rowUser !== ''): ?> · <?= ai_hist_h($rowUser) ?><?php endif; ?>
                  <?php if ($rowBranch !== ''): ?> · الفرع: <?= ai_hist_h($rowBranch) ?><?php endif; ?>
                </div>
              </div>

              <div class="hist-badges">
                <?php if ($rowType !== ''): ?>
                  <span class="hist-badge"><?= ai_hist_h($rowType) ?></span>
                <?php endif; ?>
                <?php if ($rowSess !== ''): ?>
                  <span class="hist-badge">جلسة: <?= ai_hist_h($rowSess) ?></span>
                <?php endif; ?>
              </div>
            </div>

            <div class="hist-sec">
              <div class="k">السؤال</div>
              <div class="v"><?= ai_hist_h(ai_hist_excerpt($question, 260)) ?></div>
            </div>

            <div class="hist-sec">
              <div class="k">الرد</div>
              <div class="v"><?= ai_hist_h(ai_hist_excerpt($reply, 420)) ?></div>
            </div>

            <?php if ($rowKw !== ''): ?>
              <div class="hist-sec">
                <div class="k">الكلمات المفتاحية</div>
                <div class="v"><?= ai_hist_h(ai_hist_excerpt($rowKw, 180)) ?></div>
              </div>
            <?php endif; ?>

            <div class="hist-actions">
              <?php
              $detailsUrl = u('HLG-AI-Legal-Core/legal_ai.php') . '?history_id=' . $rowId;
              ?>
              <a class="btn ghost" href="<?= ai_hist_h($detailsUrl) ?>">فتح في الذكاء القانوني</a>

              <form method="post" onsubmit="return confirm('هل تريد حذف هذا السجل؟');" style="margin:0">
                <input type="hidden" name="delete_id" value="<?= (int)$rowId ?>">
                <button class="btn danger" type="submit" name="delete_one" value="1">حذف</button>
              </form>
            </div>
          </div>
        <?php endforeach; ?>
      </div>

      <?php if ($totalPages > 1): ?>
        <div class="hist-pagination">
          <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <?php
            $link = '?q=' . urlencode($q) . '&type=' . urlencode($type) . '&page=' . $i;
            ?>
            <a class="hist-page-link <?= $i === $page ? 'active' : '' ?>" href="<?= ai_hist_h($link) ?>">
              <?= (int)$i ?>
            </a>
          <?php endfor; ?>
        </div>
      <?php endif; ?>
    <?php endif; ?>

  <?php endif; ?>
</div>

<?php render_layout_end(); ?>