<?php
/**
 * RSVP SUBMIT HANDLER
 * Path: public_html/kartikthanaweddingdinner/rsvp-submit.php
 */

require __DIR__ . "/config/db.php";

/* Allow only POST */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

/* Collect & sanitize */
$name    = trim($_POST['name'] ?? '');
$phone   = trim($_POST['phone'] ?? '');
$email   = trim($_POST['email'] ?? '');
$status  = $_POST['status'] ?? '';
$pax     = (int)($_POST['pax'] ?? 1);
$message = trim($_POST['message'] ?? '');

/* Basic validation */
if ($name === '' || !in_array($status, ['Going', 'Not Going'], true)) {
    http_response_code(400);
    exit('Invalid RSVP data');
}

/* Normalize */
$pax = ($pax > 0) ? $pax : 1;
$phone = $phone !== '' ? $phone : null;
$email = $email !== '' ? $email : null;
$message = $message !== '' ? $message : null;

/* Insert into DB */
$sql = "
    INSERT INTO rsvps
    (name, phone, email, status, pax, message)
    VALUES
    (:name, :phone, :email, :status, :pax, :message)
";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':name'    => $name,
    ':phone'   => $phone,
    ':email'   => $email,
    ':status'  => $status,
    ':pax'     => $pax,
    ':message' => $message
]);

/* Success */
header('Content-Type: application/json');
echo json_encode([
    'success' => true
]);