<?php
session_start();
require __DIR__ . '/auth.php';
require __DIR__ . '/includes/admin_lib.php';

$file = __DIR__ . '/../data/applications.txt';

function thunder_app_parse(string $file): array {
  $items = smurf_parse_blocks($file);
  $out = [];
  foreach ($items as $item) {
    $name = trim((string)($item['Name'] ?? ''));
    $email = trim((string)($item['Email'] ?? ''));
    $role = trim((string)($item['Role'] ?? ''));
    $experience = trim((string)($item['Experience'] ?? ''));
    $why = trim((string)($item['Why'] ?? ''));
    $demo = trim((string)($item['Demo'] ?? ''));
    if ($name === '' && $email === '' && $role === '' && $experience === '' && $why === '' && $demo === '') continue;
    $item['_key'] = md5(str_replace("\r", '', (string)($item['_raw'] ?? '')));
    $out[] = $item;
  }
  return $out;
}
function thunder_app_write(string $file, array $items): void {
  $blocks = [];
  foreach (array_reverse($items) as $item) {
    $raw = trim((string)($item['_raw'] ?? ''));
    if ($raw !== '') $blocks[] = $raw;
  }
  file_put_contents($file, $blocks ? implode("\n---\n", $blocks) . "\n---\n" : '', LOCK_EX);
}
function thunder_field(array $item, string $key): string { return trim((string)($item[$key] ?? '')); }
function thunder_demo_url(string $demo): string {
  $demo = trim($demo);
  if ($demo === '') return '';
  if (preg_match('~^(https?:)?//~i', $demo) || strpos($demo, '/') === 0 || strpos($demo, '../') === 0) return $demo;
  return '../uploads/demos/' . rawurlencode($demo);
}

$items = thunder_app_parse($file);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to manage applications.</p>");
  if (isset($_POST['clear_all'])) {
    thunder_app_write($file, []);
    header('Location: applications.php?saved=1');
    exit;
  }
  if (isset($_POST['delete_key'])) {
    $deleteKey = trim((string)($_POST['delete_key'] ?? ''));
    $items = array_values(array_filter($items, fn($item) => (string)($item['_key'] ?? '') !== $deleteKey));
    thunder_app_write($file, $items);
    header('Location: applications.php?saved=1');
    exit;
  }
}
$items = thunder_app_parse($file);
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap;">
    <div>
      <h1 class="admin-title" style="margin:0;">📝 Join Applications</h1>
      <p style="opacity:.82;margin:8px 0 0;">Applications submitted from the public Join page. File: <code>/data/applications.txt</code></p>
    </div>
    <div class="admin-actions">
      <?php if ($CAN_EDIT): ?>
      <form method="post" onsubmit="return confirm('Clear ALL entries?');" style="margin:0;display:inline-block;">
        <input type="hidden" name="clear_all" value="1">
        <button class="admin-btn danger" type="submit">Clear All</button>
      </form>
      <?php endif; ?>
      <a class="admin-btn" href="index.php">Back</a>
    </div>
  </div>
  <?php if (!empty($_GET['saved'])): ?><div class="msg success" style="margin-top:12px;">Saved.</div><?php endif; ?>
  <?php if (empty($items)): ?>
    <div class="content-card" style="margin-top:16px;text-align:left;"><p style="margin:0;">No applications yet.</p></div>
  <?php else: ?>
    <div class="admin-entry-list" style="margin-top:18px;">
      <?php foreach ($items as $item): ?>
        <?php $name = thunder_field($item, 'Name'); $email = thunder_field($item, 'Email'); $role = thunder_field($item, 'Role'); $experience = thunder_field($item, 'Experience'); $why = thunder_field($item, 'Why'); $demo = thunder_field($item, 'Demo'); $demoUrl = thunder_demo_url($demo); ?>
        <article class="content-card admin-entry-card">
          <div class="admin-entry-head">
            <div>
              <h3 style="margin:0 0 4px;"><?= smurf_h($name !== '' ? $name : 'Application') ?></h3>
              <div class="admin-entry-tags">
                <?php if ($role !== ''): ?><span class="admin-entry-tag"><?= smurf_h($role) ?></span><?php endif; ?>
                <?php if ($experience !== ''): ?><span class="admin-entry-tag"><?= smurf_h($experience) ?></span><?php endif; ?>
              </div>
            </div>
            <?php if ($CAN_EDIT): ?>
            <form method="post" onsubmit="return confirm('Delete this entry?');" style="margin:0;">
              <input type="hidden" name="delete_key" value="<?= smurf_h((string)($item['_key'] ?? '')) ?>">
              <button class="admin-btn" type="submit">Delete</button>
            </form>
            <?php endif; ?>
          </div>
          <div class="admin-entry-grid">
            <?php if ($email !== ''): ?><div class="admin-entry-field"><span class="admin-entry-label">Email</span><div><?= smurf_h($email) ?></div></div><?php endif; ?>
            <?php if ($role !== ''): ?><div class="admin-entry-field"><span class="admin-entry-label">Requested Role</span><div><?= smurf_h($role) ?></div></div><?php endif; ?>
            <?php if ($experience !== ''): ?><div class="admin-entry-field"><span class="admin-entry-label">Experience</span><div><?= smurf_h($experience) ?></div></div><?php endif; ?>
            <?php if ($demo !== ''): ?><div class="admin-entry-field"><span class="admin-entry-label">Demo File</span><div style="word-break:break-word;"><?= smurf_h($demo) ?></div></div><?php endif; ?>
          </div>
          <?php if ($demoUrl !== ''): ?>
            <div class="admin-entry-body" style="margin-bottom:12px;">
              <span class="admin-entry-label">Demo Audio</span>
              <audio controls preload="none" style="width:100%;max-width:520px;display:block;"><source src="<?= smurf_h($demoUrl) ?>">Your browser cannot play this file.</audio>
              <div class="admin-actions" style="margin-top:12px;"><a class="admin-btn" href="<?= smurf_h($demoUrl) ?>" target="_blank" rel="noopener">Open Demo</a><a class="admin-btn" href="<?= smurf_h($demoUrl) ?>" download>Download Demo</a></div>
            </div>
          <?php endif; ?>
          <?php if ($why !== ''): ?><div class="admin-entry-body"><span class="admin-entry-label">Why they want to join</span><p><?= nl2br(smurf_h($why)) ?></p></div><?php endif; ?>
        </article>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
