<?php
session_start();

$promoFile = __DIR__ . '/data/promo.json';
$entriesFile = __DIR__ . '/data/promo_entries.txt';
$promo = file_exists($promoFile) ? json_decode(file_get_contents($promoFile), true) : [];
if (!is_array($promo) || empty($promo['enabled'])) {
  header('Location: /events.php?err=Promotion%20is%20not%20active'); exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  header('Location: /events.php'); exit;
}

$name = trim((string)($_POST['name'] ?? ''));
$email = trim((string)($_POST['email'] ?? ''));
$msg = trim((string)($_POST['message'] ?? ''));
if ($name === '' || $email === '') {
  header('Location: /events.php?err=Missing%20name%20or%20email'); exit;
}
if (strlen($name) > 60) $name = substr($name,0,60);
if (strlen($email) > 120) $email = substr($email,0,120);
if (strlen($msg) > 240) $msg = substr($msg,0,240);

$line = date('Y-m-d H:i') . " | " . $name . " | " . $email . " | " . str_replace(["\r","\n"], ' ', $msg) . "\n";
file_put_contents($entriesFile, $line, FILE_APPEND);

header('Location: /events.php?sent=1');
exit;
