<?php
require_once __DIR__ . '/../config.php';
$pdo = db();
$conv = $pdo->query("SELECT id, title FROM conversations ORDER BY id ASC")->fetchAll();
$conversation_id = isset($_GET['c']) ? intval($_GET['c']) : ($conv ? $conv[0]['id'] : 1);
$messages = $pdo->prepare("SELECT role, content, created_at FROM messages WHERE conversation_id = ? ORDER BY id ASC");
$messages->execute([$conversation_id]);
$msgs = $messages->fetchAll();
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>ChatGPT-like PHP App</title>
  <link rel="stylesheet" href="assets/css/style.css"/>
</head>
<body>
  <div class="container">
    <h1>ChatGPT-like App (PHP 7.4 + MySQL)</h1>
    <div class="conversations">
      <strong>Conversations:</strong>
      <?php foreach ($conv as $c): ?>
        <a class="conv-link <?php echo $c['id']==$conversation_id?'active':''; ?>" href="?c=<?php echo $c['id']; ?>">
          <?php echo htmlspecialchars($c['title']); ?>
        </a>
      <?php endforeach; ?>
    </div>
    <div class="chat-history" id="chat-history">
      <?php foreach ($msgs as $m): ?>
        <div class="msg <?php echo htmlspecialchars($m['role']); ?>">
          <div class="role"><?php echo strtoupper(htmlspecialchars($m['role'])); ?></div>
          <div class="content"><?php echo nl2br(htmlspecialchars($m['content'])); ?></div>
          <div class="time"><?php echo htmlspecialchars($m['created_at']); ?></div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- Floating Chat Widget -->
  <div class="chat-widget" id="chat-widget">
    <div class="chat-header">
      <span>AI Chat</span>
      <div class="actions">
        <button id="toggle-analyzer" title="Analyzer Panel">📎</button>
        <button id="minimize" title="Minimize">—</button>
        <button id="maximize" title="Maximize">⬜</button>
      </div>
    </div>
    <div class="chat-body" id="chat-body">
      <div class="messages" id="messages"></div>
      <div class="controls">
        <textarea id="prompt" placeholder="Tulis pesan... (Shift+Enter baris baru)"></textarea>
        <div class="row">
          <button id="send">Kirim</button>
          <select id="model">
            <option value="<?php echo htmlspecialchars(envv('OPENAI_MODEL', 'gpt-4o-mini')); ?>"><?php echo htmlspecialchars(envv('OPENAI_MODEL', 'gpt-4o-mini')); ?></option>
          </select>
        </div>
      </div>
    </div>
    <div class="analyzer" id="analyzer" style="display:none;">
      <div class="panel">
        <h3>Document & Image Analyzer</h3>
        <input type="file" id="files" multiple/>
        <div style="margin-top:8px;">
          <button id="analyze">Analyze</button>
          <span class="hint">PDF via pdftotext/pdftohtml; DOC via antiword/catdoc; DOCX native; Images via Vision.</span>
        </div>
        <pre id="analyze-result"></pre>
      </div>
    </div>
  </div>

  <script>
  const conversationId = <?php echo json_encode($conversation_id); ?>;
  const msgsEl = document.getElementById('messages');
  const promptEl = document.getElementById('prompt');
  const sendBtn = document.getElementById('send');
  const modelEl = document.getElementById('model');
  const chatHistoryEl = document.getElementById('chat-history');

  function addBubble(role, text) {
    const div = document.createElement('div');
    div.className = 'bubble ' + role;
    div.innerHTML = '<div class="role">'+role.toUpperCase()+'</div><div class="text"></div>';
    div.querySelector('.text').textContent = text;
    msgsEl.appendChild(div);
    msgsEl.scrollTop = msgsEl.scrollHeight;
    return div.querySelector('.text');
  }

  function parseSSEAndAppend(reader, decoder, targetEl) {
    let buffer = '';
    function read() {
      return reader.read().then(({done, value}) => {
        if (done) return;
        buffer += decoder.decode(value, {stream:true});
        const parts = buffer.split('\n\n');
        buffer = parts.pop();
        for (const part of parts) {
          const lines = part.split('\n').filter(Boolean);
          let event = null;
          for (const line of lines) {
            if (line.startsWith('event:')) event = line.slice(6).trim();
            if (line.startsWith('data:')) {
              const dataStr = line.slice(5).trim();
              try {
                const j = JSON.parse(dataStr);
                if (event === 'response.output_text.delta') {
                  const delta = j.delta || j.text || '';
                  targetEl.textContent += delta;
                }
                if (event === 'response.error') {
                  targetEl.textContent += '\n[error] ' + (j.error || JSON.stringify(j));
                }
              } catch(e) {
                // ignore non-JSON data lines (e.g. [DONE])
              }
            }
          }
        }
        msgsEl.scrollTop = msgsEl.scrollHeight;
        return read();
      });
    }
    return read();
  }

  sendBtn.addEventListener('click', async () => {
    const text = promptEl.value.trim();
    if (!text) return;
    const userEl = addBubble('user', text);
    promptEl.value='';
    const assistantEl = addBubble('assistant', '');
    const res = await fetch('api/stream.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({message: text, conversation_id: conversationId, model: modelEl.value})
    });
    const reader = res.body.getReader();
    const decoder = new TextDecoder();
    await parseSSEAndAppend(reader, decoder, assistantEl);
  });

  promptEl.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault(); sendBtn.click();
    }
  });

  document.getElementById('minimize').onclick = () => {
    document.getElementById('chat-body').style.display='none';
  };
  document.getElementById('maximize').onclick = () => {
    document.getElementById('chat-body').style.display='block';
    document.getElementById('analyzer').style.display='none';
  };
  document.getElementById('toggle-analyzer').onclick = () => {
    const a = document.getElementById('analyzer');
    a.style.display = a.style.display==='none' ? 'block' : 'none';
    document.getElementById('chat-body').style.display = a.style.display==='none' ? 'block' : 'none';
  };

  // Analyzer
  document.getElementById('analyze').onclick = async () => {
    const files = document.getElementById('files').files;
    if (!files.length) return alert('Pilih file dulu');
    const fd = new FormData();
    fd.append('conversation_id', conversationId);
    for (const f of files) fd.append('files[]', f);
    const res = await fetch('api/analyze_upload.php', { method:'POST', body: fd });
    const js = await res.json();
    const pre = document.getElementById('analyze-result');
    pre.textContent = JSON.stringify(js, null, 2);
  };
  </script>
</body>
</html>
