<div class="ticket-grid" style="grid-template-columns:1fr 300px">
  <div class="card">
    <div class="card-header"><h3>Raise a Support Ticket</h3></div>
    <div class="card-body">
      <form method="post" action="<?= url('/portal/tickets') ?>" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <div class="form-group">
          <label>Subject <span class="req">*</span></label>
          <input type="text" id="subject-input" name="subject" maxlength="200" required autocomplete="off">
        </div>

        <div id="deflect-box"></div>

        <div class="form-row">
          <div class="form-group">
            <label>Product / Module <span class="req">*</span></label>
            <select name="product_id" required>
              <?php foreach ($products as $p) : ?><option value="<?= $p['id'] ?>"><?= e($p['name']) ?> — <?= e($p['module']) ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Category <span class="req">*</span></label>
            <select name="category_id" required>
              <?php foreach ($categories as $c) : ?><option value="<?= $c['id'] ?>"><?= $c['parent_id'] ? '— ' : '' ?><?= e($c['name']) ?></option><?php endforeach; ?>
            </select>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label>Priority <span class="req">*</span></label>
            <select name="priority_id" required>
              <?php foreach ($priorities as $p) : ?><option value="<?= $p['id'] ?>"><?= e($p['code']) ?> — <?= e($p['name']) ?>: <?= e($p['definition']) ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Business impact</label>
            <select name="severity">
              <option>Business stopped</option><option selected>Minor impact</option><option>Major impact</option><option>Cosmetic</option>
            </select>
          </div>
        </div>

        <div class="form-group">
          <label>Description <span class="req">*</span></label>
          <textarea name="description" rows="6" required placeholder="What happened, when, and who is affected…"></textarea>
        </div>
        <div class="form-group">
          <label>Attachments <span class="help-text">max 10 MB per file</span></label>
          <input type="file" name="attachments[]" multiple data-file-preview="#att-preview">
          <div id="att-preview" class="help-text"></div>
        </div>

        <div class="flex justify-between">
          <a href="<?= url('/portal') ?>" class="btn">Cancel</a>
          <button type="submit" class="btn btn-primary">Submit ticket</button>
        </div>
      </form>
    </div>
  </div>

  <div class="side-panel">
    <div class="card">
      <div class="card-header"><h3>Your open tickets</h3></div>
      <div class="card-body">
        <?php if (empty($openTickets)) : ?>
          <p class="text-sm text-faint mb-0">You have no open tickets — if this is a new issue, go ahead and submit below.</p>
        <?php else : ?>
          <p class="text-sm text-faint">Already tracking this? Check before raising a duplicate.</p>
          <?php foreach ($openTickets as $t) : ?>
            <a href="<?= url('/portal/tickets/' . $t['id']) ?>" class="kb-suggestion">
              <div class="title mono" style="font-size:11.5px"><?= e($t['ticket_no']) ?> <span class="<?= status_badge_class($t['status']) ?>" style="margin-left:4px"><?= status_label($t['status']) ?></span></div>
              <div class="excerpt"><?= e($t['subject']) ?></div>
            </a>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<script>
(function () {
  var input = document.getElementById('subject-input');
  var box = document.getElementById('deflect-box');
  var timer = null;
  var csrf = document.querySelector('input[name=_csrf]').value;

  input.addEventListener('input', function () {
    clearTimeout(timer);
    var q = input.value.trim();
    if (q.length < 4) { box.innerHTML = ''; return; }
    timer = setTimeout(function () {
      fetch('<?= url('/portal/kb-search') ?>?q=' + encodeURIComponent(q))
        .then(function (r) { return r.json(); })
        .then(function (items) { renderBox(items); })
        .catch(function () {});
    }, 350);
  });

  function renderBox(items) {
    if (!items.length) { box.innerHTML = ''; return; }
    var html = '<div class="deflect-box"><strong>✓ ' + items.length + ' article(s) may already answer this</strong>';
    items.forEach(function (a) {
      html += '<div class="mt-2"><a href="' + a.url + '" target="_blank" rel="noopener" style="font-weight:600">' + escapeHtml(a.title) + '</a>' +
        ' — <button type="button" class="btn btn-sm" data-deflect="' + a.id + '">This solved my problem</button></div>';
    });
    html += '</div>';
    box.innerHTML = html;
    box.querySelectorAll('[data-deflect]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        var f = document.createElement('form');
        f.method = 'post'; f.action = '<?= url('/portal/kb-deflect') ?>';
        f.innerHTML = '<input type="hidden" name="_csrf" value="' + csrf + '"><input type="hidden" name="article_id" value="' + btn.getAttribute('data-deflect') + '">';
        document.body.appendChild(f);
        f.submit();
      });
    });
  }

  function escapeHtml(str) {
    return String(str || '').replace(/[&<>"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]; });
  }
})();
</script>
