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

$settings = get_settings();
$submissionOpen = computed_submission_open($settings);

if (!$submissionOpen) {
    http_response_code(403);
}

$errors = [];
$done = false;
$values = [
    'entry_type' => '',
    'field_one' => '',
    'field_two' => '',
    'field_three' => '',
    'message_text' => '',
    'name' => '',
    'email' => '',
    'platform' => '',
];

if (empty($_SESSION['form_started_at'])) {
    $_SESSION['form_started_at'] = time();
}

function req_if(array $settings, string $showKey, string $requireKey, string $value, string $label, array &$errors): void {
    if (!empty($settings[$showKey]) && !empty($settings[$requireKey]) && trim($value) === '') {
        $errors[] = $label . ' is required.';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $submissionOpen) {
    foreach ($values as $key => $_v) $values[$key] = trim((string)($_POST[$key] ?? ''));
    $honeypot = trim((string)($_POST['website_field'] ?? ''));
    $started = (int)($_SESSION['form_started_at'] ?? time());
    $elapsed = time() - $started;

    if ($honeypot !== '') $errors[] = 'Spam check failed.';
    if ($elapsed < 2) $errors[] = 'Please take a little more time before submitting.';

    req_if($settings, 'show_entry_type', 'require_entry_type', $values['entry_type'], $settings['entry_type_label'] ?? 'Entry type', $errors);
    req_if($settings, 'show_field_one', 'require_field_one', $values['field_one'], $settings['field_one_label'] ?? 'Field one', $errors);
    req_if($settings, 'show_field_two', 'require_field_two', $values['field_two'], $settings['field_two_label'] ?? 'Field two', $errors);
    req_if($settings, 'show_field_three', 'require_field_three', $values['field_three'], $settings['field_three_label'] ?? 'Field three', $errors);
    req_if($settings, 'show_message_field', 'require_message_field', $values['message_text'], $settings['field_message_label'] ?? 'Message', $errors);
    req_if($settings, 'show_name_field', 'require_name_field', $values['name'], $settings['name_label'] ?? 'Name', $errors);
    req_if($settings, 'show_email_field', 'require_email_field', $values['email'], $settings['email_label'] ?? 'Email', $errors);
    req_if($settings, 'show_platform_field', 'require_platform_field', $values['platform'], $settings['platform_label'] ?? 'Platform', $errors);

    if (!empty($settings['show_email_field']) && trim($values['email']) !== '' && !filter_var($values['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Enter a valid email address.';
    }

    if (!$errors) {
        $rows = get_submissions();
        $rows[] = [
            'entry_type' => $values['entry_type'],
            'field_one' => $values['field_one'],
            'field_two' => $values['field_two'],
            'field_three' => $values['field_three'],
            'message_text' => $values['message_text'],
            'name' => $values['name'],
            'email' => $values['email'],
            'platform' => $values['platform'],
            'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
            'timestamp' => date('Y-m-d H:i:s'),
            'is_winner' => false,
            'winner_rank' => ''
        ];
        save_submissions($rows);
        $done = true;
        $_SESSION['form_started_at'] = time();
        foreach ($values as $k => $_v) $values[$k] = '';
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= e($settings['submission_title']) ?></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{--panel:rgba(10,11,16,.9);--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:860px;margin:0 auto;padding:24px 16px 50px}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:28px;padding:22px;box-shadow:0 28px 70px rgba(0,0,0,.45)}
h1,h2,h3{font-family:Oswald,Inter,sans-serif;margin:0 0 12px}
p{color:var(--muted)} label{display:block;font-weight:700;margin:12px 0 8px}
input,textarea,select{width:100%;padding:13px 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}.msg{margin:0 0 14px;padding:12px 14px;border-radius:14px}.ok{background:rgba(36,121,24,.25);border:1px solid rgba(126,217,87,.28)}.err{background:rgba(140,39,39,.22);border:1px solid rgba(255,140,140,.24)}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{background:rgba(255,255,255,.08);color:var(--text);border:1px solid rgba(255,255,255,.09)}.hp{position:absolute;left:-9999px}
@media (max-width:760px){.row{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="wrap">
  <div class="panel">
    <h1><?= e($settings['submission_title']) ?></h1>
    <p><?= e($settings['submission_intro']) ?></p>

    <?php if (!$submissionOpen): ?>
      <div class="msg err">This submission page is currently closed.</div>
    <?php endif; ?>

    <?php if ($done): ?><div class="msg ok"><?= e($settings['success_message']) ?></div><?php endif; ?>
    <?php if ($errors): ?><div class="msg err"><?= e(implode(' ', $errors)) ?></div><?php endif; ?>

    <form method="post" novalidate>
      <div class="hp">
        <label>Leave this field blank</label>
        <input type="text" name="website_field" value="">
      </div>

      <?php if (!empty($settings['show_entry_type'])): ?>
        <label><?= e($settings['entry_type_label']) ?></label>
        <select name="entry_type">
          <option value="">Select</option>
          <?php foreach (($settings['entry_type_options'] ?? []) as $opt): ?>
            <option value="<?= e($opt) ?>" <?= $values['entry_type'] === $opt ? 'selected' : '' ?>><?= e($opt) ?></option>
          <?php endforeach; ?>
        </select>
      <?php endif; ?>

      <?php if (!empty($settings['show_field_one'])): ?>
        <label><?= e($settings['field_one_label']) ?></label>
        <input type="text" name="field_one" value="<?= e($values['field_one']) ?>" placeholder="<?= e($settings['field_one_placeholder']) ?>">
      <?php endif; ?>

      <?php if (!empty($settings['show_field_two'])): ?>
        <label><?= e($settings['field_two_label']) ?></label>
        <input type="text" name="field_two" value="<?= e($values['field_two']) ?>" placeholder="<?= e($settings['field_two_placeholder']) ?>">
      <?php endif; ?>

      <?php if (!empty($settings['show_field_three'])): ?>
        <label><?= e($settings['field_three_label']) ?></label>
        <input type="text" name="field_three" value="<?= e($values['field_three']) ?>" placeholder="<?= e($settings['field_three_placeholder']) ?>">
      <?php endif; ?>

      <?php if (!empty($settings['show_message_field'])): ?>
        <label><?= e($settings['field_message_label']) ?></label>
        <textarea name="message_text" placeholder="<?= e($settings['field_message_placeholder']) ?>"><?= e($values['message_text']) ?></textarea>
      <?php endif; ?>

      <div class="row">
        <?php if (!empty($settings['show_name_field'])): ?>
          <div>
            <label><?= e($settings['name_label']) ?></label>
            <input type="text" name="name" value="<?= e($values['name']) ?>">
          </div>
        <?php endif; ?>
        <?php if (!empty($settings['show_email_field'])): ?>
          <div>
            <label><?= e($settings['email_label']) ?></label>
            <input type="email" name="email" value="<?= e($values['email']) ?>">
          </div>
        <?php endif; ?>
      </div>

      <?php if (!empty($settings['show_platform_field'])): ?>
        <label><?= e($settings['platform_label']) ?></label>
        <select name="platform">
          <option value="">Select</option>
          <?php foreach (($settings['platforms'] ?? []) as $opt): ?>
            <option value="<?= e($opt) ?>" <?= $values['platform'] === $opt ? 'selected' : '' ?>><?= e($opt) ?></option>
          <?php endforeach; ?>
        </select>
      <?php endif; ?>

      <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:18px">
        <button type="submit" <?= !$submissionOpen ? 'disabled' : '' ?>>Submit</button>
        <a class="button secondary" href="<?= e(site_url('index.php')) ?>">Back to site</a>
      </div>
    </form>
  </div>
</div>
</body>
</html>
