<?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>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@400;600;700&family=Inter:wght@400;500;700&display=swap" rel="stylesheet">
<style>
body{margin:0;font-family:Inter,Arial,sans-serif;background:linear-gradient(180deg,#050608,#0b0d12);color:#eef6ff;display:grid;place-items:center;min-height:100vh;padding:18px}
.box{width:min(92vw,460px);background:rgba(10,11,16,.9);border:1px solid rgba(255,170,68,.22);padding:28px;border-radius:28px;box-shadow:0 28px 70px rgba(0,0,0,.45)}
h1{font-family:Oswald,Arial,sans-serif;margin:0 0 10px}
input,button{width:100%;max-width:100%;padding:13px 14px;margin:8px 0;border-radius:14px}
input{border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.06);color:#eef6ff}
button{background:linear-gradient(180deg,#ffb347,#ff7f11);font-weight:800;border:0;cursor:pointer;color:#210d00}
.err{color:#ff9f9f;margin-bottom:6px}
a{color:#ffd391}
</style></head><body><div class="box">
<h1>BroadcastUrSelf Admin</h1>
<p>Manage the main site, active event, and submission form.</p>
<?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">Log In</button>
</form>
<p><a href="<?= e(site_url('index.php')) ?>">Back to site</a></p>
</div></body></html>
<?php
    exit;
}

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

function textarea_to_array(string $value): array {
    $lines = preg_split('/\r\n|\r|\n/', trim($value)) ?: [];
    return array_values(array_filter(array_map('trim', $lines)));
}

function blocks_to_text(array $blocks): string {
    $rows = [];
    foreach ($blocks as $block) {
        $rows[] = trim(($block['title'] ?? '') . ' | ' . ($block['text'] ?? ''));
    }
    return implode("\n", array_filter($rows));
}

function text_to_blocks(string $value): array {
    $lines = preg_split('/\r\n|\r|\n/', trim($value)) ?: [];
    $blocks = [];
    foreach ($lines as $line) {
        if (trim($line) === '') continue;
        $parts = explode('|', $line, 2);
        $blocks[] = [
            'title' => trim($parts[0] ?? ''),
            'text' => trim($parts[1] ?? '')
        ];
    }
    return $blocks;
}

if (isset($_POST['save_settings'])) {
    $keys = [
        'site_name','site_tagline','site_logo','site_intro','community_blurb','footer_note',
        'primary_button_label','primary_button_url','secondary_button_label','station_heading',
        'event_type','event_name','headline','event_poster','pot_label','pot_value','date_range',
        'description','how_it_works','event_notice','cta_text','status_text',
        'submission_button_text','submission_title','submission_intro','success_message',
        'entry_type_label','field_one_label','field_one_placeholder','field_two_label','field_two_placeholder',
        'field_message_label','field_message_placeholder','name_label','email_label','platform_label'
    ];

    foreach ($keys as $key) {
        $settings[$key] = trim($_POST[$key] ?? '');
    }

    $settings['event_active'] = isset($_POST['event_active']);
    $settings['show_prize_box'] = isset($_POST['show_prize_box']);
    $settings['show_submission_button'] = isset($_POST['show_submission_button']);
    $settings['submission_page_open'] = isset($_POST['submission_page_open']);

    $settings['stations'] = textarea_to_array($_POST['stations'] ?? '');
    $settings['platforms'] = textarea_to_array($_POST['platforms'] ?? '');
    $settings['entry_type_options'] = textarea_to_array($_POST['entry_type_options'] ?? '');
    $settings['featured_blocks'] = text_to_blocks($_POST['featured_blocks'] ?? '');

    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="broadcasturself-submissions.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Entry Type', 'Field One', 'Field Two', 'Message', 'Name', 'Email', 'Platform', 'IP', 'Timestamp']);
    foreach ($submissions as $row) {
        fputcsv($out, [
            $row['entry_type'] ?? '',
            $row['field_one'] ?? '',
            $row['field_two'] ?? '',
            $row['message_text'] ?? '',
            $row['name'] ?? '',
            $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>BroadcastUrSelf Admin</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@400;600;700&family=Inter:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root{
  --bg:#050608;--panel:rgba(10,11,16,.9);--panel2:rgba(255,255,255,.03);--line:rgba(255,170,68,.22);
  --text:#eef6ff;--muted:rgba(238,246,255,.74);--gold:#ffb347;--gold2:#ff7f11;
}
*{box-sizing:border-box}
body{
  margin:0;font-family:Inter,system-ui,sans-serif;color:var(--text);
  background:linear-gradient(180deg,#050608,#0b0d12)
}
.wrap{max-width:1380px;margin:0 auto;padding:22px 18px 50px}
.top{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:18px}
.top a{color:#ffd391}
.grid{display:grid;grid-template-columns:1.2fr .8fr;gap:20px}
.panel{
  background:var(--panel);border:1px solid var(--line);border-radius:28px;padding:22px;
  box-shadow:0 28px 70px rgba(0,0,0,.35);overflow:hidden
}
.stack{display:grid;gap:20px}
h1,h2,h3{font-family:Oswald,Inter,sans-serif;line-height:1.05;margin:0 0 12px}
p{color:var(--muted)}
label{display:block;margin:12px 0 6px;font-weight:700}
input,textarea,select{
  width:100%;max-width:100%;padding:12px 14px;border-radius:14px;
  border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.06);color:var(--text)
}
textarea{min-height:110px;resize:vertical}
.row{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.row3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px}
.checks{display:flex;gap:18px;flex-wrap:wrap;margin-top:8px}
.checks label{display:flex;align-items:center;gap:8px;margin:0;font-weight:600}
.checks input{width:auto}
button,.button{
  display:inline-flex;align-items:center;justify-content:center;
  padding:13px 18px;border-radius:999px;border:0;cursor:pointer;font-weight:800;
  background:linear-gradient(180deg,var(--gold),var(--gold2));color:#210d00;text-decoration:none
}
.button.secondary, button.secondary{
  background:rgba(255,255,255,.08);color:var(--text);border:1px solid rgba(255,255,255,.09)
}
.msg{margin:0 0 14px;padding:12px 14px;border-radius:14px;background:rgba(36,121,24,.25);border:1px solid rgba(126,217,87,.28)}
.table-wrap{overflow:auto}
table{width:100%;border-collapse:collapse;min-width:900px}
th,td{padding:12px;border-bottom:1px solid rgba(255,255,255,.08);text-align:left;vertical-align:top}
td form{margin:0}
.small{font-size:.92rem;color:var(--muted)}
@media (max-width:1100px){.grid{grid-template-columns:1fr}}
@media (max-width:760px){.row,.row3{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="wrap">
  <div class="top">
    <div>
      <h1>BroadcastUrSelf Admin</h1>
      <p>Control the main site, the featured event, and the submission form from one place.</p>
    </div>
    <div style="display:flex;gap:10px;flex-wrap:wrap">
      <a class="button secondary" href="<?= e(site_url('index.php')) ?>">View Site</a>
      <a class="button secondary" href="<?= e(site_url('admin.php?logout=1')) ?>">Log Out</a>
    </div>
  </div>

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

  <div class="grid">
    <div class="stack">
      <div class="panel">
        <h2>Site & event settings</h2>
        <form method="post">
          <h3>Main branding</h3>
          <div class="row">
            <div>
              <label>Site Name</label>
              <input type="text" name="site_name" value="<?= e($settings['site_name'] ?? '') ?>">
            </div>
            <div>
              <label>Site Tagline</label>
              <input type="text" name="site_tagline" value="<?= e($settings['site_tagline'] ?? '') ?>">
            </div>
          </div>

          <div class="row">
            <div>
              <label>Site Logo Path</label>
              <input type="text" name="site_logo" value="<?= e($settings['site_logo'] ?? '') ?>">
            </div>
            <div>
              <label>Footer Note</label>
              <input type="text" name="footer_note" value="<?= e($settings['footer_note'] ?? '') ?>">
            </div>
          </div>

          <label>Site Intro</label>
          <textarea name="site_intro"><?= e($settings['site_intro'] ?? '') ?></textarea>

          <label>Community Blurb</label>
          <textarea name="community_blurb"><?= e($settings['community_blurb'] ?? '') ?></textarea>

          <label>Homepage feature blocks</label>
          <textarea name="featured_blocks"><?= e(blocks_to_text($settings['featured_blocks'] ?? [])) ?></textarea>
          <div class="small">Use one line per block in this format: Title | Description</div>

          <h3 style="margin-top:22px">Featured event</h3>
          <div class="row3">
            <div>
              <label>Event Type</label>
              <input type="text" name="event_type" value="<?= e($settings['event_type'] ?? '') ?>">
            </div>
            <div>
              <label>Event Name</label>
              <input type="text" name="event_name" value="<?= e($settings['event_name'] ?? '') ?>">
            </div>
            <div>
              <label>Dates</label>
              <input type="text" name="date_range" value="<?= e($settings['date_range'] ?? '') ?>">
            </div>
          </div>

          <div class="row">
            <div>
              <label>Headline</label>
              <input type="text" name="headline" value="<?= e($settings['headline'] ?? '') ?>">
            </div>
            <div>
              <label>Event Poster Path</label>
              <input type="text" name="event_poster" value="<?= e($settings['event_poster'] ?? '') ?>">
            </div>
          </div>

          <div class="row3">
            <div>
              <label>Prize Label</label>
              <input type="text" name="pot_label" value="<?= e($settings['pot_label'] ?? '') ?>">
            </div>
            <div>
              <label>Prize Value</label>
              <input type="text" name="pot_value" value="<?= e($settings['pot_value'] ?? '') ?>">
            </div>
            <div>
              <label>Status Text (when closed)</label>
              <input type="text" name="status_text" value="<?= e($settings['status_text'] ?? '') ?>">
            </div>
          </div>

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

          <label>How It Works</label>
          <textarea name="how_it_works"><?= e($settings['how_it_works'] ?? '') ?></textarea>

          <div class="row">
            <div>
              <label>Event Notice</label>
              <input type="text" name="event_notice" value="<?= e($settings['event_notice'] ?? '') ?>">
            </div>
            <div>
              <label>CTA Text</label>
              <input type="text" name="cta_text" value="<?= e($settings['cta_text'] ?? '') ?>">
            </div>
          </div>

          <h3 style="margin-top:22px">Buttons & lists</h3>
          <div class="row">
            <div>
              <label>Primary Button Label</label>
              <input type="text" name="primary_button_label" value="<?= e($settings['primary_button_label'] ?? '') ?>">
            </div>
            <div>
              <label>Primary Button URL</label>
              <input type="text" name="primary_button_url" value="<?= e($settings['primary_button_url'] ?? '') ?>">
            </div>
          </div>

          <div class="row">
            <div>
              <label>Submission Button Text</label>
              <input type="text" name="submission_button_text" value="<?= e($settings['submission_button_text'] ?? '') ?>">
            </div>
            <div>
              <label>Station Section Heading</label>
              <input type="text" name="station_heading" value="<?= e($settings['station_heading'] ?? '') ?>">
            </div>
          </div>

          <label>Participating stations / DJs</label>
          <textarea name="stations"><?= e(implode("\n", $settings['stations'] ?? [])) ?></textarea>

          <div class="checks">
            <label><input type="checkbox" name="show_prize_box" <?= !empty($settings['show_prize_box']) ? 'checked' : '' ?>> Show prize box</label>
            <label><input type="checkbox" name="show_submission_button" <?= !empty($settings['show_submission_button']) ? 'checked' : '' ?>> Show submission button</label>
            <label><input type="checkbox" name="submission_page_open" <?= !empty($settings['submission_page_open']) ? 'checked' : '' ?>> Open submission page now</label>
          </div>

          <h3 style="margin-top:22px">Submission form</h3>
          <div class="row">
            <div>
              <label>Submission Page Title</label>
              <input type="text" name="submission_title" value="<?= e($settings['submission_title'] ?? '') ?>">
            </div>
            <div>
              <label>Success Message</label>
              <input type="text" name="success_message" value="<?= e($settings['success_message'] ?? '') ?>">
            </div>
          </div>

          <label>Submission Intro</label>
          <textarea name="submission_intro"><?= e($settings['submission_intro'] ?? '') ?></textarea>

          <div class="row3">
            <div>
              <label>Entry Type Label</label>
              <input type="text" name="entry_type_label" value="<?= e($settings['entry_type_label'] ?? '') ?>">
            </div>
            <div>
              <label>Name Label</label>
              <input type="text" name="name_label" value="<?= e($settings['name_label'] ?? '') ?>">
            </div>
            <div>
              <label>Email Label</label>
              <input type="text" name="email_label" value="<?= e($settings['email_label'] ?? '') ?>">
            </div>
          </div>

          <div class="row">
            <div>
              <label>Field One Label</label>
              <input type="text" name="field_one_label" value="<?= e($settings['field_one_label'] ?? '') ?>">
            </div>
            <div>
              <label>Field One Placeholder</label>
              <input type="text" name="field_one_placeholder" value="<?= e($settings['field_one_placeholder'] ?? '') ?>">
            </div>
          </div>

          <div class="row">
            <div>
              <label>Field Two Label</label>
              <input type="text" name="field_two_label" value="<?= e($settings['field_two_label'] ?? '') ?>">
            </div>
            <div>
              <label>Field Two Placeholder</label>
              <input type="text" name="field_two_placeholder" value="<?= e($settings['field_two_placeholder'] ?? '') ?>">
            </div>
          </div>

          <div class="row">
            <div>
              <label>Message Field Label</label>
              <input type="text" name="field_message_label" value="<?= e($settings['field_message_label'] ?? '') ?>">
            </div>
            <div>
              <label>Message Field Placeholder</label>
              <input type="text" name="field_message_placeholder" value="<?= e($settings['field_message_placeholder'] ?? '') ?>">
            </div>
          </div>

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

          <label>Entry Type Options</label>
          <textarea name="entry_type_options"><?= e(implode("\n", $settings['entry_type_options'] ?? [])) ?></textarea>

          <label>Platform Options</label>
          <textarea name="platforms"><?= e(implode("\n", $settings['platforms'] ?? [])) ?></textarea>

          <div style="margin-top:18px">
            <button type="submit" name="save_settings">Save All Settings</button>
          </div>
        </form>
      </div>
    </div>

    <div class="stack">
      <div class="panel">
        <h2>Submission manager</h2>
        <p>Total submissions: <strong><?= count($submissions) ?></strong></p>
        <div style="display:flex;gap:10px;flex-wrap:wrap">
          <a class="button secondary" href="<?= e(site_url('admin.php?export=csv')) ?>">Export CSV</a>
          <form method="post" onsubmit="return confirm('Clear all submissions?');">
            <button class="secondary" type="submit" name="clear_submissions">Clear All</button>
          </form>
        </div>
      </div>

      <div class="panel">
        <h2>Recent submissions</h2>
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Type</th>
                <th>Main Field</th>
                <th>Second Field</th>
                <th>Name</th>
                <th>Email</th>
                <th>Platform</th>
                <th>Time</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
            <?php if (!$submissions): ?>
              <tr><td colspan="8">No submissions yet.</td></tr>
            <?php else: ?>
              <?php foreach (array_reverse($submissions, true) as $index => $row): ?>
                <tr>
                  <td><?= e($row['entry_type'] ?? '') ?></td>
                  <td><?= e($row['field_one'] ?? '') ?></td>
                  <td><?= e($row['field_two'] ?? '') ?></td>
                  <td><?= e($row['name'] ?? '') ?></td>
                  <td><?= e($row['email'] ?? '') ?></td>
                  <td><?= e($row['platform'] ?? '') ?></td>
                  <td><?= e($row['timestamp'] ?? '') ?></td>
                  <td>
                    <form method="post" onsubmit="return confirm('Delete this submission?');">
                      <button type="submit" name="delete_submission" value="<?= (int)$index ?>">Delete</button>
                    </form>
                  </td>
                </tr>
                <?php if (!empty($row['message_text'])): ?>
                  <tr>
                    <td colspan="8"><strong>Message:</strong> <?= e($row['message_text']) ?></td>
                  </tr>
                <?php endif; ?>
              <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
</html>
