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

$file = __DIR__ . '/../data/applications.txt';
$metaFile = __DIR__ . '/../data/application_status.json';
$meta = smurf_read_json($metaFile, []);
if (!is_array($meta)) $meta = [];
$action = $_GET['action'] ?? '';
$idx = isset($_GET['i']) ? (int)$_GET['i'] : -1;

$items = smurf_parse_blocks($file);
foreach ($items as $n => $item) {
  $items[$n]['_key'] = md5((string)($item['_raw'] ?? json_encode($item)));
}

if ($action === 'delete' && $idx >= 0) {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to delete entries.');
  if (isset($items[$idx]['_key'])) unset($meta[$items[$idx]['_key']]);
  smurf_write_json($metaFile, $meta);
  smurf_delete_block($file, $idx);
  header('Location: /admin/applications.php');
  exit;
}

if ($action === 'clear') {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to clear entries.');
  smurf_clear_file($file);
  smurf_write_json($metaFile, []);
  header('Location: /admin/applications.php');
  exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['application_key'])) {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to update applications.');
  $key = preg_replace('/[^a-f0-9]/', '', (string)($_POST['application_key'] ?? ''));
  if ($key !== '') {
    $meta[$key] = [
      'status' => trim((string)($_POST['status'] ?? 'new')) ?: 'new',
      'notes' => trim((string)($_POST['notes'] ?? '')),
      'updated_by' => (string)($_SESSION['user'] ?? 'admin'),
      'updated_at' => date('Y-m-d H:i:s'),
    ];
    smurf_write_json($metaFile, $meta);
  }
  header('Location: /admin/applications.php?saved=1');
  exit;
}

$q = smurf_q('q');
$status = strtolower(smurf_q('status', 'all'));
$filtered = array_values(array_filter($items, function($item) use ($q, $status, $meta) {
  $key = (string)($item['_key'] ?? '');
  $itemStatus = strtolower(trim((string)($meta[$key]['status'] ?? 'new')));
  $haystack = implode(' ', [
    (string)($item['Name'] ?? ''),
    (string)($item['Email'] ?? ''),
    (string)($item['Role'] ?? ''),
    (string)($item['Experience'] ?? ''),
    (string)($item['Why'] ?? ''),
    (string)($meta[$key]['notes'] ?? ''),
  ]);
  if (!smurf_match_text($haystack, $q)) return false;
  return $status === 'all' ? true : $itemStatus === $status;
}));
$counts = ['all' => count($items), 'new' => 0, 'shortlisted' => 0, 'rejected' => 0, 'archived' => 0];
foreach ($items as $item) {
  $key = (string)($item['_key'] ?? '');
  $s = strtolower(trim((string)($meta[$key]['status'] ?? 'new')));
  if (!isset($counts[$s])) $counts[$s] = 0;
  $counts[$s]++;
}
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">📝 Join Applications</h1>
  <p style="opacity:.8;">File: <code>/data/applications.txt</code></p>
  <?php if (!empty($_GET['saved'])): ?><div class="msg success">Application updated.</div><?php endif; ?>

  <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:12px 0 18px;">
    <div class="content-card"><strong><?= (int)$counts['all'] ?></strong><div>Total</div></div>
    <div class="content-card"><strong><?= (int)$counts['new'] ?></strong><div>New</div></div>
    <div class="content-card"><strong><?= (int)$counts['shortlisted'] ?></strong><div>Shortlisted</div></div>
    <div class="content-card"><strong><?= (int)$counts['rejected'] ?></strong><div>Rejected</div></div>
    <div class="content-card"><strong><?= (int)$counts['archived'] ?></strong><div>Archived</div></div>
  </div>

  <div style="margin:10px 0 18px; display:flex; gap:10px; flex-wrap:wrap; justify-content:space-between; align-items:center;">
    <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
      <input class="input-field" type="text" name="q" value="<?= smurf_h($q) ?>" placeholder="Search applicant, role or notes" style="min-width:220px;">
      <select class="input-field" name="status" style="min-width:160px;">
        <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All statuses</option>
        <option value="new" <?= $status === 'new' ? 'selected' : '' ?>>New</option>
        <option value="shortlisted" <?= $status === 'shortlisted' ? 'selected' : '' ?>>Shortlisted</option>
        <option value="rejected" <?= $status === 'rejected' ? 'selected' : '' ?>>Rejected</option>
        <option value="archived" <?= $status === 'archived' ? 'selected' : '' ?>>Archived</option>
      </select>
      <button class="admin-btn" type="submit">Filter</button>
      <?php if ($q !== '' || $status !== 'all'): ?><a class="admin-btn" href="/admin/applications.php">Reset</a><?php endif; ?>
    </form>
    <div style="display:flex;gap:10px;flex-wrap:wrap;">
      <?php if ($CAN_EDIT): ?><a class="admin-btn" href="/admin/applications.php?action=clear" onclick="return confirm('Clear ALL entries?');">Clear All</a><?php endif; ?>
      <a class="admin-btn" href="/admin/index.php">Back</a>
    </div>
  </div>

  <div class="content-card" style="text-align:left;">
    <?php if (empty($filtered)): ?>
      <p>No applications match this view.</p>
    <?php else: ?>
      <?php foreach ($filtered as $n => $item): $key=(string)$item['_key']; $appMeta = $meta[$key] ?? ['status' => 'new', 'notes' => '']; $appStatus = strtolower(trim((string)($appMeta['status'] ?? 'new'))) ?: 'new'; ?>
        <div class="content-card" style="text-align:left; margin-bottom:14px;">
          <div style="display:flex; justify-content:space-between; gap:12px; align-items:flex-start; flex-wrap:wrap;">
            <div style="flex:1; min-width:320px;">
              <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
                <h3 style="margin:0 0 8px;"><?= smurf_h((string)($item['Name'] ?? 'Applicant')) ?></h3>
                <span class="badge" style="background:rgba(255,255,255,.08);padding:4px 8px;border-radius:999px;"><?= smurf_h(ucfirst($appStatus)) ?></span>
              </div>
              <?php if (!empty($item['Email'])): ?><div><strong>Email:</strong> <?= smurf_h((string)$item['Email']) ?></div><?php endif; ?>
              <?php if (!empty($item['Role'])): ?><div><strong>Role:</strong> <?= smurf_h((string)$item['Role']) ?></div><?php endif; ?>
              <?php if (!empty($item['Experience'])): ?><div><strong>Experience:</strong> <?= smurf_h((string)$item['Experience']) ?></div><?php endif; ?>
              <?php if (!empty($item['Why'])): ?><div style="margin-top:10px;"><strong>Why they want to join:</strong><br><?= nl2br(smurf_h((string)$item['Why'])) ?></div><?php endif; ?>
              <?php if (!empty($item['Demo'])): ?><?php $demoName=(string)$item['Demo']; $demoUrl='/uploads/demos/' . rawurlencode($demoName); ?><div style="margin-top:10px;"><strong>Demo:</strong> <?= smurf_h($demoName) ?></div><div style="margin-top:8px; display:flex; gap:10px; flex-wrap:wrap; align-items:center;"><audio controls preload="none" src="<?= smurf_h($demoUrl) ?>"></audio><a class="admin-btn" href="<?= smurf_h($demoUrl) ?>" target="_blank" rel="noopener">Listen to Demo</a><a class="admin-btn" href="<?= smurf_h($demoUrl) ?>" download>Download Demo</a></div><?php endif; ?>
              <?php if (!empty($appMeta['updated_at'])): ?><div style="margin-top:10px;opacity:.75;">Last updated: <?= smurf_h((string)$appMeta['updated_at']) ?><?= !empty($appMeta['updated_by']) ? ' by ' . smurf_h((string)$appMeta['updated_by']) : '' ?></div><?php endif; ?>
            </div>
            <div style="flex:1;min-width:280px;">
              <?php if ($CAN_EDIT): ?>
                <form method="post">
                  <input type="hidden" name="application_key" value="<?= smurf_h($key) ?>">
                  <label>Status</label>
                  <select class="input-field" name="status">
                    <option value="new" <?= $appStatus === 'new' ? 'selected' : '' ?>>New</option>
                    <option value="shortlisted" <?= $appStatus === 'shortlisted' ? 'selected' : '' ?>>Shortlisted</option>
                    <option value="rejected" <?= $appStatus === 'rejected' ? 'selected' : '' ?>>Rejected</option>
                    <option value="archived" <?= $appStatus === 'archived' ? 'selected' : '' ?>>Archived</option>
                  </select>
                  <label>Notes</label>
                  <textarea class="input-field" name="notes" rows="5" placeholder="Private admin notes"><?= smurf_h((string)($appMeta['notes'] ?? '')) ?></textarea>
                  <div style="display:flex;gap:10px;justify-content:space-between;flex-wrap:wrap;">
                    <button class="admin-btn" type="submit">Save Status</button>
                    <a class="admin-btn" href="/admin/applications.php?action=delete&i=<?= (int)array_search($item, $items, true) ?>" onclick="return confirm('Delete this application?');">Delete</a>
                  </div>
                </form>
              <?php endif; ?>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
