<?php

declare(strict_types=1);

/**
 * Ask a question — login-gated form + create. Reached at "/ask" via
 * public-routes.php. Creates a qa_questions row (slug via Slugify, author via
 * the forum identity bridge) + links tags, then redirects to the new thread.
 */

require __DIR__ . '/_shell.php';

use PpPhp\Core\Security;
use PpPhp\Core\DB;
use PpPhp\Core\Seo\Slugify;

$b   = forum_base();
$uid = forum_author_id();
if (!$uid) {
    header('Location: ' . $b . '/login');
    exit;
}
// Suspended members can browse but not post.
$suspended = forum_is_suspended();

$err  = '';
$vals = ['title' => '', 'body' => '', 'category' => 0, 'tags' => ''];
$categories = dbAll('SELECT id, name FROM qa_categories ORDER BY sort_order, name');

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $vals['title']    = trim((string) ($_POST['title'] ?? ''));
    $vals['body']     = trim((string) ($_POST['body'] ?? ''));
    $vals['category'] = (int) ($_POST['category'] ?? 0);
    $vals['tags']     = trim((string) ($_POST['tags'] ?? ''));

    if ($suspended) {
        $err = 'Your account is suspended — you can’t post questions right now.';
    } elseif (!Security::CSRF()->Check((string) ($_POST['_token'] ?? ''))) {
        $err = 'Your session expired — please submit again.';
    } elseif (mb_strlen($vals['title']) < 12) {
        $err = 'Give your question a clear title (at least 12 characters).';
    } elseif (mb_strlen($vals['body']) < 20) {
        $err = 'Add a bit more detail so people can help (at least 20 characters).';
    } else {
        $slug = Slugify::make($vals['title'], 200) ?: 'question';
        $stem = $slug; $n = 1;
        while (dbValue('SELECT id FROM qa_questions WHERE slug = ?', [$slug])) {
            $slug = $stem . '-' . (++$n);
        }
        $catId = ($vals['category'] > 0 && dbValue('SELECT id FROM qa_categories WHERE id = ?', [$vals['category']]))
            ? $vals['category'] : null;

        DB::Insert('qa_questions', [
            'slug'      => $slug,
            'title'     => $vals['title'],
            'body_md'   => $vals['body'],
            'author_id' => $uid,
            'category_id' => $catId,
            'status'    => 'open',
        ]);
        $qid = (int) dbValue('SELECT id FROM qa_questions WHERE slug = ?', [$slug]);

        // Tags: up to 5, find-or-create then link.
        $tagList = array_slice(array_filter(array_map('trim', preg_split('/[,\s]+/', $vals['tags']) ?: [])), 0, 5);
        foreach ($tagList as $tg) {
            $tslug = Slugify::make($tg, 40);
            if ($tslug === '') continue;
            $tid = dbValue('SELECT id FROM qa_tags WHERE slug = ?', [$tslug]);
            if (!$tid) {
                DB::Insert('qa_tags', ['slug' => $tslug, 'name' => mb_strtolower($tg)]);
                $tid = dbValue('SELECT id FROM qa_tags WHERE slug = ?', [$tslug]);
            }
            if ($tid) {
                try { DB::Insert('qa_question_tags', ['question_id' => $qid, 'tag_id' => $tid]); } catch (\Throwable $e) {}
            }
        }
        if ($catId) {
            try { DB::Query('UPDATE qa_categories SET question_count = question_count + 1 WHERE id = ?', [$catId]); } catch (\Throwable $e) {}
        }
        header('Location: ' . $b . '/q/' . $qid . '/' . $slug);
        exit;
    }
}

forum_head('Ask a Question — PPPHP Community');
?>
<a class="fx-back" href="<?= $b ?>/"><i class="bi bi-arrow-left"></i> All questions</a>
<h1 class="fx-h1">Ask a Question</h1>
<p class="fx-sub">Be specific and imagine you're asking another person. Markdown is supported.</p>

<form class="fx-card-form" method="post" action="<?= $b ?>/ask">
  <input type="hidden" name="_token" value="<?= forum_e(forum_csrf()) ?>">
  <?php if ($err): ?><div class="fx-formerr"><i class="bi bi-exclamation-circle"></i> <?= forum_e($err) ?></div><?php endif; ?>

  <div class="fx-field">
    <label>Title <span class="hint">a one-line summary of your problem</span></label>
    <input class="fx-input" type="text" name="title" maxlength="300" required
           placeholder="e.g. How do I connect PPPHP to a PostgreSQL database?" value="<?= forum_e($vals['title']) ?>">
  </div>

  <div class="fx-field">
    <label>Details <span class="hint">what you tried, what happened — Markdown &amp; `code` welcome</span></label>
    <textarea class="fx-textarea" name="body" required placeholder="Describe your question in detail…"><?= forum_e($vals['body']) ?></textarea>
    <p class="fx-mdhint"><i class="bi bi-markdown"></i> Markdown supported: **bold**, `code`, - lists, &gt; quotes, [links](url)</p>
  </div>

  <div class="fx-row2">
    <div class="fx-field">
      <label>Category</label>
      <select class="fx-select" name="category">
        <option value="0">— none —</option>
        <?php foreach ($categories as $c): ?>
          <option value="<?= (int) $c['id'] ?>" <?= $vals['category'] === (int) $c['id'] ? 'selected' : '' ?>><?= forum_e($c['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="fx-field">
      <label>Tags <span class="hint">up to 5, comma-separated — press Enter or comma to add</span></label>
      <div class="fx-tagbox" id="fxTagbox">
        <input type="hidden" name="tags" id="fxTagsHidden" value="<?= forum_e($vals['tags']) ?>">
        <input type="text" class="fx-taginput" id="fxTagInput" placeholder="e.g. mysql, deployment, oracle" autocomplete="off" aria-label="Add a tag">
      </div>
    </div>
  </div>

  <button class="fx-submit" type="submit">Post your question</button>
</form>
<script>
(function () {
  var box = document.getElementById('fxTagbox'), input = document.getElementById('fxTagInput'), hidden = document.getElementById('fxTagsHidden');
  if (!box || !input || !hidden) return;
  var tags = [];
  function sync(){ hidden.value = tags.join(', '); }
  function render(){
    box.querySelectorAll('.fx-tagpill').forEach(function(n){ n.remove(); });
    tags.forEach(function(t){
      var pill = document.createElement('span'); pill.className = 'fx-tagpill';
      pill.innerHTML = t.replace(/[&<>"]/g, function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];}) + ' <button type="button" aria-label="Remove tag">×</button>';
      pill.querySelector('button').addEventListener('click', function(){ tags = tags.filter(function(x){return x!==t;}); render(); sync(); input.focus(); });
      box.insertBefore(pill, input);
    });
    sync();
  }
  function add(raw){
    (raw||'').split(',').forEach(function(part){
      var t = part.trim().toLowerCase().replace(/\s+/g,'-').replace(/[^a-z0-9-]/g,'');
      if (t && tags.indexOf(t) === -1 && tags.length < 5) tags.push(t);
    });
    input.value = ''; render();
  }
  input.addEventListener('keydown', function(e){
    if (e.key === ',' || e.key === 'Enter' || e.key === 'Tab') {
      if (input.value.trim()) { e.preventDefault(); add(input.value); }
    } else if (e.key === 'Backspace' && input.value === '' && tags.length) {
      tags.pop(); render();
    }
  });
  input.addEventListener('blur', function(){ if (input.value.trim()) add(input.value); });
  // seed from any prior value (validation re-render)
  if (hidden.value.trim()) add(hidden.value);
})();
</script>
<?php forum_foot(); ?>
