<?php
session_start();
require __DIR__ . '/config.php';
ensure_data_files();

if (isset($_GET['logout'])) {
    unset($_SESSION['admin']);
    header('Location: ' . site_url('admin.php'));
    exit;
}

$loginError = '';
if (isset($_POST['login'])) {
    if (($_POST['username'] ?? '') === ADMIN_USER && ($_POST['password'] ?? '') === ADMIN_PASS) {
        $_SESSION['admin'] = true;
        header('Location: ' . site_url('admin.php'));
        exit;
    }
    $loginError = 'Wrong username or password.';
}

if (empty($_SESSION['admin'])) {
    ?>
    <!doctype html>
    <html lang="en"><head>
    <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Admin Login</title>
    <style>
    body{margin:0;font-family:Arial,sans-serif;background:#110703;color:#fff;display:grid;place-items:center;min-height:100vh}
    .box{width:min(92vw,420px);background:#1a0b06;border:1px solid rgba(255,200,0,.18);padding:28px;border-radius:24px}
    input,button{width:100%;padding:12px;margin:8px 0;border-radius:12px;border:0}
    button{background:#ffcb47;font-weight:700;cursor:pointer}.err{color:#ff8f8f}
    </style></head><body><div class="box">
    <h1>Admin Login</h1>
    <?php if ($loginError): ?><div class="err"><?= e($loginError) ?></div><?php endif; ?>
    <form method="post">
      <input type="text" name="username" placeholder="Username" required>
      <input type="password" name="password" placeholder="Password" required>
      <button type="submit" name="login">Login</button>
    </form>
    <p><a style="color:#ffcb47" href="<?= e(site_url('index.php')) ?>">Back to site</a></p>
    </div></body></html>
    <?php
    exit;
}

$settings = get_settings();
$submissions = get_submissions();
$message = '';

if (isset($_POST['save_settings'])) {
    $stations = preg_split('/\r\n|\r|\n/', trim($_POST['stations'] ?? '')) ?: [];
    $platforms = preg_split('/\r\n|\r|\n/', trim($_POST['platforms'] ?? '')) ?: [];

    $settings['event_name'] = trim($_POST['event_name'] ?? '');
    $settings['headline'] = trim($_POST['headline'] ?? '');
    $settings['poster'] = trim($_POST['poster'] ?? 'assets/poster.png');
    $settings['pot'] = (int) ($_POST['pot'] ?? 0);
    $settings['date_range'] = trim($_POST['date_range'] ?? '');
    $settings['description'] = trim($_POST['description'] ?? '');
    $settings['cta_text'] = trim($_POST['cta_text'] ?? '');
    $settings['cta_url'] = trim($_POST['cta_url'] ?? '');
    $settings['form_title'] = trim($_POST['form_title'] ?? 'Submit Your Answer');
    $settings['success_message'] = trim($_POST['success_message'] ?? 'Thanks. Your answer has been received.');
    $settings['answer_page_open'] = isset($_POST['answer_page_open']);
    $settings['stations'] = array_values(array_filter(array_map('trim', $stations)));
    $settings['platforms'] = array_values(array_filter(array_map('trim', $platforms)));

    save_settings($settings);
    $message = 'Settings saved.';
}

if (isset($_POST['delete_submission'])) {
    $index = (int) $_POST['delete_submission'];
    if (isset($submissions[$index])) {
        unset($submissions[$index]);
        save_submissions($submissions);
        $submissions = get_submissions();
        $message = 'Submission deleted.';
    }
}

if (isset($_POST['clear_submissions'])) {
    save_submissions([]);
    $submissions = [];
    $message = 'All submissions cleared.';
}

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="submissions.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Name', 'Artist', 'Song', 'Email', 'Platform', 'IP', 'Timestamp']);
    foreach ($submissions as $row) {
        fputcsv($out, [
            $row['name'] ?? '',
            $row['artist'] ?? '',
            $row['song'] ?? '',
            $row['email'] ?? '',
            $row['platform'] ?? '',
            $row['ip'] ?? '',
            $row['timestamp'] ?? ''
        ]);
    }
    fclose($out);
    exit;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Event Admin</title>
<style>
*{box-sizing:border-box}
html,body{margin:0;overflow-x:hidden}
body{font-family:Arial,sans-serif;background:#120703;color:#fff7e7}
.wrap{max-width:1200px;margin:0 auto;padding:22px}
.grid{display:grid;grid-template-columns:minmax(320px,380px) minmax(0,1fr);gap:22px;align-items:start}
.card{background:#1b0d08;border:1px solid rgba(255,194,74,.18);border-radius:22px;padding:20px;box-shadow:0 18px 40px rgba(0,0,0,.32);min-width:0}
form{display:block;min-width:0}
input,textarea,select,button{display:block;width:100%;max-width:100%;padding:11px 12px;border-radius:12px;border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.06);color:#fff;margin-top:8px;font:inherit}
textarea{min-height:90px;resize:vertical}
button{cursor:pointer;background:#ffcb47;color:#221000;font-weight:800;border:0}
.smallbtn{width:auto;display:inline-block;padding:10px 14px;margin:4px 8px 4px 0}
label{display:block;margin-top:12px;font-weight:700}
label input[type=checkbox]{display:inline-block;width:auto;max-width:none;margin:0 8px 0 0;vertical-align:middle}
table{width:100%;border-collapse:collapse;font-size:.95rem;table-layout:auto}
th,td{padding:10px;border-bottom:1px solid rgba(255,255,255,.08);text-align:left;vertical-align:top;word-break:break-word}
.badge{display:inline-block;padding:8px 12px;border-radius:999px;background:#234b10;color:#ddff95;font-weight:700}.off{background:#4c1b1b;color:#ffb8b8}
.topbar{display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:16px}.msg{margin-bottom:14px;color:#aff5a8}.muted{opacity:.8}
.table-wrap{overflow:auto;margin-top:10px}
@media (max-width: 980px){.grid{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="wrap">
  <div class="topbar">
    <div>
      <h1 style="margin:0 0 6px">Event Admin</h1>
      <div class="muted">Control the answer page, update the event details, and manage submissions without the form fields spilling outside the panel.</div>
    </div>
    <div>
      <a class="smallbtn" style="background:#2d1a06;color:#ffd25a;text-decoration:none;border-radius:999px" href="<?= e(site_url('index.php')) ?>">View Site</a>
      <a class="smallbtn" style="background:#2d1a06;color:#ffd25a;text-decoration:none;border-radius:999px" href="<?= e(site_url('admin.php')) ?>?export=csv">Export CSV</a>
      <a class="smallbtn" style="background:#441010;color:#fff4f4;text-decoration:none;border-radius:999px" href="<?= e(site_url('admin.php')) ?>?logout=1">Logout</a>
    </div>
  </div>

  <?php if ($message): ?><div class="msg"><?= e($message) ?></div><?php endif; ?>

  <div class="grid">
    <div class="card">
      <h2>Event Settings</h2>
      <p>Status:
        <?php if (!empty($settings['answer_page_open'])): ?>
          <span class="badge">Answer Page Open</span>
        <?php else: ?>
          <span class="badge off">Answer Page Closed</span>
        <?php endif; ?>
      </p>

      <form method="post">
        <label>Event Name</label>
        <input type="text" name="event_name" value="<?= e($settings['event_name'] ?? '') ?>">

        <label>Headline</label>
        <input type="text" name="headline" value="<?= e($settings['headline'] ?? '') ?>">

        <label>Poster Path</label>
        <input type="text" name="poster" value="<?= e($settings['poster'] ?? '') ?>">

        <label>Current Pot</label>
        <input type="number" name="pot" value="<?= e((string) ($settings['pot'] ?? 0)) ?>">

        <label>Date Range</label>
        <input type="text" name="date_range" value="<?= e($settings['date_range'] ?? '') ?>">

        <label>Description</label>
        <textarea name="description"><?= e($settings['description'] ?? '') ?></textarea>

        <label>CTA Text</label>
        <input type="text" name="cta_text" value="<?= e($settings['cta_text'] ?? '') ?>">

        <label>CTA URL</label>
        <input type="text" name="cta_url" value="<?= e($settings['cta_url'] ?? '') ?>">

        <label>Form Title</label>
        <input type="text" name="form_title" value="<?= e($settings['form_title'] ?? '') ?>">

        <label>Success Message</label>
        <input type="text" name="success_message" value="<?= e($settings['success_message'] ?? '') ?>">

        <label>Stations (one per line)</label>
        <textarea name="stations"><?= e(implode("\n", $settings['stations'] ?? [])) ?></textarea>

        <label>Platforms (one per line)</label>
        <textarea name="platforms"><?= e(implode("\n", $settings['platforms'] ?? [])) ?></textarea>

        <label><input style="width:auto;margin-right:8px" type="checkbox" name="answer_page_open" <?= !empty($settings['answer_page_open']) ? 'checked' : '' ?>> Open answer page now</label>

        <button type="submit" name="save_settings">Save Settings</button>
      </form>
    </div>

    <div class="card">
      <h2>Submissions (<?= count($submissions) ?>)</h2>
      <form method="post" onsubmit="return confirm('Clear all submissions?');">
        <button class="smallbtn" type="submit" name="clear_submissions">Clear All</button>
      </form>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Artist</th>
              <th>Song</th>
              <th>Email</th>
              <th>Platform</th>
              <th>IP</th>
              <th>Timestamp</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php if (!$submissions): ?>
              <tr><td colspan="8">No submissions yet.</td></tr>
            <?php endif; ?>
            <?php foreach ($submissions as $i => $row): ?>
              <tr>
                <td><?= e($row['name'] ?? '') ?></td>
                <td><?= e($row['artist'] ?? '') ?></td>
                <td><?= e($row['song'] ?? '') ?></td>
                <td><?= e($row['email'] ?? '') ?></td>
                <td><?= e($row['platform'] ?? '') ?></td>
                <td><?= e($row['ip'] ?? '') ?></td>
                <td><?= e($row['timestamp'] ?? '') ?></td>
                <td>
                  <form method="post" onsubmit="return confirm('Delete this submission?');">
                    <input type="hidden" name="delete_submission" value="<?= $i ?>">
                    <button class="smallbtn" type="submit">Delete</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
</body>
</html>
