<?php
require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/db.php';
require_once __DIR__ . '/../lib/layout.php';
require_login();

$user_id = current_user()['id'];

$stmt = db()->prepare('SELECT * FROM requests_benefitsantrag WHERE user_id = ? ORDER BY created_at DESC');
$stmt->execute([$user_id]);
$requests = $stmt->fetchAll();

$benefit_labels = [
    'yoga'               => 'Yoga',
    'autogenes_training' => 'Autogenes Training',
    'massage'            => 'Massage',
    'tankgutschein'      => 'Tankgutschein',
    'online_gutscheine'  => 'Online-Gutscheine',
];

$status_labels = ['pending' => 'Ausstehend', 'accepted' => 'Akzeptiert', 'rejected' => 'Abgelehnt'];

layout_start('OMSORG – Benefitsantrag', 'benefitsantrag');
?>
<style>
.modal-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.55);display:none;align-items:center;justify-content:center;z-index:1000}
.modal-box{background:var(--glass-bg,#1e2235);border:1px solid var(--border,rgba(255,255,255,.1));border-radius:14px;padding:28px 32px;max-width:480px;width:90%;position:relative}
.modal-box h3{margin:0 0 20px;font-family:'KindelSerif',Georgia,serif;font-size:1.3rem}
.modal-close{position:absolute;top:12px;right:16px;background:none;border:none;font-size:1.5rem;cursor:pointer;color:var(--muted,#888);line-height:1}
.modal-dl{display:grid;grid-template-columns:auto 1fr;gap:8px 16px;font-size:.95rem}
.modal-dl dt{color:var(--muted,#888);white-space:nowrap}
.modal-dl dd{margin:0;font-weight:500}
.btn-sm{display:inline-flex;align-items:center;gap:6px;padding:7px 13px;border-radius:9px;border:1px solid rgba(255,255,255,.2);background:rgba(255,255,255,.08);color:#fff;font-weight:600;font-size:.82rem;cursor:pointer;font:inherit;transition:background .15s}
.btn-sm:hover{background:rgba(255,255,255,.15)}
</style>

<h1 class="main-title">🎁 Benefitsantrag</h1>
<p class="main-sub">Beantrage einen Mitarbeiterbenefit deiner Wahl.</p>

<?php if (isset($_GET['success'])): ?>
  <div class="success" style="margin-top:16px">Antrag erfolgreich eingereicht.</div>
<?php elseif (isset($_GET['error'])): ?>
  <div class="error" style="margin-top:16px"><?= e(urldecode($_GET['error'])) ?></div>
<?php endif; ?>

<div id="ben-modal" class="modal-backdrop" onclick="if(event.target===this)this.style.display='none'">
  <div class="modal-box glass">
    <button class="modal-close" onclick="document.getElementById('ben-modal').style.display='none'">&times;</button>
    <h3>Antrag Details</h3>
    <dl class="modal-dl">
      <dt>Benefit</dt>    <dd id="ben-benefit">–</dd>
      <dt>Nachricht</dt>  <dd id="ben-nachricht">–</dd>
      <dt>Eingereicht</dt><dd id="ben-eingereicht">–</dd>
      <dt>Status</dt>     <dd id="ben-status">–</dd>
      <dt>Admin-Notiz</dt><dd id="ben-note">–</dd>
    </dl>
  </div>
</div>

<div id="liberty-modal" class="modal-backdrop" onclick="if(event.target===this)this.style.display='none'">
  <div class="modal-box glass" style="max-width:600px;padding:16px;text-align:center">
    <button class="modal-close" onclick="document.getElementById('liberty-modal').style.display='none'">&times;</button>
    <div class="success" style="margin:0 0 14px">Antrag erfolgreich eingereicht.</div>
    <img src="../assets/Liberty.jpeg" alt="Liberty" style="width:100%;border-radius:10px;display:block">
  </div>
</div>

<div class="page-split">

  <div class="page-split-list">
    <h2>Meine Anträge</h2>
    <?php if (empty($requests)): ?>
      <p style="color:var(--muted)">Noch keine Anträge gestellt.</p>
    <?php else: ?>
      <table class="requests-table">
        <thead>
          <tr>
            <th>Benefit</th>
            <th>Status</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($requests as $r): ?>
          <tr>
            <td style="font-weight:800"><?= e($benefit_labels[$r['benefit']] ?? $r['benefit']) ?></td>
            <td><span class="badge badge-<?= e($r['status']) ?>"><?= e($status_labels[$r['status']] ?? $r['status']) ?></span></td>
            <td>
              <button class="btn-sm js-ben-details"
                data-benefit="<?= e($benefit_labels[$r['benefit']] ?? $r['benefit']) ?>"
                data-nachricht="<?= e($r['nachricht'] !== '' ? $r['nachricht'] : '–') ?>"
                data-eingereicht="<?= e(date('d.m.Y', strtotime($r['created_at']))) ?>"
                data-status-label="<?= e($status_labels[$r['status']] ?? $r['status']) ?>"
                data-status-key="<?= e($r['status']) ?>"
                data-note="<?= e($r['admin_note'] !== '' ? $r['admin_note'] : '–') ?>"
              >Details</button>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>

  <div class="page-split-form">
    <div class="glass detail-card">
      <h2>Neuer Benefitsantrag</h2>
      <form id="benefits-form" action="../actions/submit-benefitsantrag.php" method="post">
        <?= csrf_field() ?>
        <label>
          <span>Benefit <span style="color:#ff8080">*</span></span>
          <select name="benefit" required>
            <option value="">– Bitte wählen –</option>
            <option value="yoga">Yoga</option>
            <option value="autogenes_training">Autogenes Training</option>
            <option value="massage">Massage</option>
            <option value="tankgutschein">Tankgutschein</option>
            <option value="online_gutscheine">Online-Gutscheine</option>
          </select>
        </label>
        <label>
          Nachricht
          <textarea name="nachricht" rows="4" placeholder="Optionale Anmerkungen"></textarea>
        </label>
        <div id="benefits-form-error" class="error" style="display:none;margin-top:8px"></div>
        <button type="submit" class="btn" style="margin-top:6px">Antrag einreichen</button>
      </form>
    </div>
  </div>

</div>
<script>
var LIBERTY_BENEFITS = ['autogenes_training', 'massage'];

document.getElementById('benefits-form').addEventListener('submit', function(e) {
  var benefit = this.querySelector('[name="benefit"]').value;
  if (!LIBERTY_BENEFITS.includes(benefit)) return; // normal submit for other benefits
  e.preventDefault();
  var form = this;
  var btn = form.querySelector('[type="submit"]');
  btn.disabled = true;
  var errEl = document.getElementById('benefits-form-error');
  errEl.style.display = 'none';
  fetch(form.action, {
    method: 'POST',
    body: new FormData(form),
    headers: { 'X-Requested-With': 'XMLHttpRequest' }
  }).then(function(r) { return r.json(); }).then(function(data) {
    btn.disabled = false;
    if (data.ok) {
      form.reset();
      document.getElementById('liberty-modal').style.display = 'flex';
    } else {
      errEl.textContent = data.error || 'Ein Fehler ist aufgetreten.';
      errEl.style.display = 'block';
    }
  }).catch(function() {
    btn.disabled = false;
    errEl.textContent = 'Ein Fehler ist aufgetreten. Bitte erneut versuchen.';
    errEl.style.display = 'block';
  });
});

document.addEventListener('click', function(e) {
  var btn = e.target.closest('.js-ben-details');
  if (!btn) return;
  var d = btn.dataset;
  document.getElementById('ben-benefit').textContent    = d.benefit;
  document.getElementById('ben-nachricht').textContent  = d.nachricht;
  document.getElementById('ben-eingereicht').textContent= d.eingereicht;
  document.getElementById('ben-status').innerHTML =
    '<span class="badge badge-' + d.statusKey + '">' + d.statusLabel + '</span>';
  document.getElementById('ben-note').textContent       = d.note;
  document.getElementById('ben-modal').style.display = 'flex';
});
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') {
    document.getElementById('ben-modal').style.display = 'none';
    document.getElementById('liberty-modal').style.display = 'none';
  }
});
</script>
<?php layout_end(); ?>
