<?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;
}

/* ========= PDO ========= */
$pdo = null;
try {
    $pdo = db();
    if ($pdo instanceof PDO) {
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $pdo = null;
}

/* ========= Params ========= */
$sessionId = (int)($_GET['session_id'] ?? 0);
$caseId    = (int)($_GET['case_id'] ?? 0);
$clientId  = (int)($_GET['client_id'] ?? 0);
$userId    = (int)($_SESSION['user_id'] ?? 0);

/* ========= Helpers ========= */
function ai_chat_table_exists(?PDO $pdo, string $table): bool
{
    if (!$pdo instanceof PDO) {
        return false;
    }

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

function ai_chat_load_messages(?PDO $pdo, int $sessionId, int $userId): array
{
    if (
        !$pdo instanceof PDO ||
        $sessionId <= 0 ||
        !ai_chat_table_exists($pdo, 'ai_chat_sessions') ||
        !ai_chat_table_exists($pdo, 'ai_chat_messages')
    ) {
        return [];
    }

    try {
        $check = $pdo->prepare("
            SELECT id
            FROM ai_chat_sessions
            WHERE id = ?
              AND user_id = ?
            LIMIT 1
        ");
        $check->execute([$sessionId, $userId]);
        if (!$check->fetch()) {
            return [];
        }

        $st = $pdo->prepare("
            SELECT sender, message, created_at
            FROM ai_chat_messages
            WHERE session_id = ?
            ORDER BY id ASC
        ");
        $st->execute([$sessionId]);
        return $st->fetchAll() ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

$oldMessages = ai_chat_load_messages($pdo, $sessionId, $userId);

render_layout_start('المساعد القانوني');
?>

<style>
.aiPageCard{
  display:flex;
  flex-direction:column;
  min-height:calc(100vh - 180px);
}

.aiPageCard .cardHead{
  margin-bottom:14px;
}

.chatWrap{
  display:flex;
  flex-direction:column;
  gap:14px;
  flex:1 1 auto;
  min-height:0;
}

.chatHeaderNote{
  color:var(--muted);
  font-size:13px;
  line-height:1.8;
}

.chatMeta{
  display:flex;
  flex-wrap:wrap;
  gap:8px;
}

.chatMeta .tag{
  font-size:12px;
}

.chatShell{
  display:flex;
  flex-direction:column;
  flex:1 1 auto;
  min-height:0;
  border:1px solid rgba(255,255,255,.08);
  background:linear-gradient(180deg, rgba(255,255,255,.03), rgba(255,255,255,.02));
  border-radius:22px;
  overflow:hidden;
  box-shadow:0 14px 40px rgba(0,0,0,.12);
}

.chatBox{
  flex:1 1 auto;
  min-height:360px;
  max-height:none;
  overflow:auto;
  display:flex;
  flex-direction:column;
  gap:12px;
  padding:18px;
  scroll-behavior:smooth;
}

.msgUser,
.msgAI,
.msgSystem{
  padding:12px 14px;
  border-radius:16px;
  max-width:min(78%, 860px);
  line-height:1.95;
  white-space:pre-wrap;
  word-break:break-word;
  font-size:15px;
}

.msgUser{
  align-self:flex-end;
  background:rgba(0,106,122,.22);
  border:1px solid rgba(0,106,122,.32);
  box-shadow:0 8px 20px rgba(0,0,0,.08);
}

.msgAI{
  align-self:flex-start;
  background:rgba(255,255,255,.06);
  border:1px solid rgba(255,255,255,.08);
  box-shadow:0 8px 20px rgba(0,0,0,.06);
}

.msgSystem{
  align-self:center;
  background:rgba(212,175,55,.10);
  border:1px solid rgba(212,175,55,.22);
  color:#f7e7a8;
  font-size:13px;
  text-align:center;
  max-width:92%;
}

.emptyState{
  color:var(--muted);
  font-size:14px;
  text-align:center;
  padding:12px 10px 4px;
  line-height:1.9;
}

.chatInputWrap{
  border-top:1px solid rgba(255,255,255,.08);
  background:rgba(4,24,31,.65);
  backdrop-filter:blur(8px);
  padding:14px;
  display:flex;
  flex-direction:column;
  gap:10px;
}

.chatInput{
  display:flex;
  gap:10px;
  align-items:stretch;
}

.chatInput input{
  flex:1 1 auto;
  min-width:0;
  height:52px;
  border-radius:14px;
}

.chatSendBtn{
  min-width:120px;
  height:52px;
  border-radius:14px;
}

.chatActions{
  display:flex;
  gap:10px;
  flex-wrap:wrap;
}

.chatBox::-webkit-scrollbar{
  width:10px;
}

.chatBox::-webkit-scrollbar-track{
  background:transparent;
}

.chatBox::-webkit-scrollbar-thumb{
  background:rgba(255,255,255,.14);
  border-radius:999px;
}

@media (max-width: 760px){
  .aiPageCard{
    min-height:calc(100vh - 130px);
  }

  .chatBox{
    min-height:300px;
    padding:14px;
  }

  .msgUser,
  .msgAI,
  .msgSystem{
    max-width:92%;
    font-size:14px;
  }

  .chatInput{
    flex-direction:column;
  }

  .chatSendBtn{
    width:100%;
    min-width:0;
  }

  .chatActions .btn{
    width:100%;
    justify-content:center;
  }
}
</style>

<div class="grid">
  <div class="card aiPageCard">
    <div class="cardHead">
      <div>
        <div class="serviceTitle">المساعد القانوني الذكي</div>
        <div class="chatHeaderNote">
          اسأل عن القوانين، المواد القانونية، القضايا، العملاء، أو اطلب صياغة أولية لمذكرة.
        </div>
      </div>
    </div>

    <div class="chatWrap">
      <div class="chatMeta">
        <?php if ($sessionId > 0): ?>
          <span class="tag">الجلسة #<?= (int)$sessionId ?></span>
        <?php else: ?>
          <span class="tag">جلسة جديدة</span>
        <?php endif; ?>

        <?php if ($caseId > 0): ?>
          <span class="tag ok">قضية #<?= (int)$caseId ?></span>
        <?php endif; ?>

        <?php if ($clientId > 0): ?>
          <span class="tag ok">عميل #<?= (int)$clientId ?></span>
        <?php endif; ?>
      </div>

      <div class="chatShell">
        <div id="chatBox" class="chatBox">
          <?php if (!empty($oldMessages)): ?>
            <div class="msgSystem">تم تحميل الرسائل السابقة لهذه الجلسة.</div>

            <?php foreach ($oldMessages as $m): ?>
              <?php
                $sender = strtolower(trim((string)($m['sender'] ?? 'assistant')));
                $text   = trim((string)($m['message'] ?? ''));
                if ($text === '') {
                    continue;
                }

                $cls = 'msgAI';
                if ($sender === 'user') {
                    $cls = 'msgUser';
                } elseif ($sender === 'system') {
                    $cls = 'msgSystem';
                }
              ?>
              <div class="<?= h($cls) ?>"><?= nl2br(h($text)) ?></div>
            <?php endforeach; ?>
          <?php else: ?>
            <div class="msgAI">مرحباً، أنا المساعد القانوني لنظام HLG-ONE.

يمكنك سؤالي عن:
- مواد قانونية
- القضايا والعملاء
- صياغة مذكرة أولية
- تحليل قانوني مبدئي</div>

            <div class="emptyState" id="emptyState">
              اكتب سؤالك في الأسفل لبدء جلسة جديدة.
            </div>
          <?php endif; ?>
        </div>

        <div class="chatInputWrap">
          <div class="chatInput">
            <input
              type="text"
              id="msg"
              class="input"
              placeholder="اكتب سؤالك القانوني هنا..."
              autocomplete="off"
            >
            <button type="button" class="btn chatSendBtn" id="sendBtn" onclick="sendMsg()">إرسال</button>
          </div>

          <div class="chatActions">
            <a class="btn ghost" href="<?= h(u('HLG-AI-Legal-Core/legal_ai.php')) ?>">العودة إلى لوحة الذكاء القانوني</a>
            <?php if ($sessionId > 0): ?>
              <a class="btn ghost" href="<?= h(u('HLG-AI-Legal-Core/legal_ai_history.php?session_id=' . $sessionId)) ?>">فتح السجل</a>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
let currentSessionId = <?= (int)$sessionId ?>;
let currentCaseId    = <?= (int)$caseId ?>;
let currentClientId  = <?= (int)$clientId ?>;
let isSending        = false;

function removeEmptyState() {
  const empty = document.getElementById("emptyState");
  if (empty) empty.remove();
}

function appendMessage(className, text, isHtml = false) {
  const box = document.getElementById("chatBox");
  if (!box) return null;

  removeEmptyState();

  const el = document.createElement("div");
  el.className = className;

  if (isHtml) {
    el.innerHTML = text;
  } else {
    el.innerText = text;
  }

  box.appendChild(el);
  box.scrollTop = box.scrollHeight;
  return el;
}

function setSendingState(state) {
  isSending = state;
  const btn = document.getElementById("sendBtn");
  const input = document.getElementById("msg");

  if (btn) {
    btn.disabled = state;
    btn.style.opacity = state ? "0.7" : "1";
    btn.style.cursor = state ? "not-allowed" : "pointer";
  }

  if (input) {
    input.disabled = state;
  }
}

function sendMsg(){
  if (isSending) return;

  const input = document.getElementById("msg");
  const text = (input?.value || "").trim();
  if (!text) return;

  appendMessage("msgUser", text);

  input.value = "";
  setSendingState(true);

  const loading = appendMessage("msgAI", "جارٍ البحث في النظام القانوني...");
  if (input) input.focus();

  fetch("<?= h(u('HLG-AI-Legal-Core/ai_api.php')) ?>", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      message: text,
      session_id: currentSessionId,
      case_id: currentCaseId,
      client_id: currentClientId
    })
  })
  .then(async (r) => {
    let data = null;
    try {
      data = await r.json();
    } catch (e) {
      data = { reply: "صدر رد غير صالح من الخادم." };
    }

    if (loading) loading.remove();

    appendMessage("msgAI", data.reply || "تعذر تكوين الرد.");

    if (data.session_id && !currentSessionId) {
      currentSessionId = parseInt(data.session_id, 10) || 0;

      if (currentSessionId > 0) {
        const url = new URL(window.location.href);
        url.searchParams.set("session_id", String(currentSessionId));
        if (currentCaseId > 0) {
          url.searchParams.set("case_id", String(currentCaseId));
        }
        if (currentClientId > 0) {
          url.searchParams.set("client_id", String(currentClientId));
        }
        window.history.replaceState({}, "", url.toString());
      }
    }
  })
  .catch(() => {
    if (loading) loading.remove();
    appendMessage("msgAI", "تعذر الاتصال بخدمة الذكاء القانوني حالياً.");
  })
  .finally(() => {
    setSendingState(false);
    const box = document.getElementById("chatBox");
    if (box) box.scrollTop = box.scrollHeight;
    if (input) input.focus();
  });
}

document.getElementById("msg")?.addEventListener("keydown", function(e){
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    sendMsg();
  }
});

window.addEventListener("load", function(){
  const box = document.getElementById("chatBox");
  if (box) {
    box.scrollTop = box.scrollHeight;
  }
  const input = document.getElementById("msg");
  if (input) input.focus();
});
</script>

<?php
render_layout_end();
?>