<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/mailer.php';

header('Content-Type: application/json; charset=utf-8');
header('X-Robots-Tag: noindex, nofollow, noarchive');
header('X-Content-Type-Options: nosniff');

function rsvp_json(int $status, array $payload): void
{
    http_response_code($status);
    echo json_encode($payload, JSON_UNESCAPED_SLASHES);
    exit;
}

function rsvp_clean_string(string $value, int $maxLength): string
{
    $value = trim(preg_replace('/\s+/', ' ', $value) ?? '');
    $value = strip_tags($value);
    return mb_substr($value, 0, $maxLength);
}

function rsvp_client_ip(): string
{
    foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $key) {
        if (empty($_SERVER[$key])) {
            continue;
        }
        $value = (string) $_SERVER[$key];
        if ($key === 'HTTP_X_FORWARDED_FOR') {
            $value = trim(explode(',', $value)[0]);
        }
        return mb_substr($value, 0, 45);
    }

    return '';
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    rsvp_json(405, ['ok' => false, 'message' => 'Please submit the RSVP form.']);
}

$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (strpos($contentType, 'application/json') !== false) {
    $raw = file_get_contents('php://input') ?: '';
    $payload = json_decode($raw, true);
    if (!is_array($payload)) {
        rsvp_json(400, ['ok' => false, 'message' => 'Your RSVP could not be read. Please try again.']);
    }
} else {
    $payload = $_POST;
}

if (!empty($payload['website'])) {
    rsvp_json(200, ['ok' => true, 'message' => 'Thank you.']);
}

$startedAt = isset($payload['form_started_at']) ? (int) $payload['form_started_at'] : 0;
if ($startedAt > 0 && (time() - $startedAt) < 3) {
    rsvp_json(429, ['ok' => false, 'message' => 'Please take a moment to review your response before submitting.']);
}

$fullName = rsvp_clean_string((string) ($payload['fullName'] ?? ''), 160);
$email = mb_strtolower(rsvp_clean_string((string) ($payload['email'] ?? ''), 190));
$phone = rsvp_clean_string((string) ($payload['phone'] ?? ''), 60);
$category = rsvp_clean_string((string) ($payload['category'] ?? ''), 60);
$attendance = rsvp_clean_string((string) ($payload['attendance'] ?? ''), 10);
$note = rsvp_clean_string((string) ($payload['note'] ?? ''), 1000);
$partySize = (int) ($payload['partySize'] ?? 1);

$validCategories = ['Umudim Agu', 'Otu Umuokpu', 'Pengassan', 'Chevron', 'Jesus Embassy', 'Family', 'Others'];

if ($fullName === '' || $email === '') {
    rsvp_json(422, ['ok' => false, 'message' => 'Please share your name and email so we know who to expect.']);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    rsvp_json(422, ['ok' => false, 'message' => 'Please enter a valid email address.']);
}

if (!in_array($category, $validCategories, true)) {
    rsvp_json(422, ['ok' => false, 'message' => 'Please select which group you are joining us with.']);
}

if (!in_array($attendance, ['yes', 'no'], true)) {
    rsvp_json(422, ['ok' => false, 'message' => 'Please let us know whether you will be attending.']);
}

$partySize = $attendance === 'yes' ? max(1, min(6, $partySize)) : 0;
$config = rsvp_config();
$eventId = $config['event']['id'];

try {
    $pdo = rsvp_pdo();
    $existing = $pdo->prepare('SELECT id, attendance, party_size, created_at FROM rsvp_responses WHERE event_id = :event_id AND email = :email LIMIT 1');
    $existing->execute(['event_id' => $eventId, 'email' => $email]);
    $row = $existing->fetch();

    if ($row) {
        $message = $row['attendance'] === 'yes'
            ? 'We already have your RSVP on file. Thank you - no duplicate response was submitted.'
            : 'We already have your response on file. Thank you - no duplicate response was submitted.';
        rsvp_json(409, [
            'ok' => false,
            'duplicate' => true,
            'message' => $message,
        ]);
    }

    $insert = $pdo->prepare(
        'INSERT INTO rsvp_responses
        (event_id, full_name, email, phone, category, attendance, party_size, note, ip_address, user_agent, created_at)
        VALUES
        (:event_id, :full_name, :email, :phone, :category, :attendance, :party_size, :note, :ip_address, :user_agent, NOW())'
    );
    $insert->execute([
        'event_id' => $eventId,
        'full_name' => $fullName,
        'email' => $email,
        'phone' => $phone,
        'category' => $category,
        'attendance' => $attendance,
        'party_size' => $partySize,
        'note' => $note,
        'ip_address' => rsvp_client_ip(),
        'user_agent' => mb_substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255),
    ]);

    $id = (int) $pdo->lastInsertId();
    $mailResult = rsvp_send_confirmation_email([
        'full_name' => $fullName,
        'email' => $email,
        'category' => $category,
        'attendance' => $attendance,
        'party_size' => $partySize,
    ]);
    $notificationResult = rsvp_send_admin_notification([
        'full_name' => $fullName,
        'email' => $email,
        'phone' => $phone,
        'category' => $category,
        'attendance' => $attendance,
        'party_size' => $partySize,
        'note' => $note,
        'created_at' => date('Y-m-d H:i:s'),
    ]);

    $update = $pdo->prepare('UPDATE rsvp_responses SET email_sent = :email_sent, email_error = :email_error, notification_sent = :notification_sent, notification_error = :notification_error WHERE id = :id');
    $update->execute([
        'email_sent' => $mailResult['sent'] ? 1 : 0,
        'email_error' => $mailResult['error'],
        'notification_sent' => $notificationResult['sent'] ? 1 : 0,
        'notification_error' => $notificationResult['error'],
        'id' => $id,
    ]);

    $message = $attendance === 'yes'
        ? 'Your RSVP has been received. A confirmation email has been sent to you.'
        : 'Thank you for letting us know. A confirmation email has been sent to you.';

    if (!$mailResult['sent']) {
        $message = $attendance === 'yes'
            ? 'Your RSVP has been received. We could not send the confirmation email just now, but your response is saved.'
            : 'Thank you for letting us know. Your response is saved, but we could not send the confirmation email just now.';
    }

    rsvp_json(200, [
        'ok' => true,
        'message' => $message,
        'emailSent' => $mailResult['sent'],
        'attendance' => $attendance,
    ]);
} catch (Throwable $exception) {
    error_log('RSVP submission failed: ' . $exception->getMessage());
    rsvp_json(500, [
        'ok' => false,
        'message' => 'We could not record your response just now. Please try again in a moment.',
    ]);
}
