<?php
/**
 * Unified form handler: team registration, stall booking, activity registration, contact.
 * Sends structured email via PHPMailer and appends JSON lines to data/form-submissions.log.
 */

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/phpmailer/Exception.php';
require_once __DIR__ . '/phpmailer/PHPMailer.php';
require_once __DIR__ . '/phpmailer/SMTP.php';

header('Content-Type: application/json; charset=utf-8');

function respond(bool $success, string $message, int $code = 200): void {
    http_response_code($code);
    echo json_encode(['success' => $success, 'message' => $message], JSON_UNESCAPED_UNICODE);
    exit;
}

function log_submission(array $payload): void {
    $dir = dirname(__DIR__) . '/data';
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
    $line = json_encode($payload, JSON_UNESCAPED_UNICODE) . "\n";
    @file_put_contents($dir . '/form-submissions.log', $line, FILE_APPEND | LOCK_EX);
}

function h(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(false, 'Invalid request method.', 405);
}

$type = isset($_POST['registration_type']) ? trim((string) $_POST['registration_type']) : '';
$allowed = ['event', 'stall', 'activity', 'contact'];
if (!in_array($type, $allowed, true)) {
    respond(false, 'Unknown form type.', 400);
}

$row = ['ts' => gmdate('c'), 'type' => $type, 'ip' => $_SERVER['REMOTE_ADDR'] ?? '', 'data' => []];
$errors = [];

switch ($type) {
    case 'event':
        $full_name = trim((string) ($_POST['full_name'] ?? ''));
        $team_name = trim((string) ($_POST['team_name'] ?? ''));
        $email = filter_var(trim((string) ($_POST['email'] ?? '')), FILTER_VALIDATE_EMAIL);
        $phone = trim((string) ($_POST['phone'] ?? ''));
        $category = trim((string) ($_POST['category'] ?? ''));
        $notes = trim((string) ($_POST['notes'] ?? ''));
        $cats = ['upazilla', 'sisters', 'masjid', 'community'];
        if ($full_name === '') {
            $errors[] = 'Full name is required.';
        }
        if ($team_name === '') {
            $errors[] = 'Team name is required.';
        }
        if (!$email) {
            $errors[] = 'Valid email is required.';
        }
        if ($phone === '') {
            $errors[] = 'Phone is required.';
        }
        if (!in_array($category, $cats, true)) {
            $errors[] = 'Please select a race category.';
        }
        $row['data'] = compact('full_name', 'team_name', 'email', 'phone', 'category', 'notes');
        $subject = 'Team registration: ' . $team_name;
        $html = '<h2>Team registration</h2>'
            . '<p><strong>Full name:</strong> ' . h($full_name) . '</p>'
            . '<p><strong>Team name:</strong> ' . h($team_name) . '</p>'
            . '<p><strong>Email:</strong> ' . h((string) $email) . '</p>'
            . '<p><strong>Phone:</strong> ' . h($phone) . '</p>'
            . '<p><strong>Category:</strong> ' . h($category) . '</p>'
            . '<p><strong>Additional notes:</strong><br>' . nl2br(h($notes)) . '</p>';
        break;

    case 'stall':
        $contact_name = trim((string) ($_POST['contact_name'] ?? ''));
        $business_name = trim((string) ($_POST['business_name'] ?? ''));
        $email = filter_var(trim((string) ($_POST['email'] ?? '')), FILTER_VALIDATE_EMAIL);
        $phone = trim((string) ($_POST['phone'] ?? ''));
        $stall_type = trim((string) ($_POST['stall_type'] ?? ''));
        $description = trim((string) ($_POST['description'] ?? ''));
        $requirements = trim((string) ($_POST['requirements'] ?? ''));
        $stallTypes = ['food', 'clothing', 'crafts', 'community', 'charity', 'other'];
        if ($contact_name === '') {
            $errors[] = 'Contact name is required.';
        }
        if ($business_name === '') {
            $errors[] = 'Business / organisation is required.';
        }
        if (!$email) {
            $errors[] = 'Valid email is required.';
        }
        if ($phone === '') {
            $errors[] = 'Phone is required.';
        }
        if (!in_array($stall_type, $stallTypes, true)) {
            $errors[] = 'Please select a stall type.';
        }
        if ($description === '') {
            $errors[] = 'Description is required.';
        }
        $row['data'] = compact('contact_name', 'business_name', 'email', 'phone', 'stall_type', 'description', 'requirements');
        $subject = 'Stall booking: ' . $business_name;
        $html = '<h2>Stall booking</h2>'
            . '<p><strong>Contact name:</strong> ' . h($contact_name) . '</p>'
            . '<p><strong>Business:</strong> ' . h($business_name) . '</p>'
            . '<p><strong>Email:</strong> ' . h((string) $email) . '</p>'
            . '<p><strong>Phone:</strong> ' . h($phone) . '</p>'
            . '<p><strong>Stall type:</strong> ' . h($stall_type) . '</p>'
            . '<p><strong>Description:</strong><br>' . nl2br(h($description)) . '</p>'
            . '<p><strong>Special requirements:</strong><br>' . nl2br(h($requirements)) . '</p>';
        break;

    case 'activity':
        $activity_slug = trim((string) ($_POST['activity_slug'] ?? ''));
        $full_name = trim((string) ($_POST['full_name'] ?? ''));
        $email = filter_var(trim((string) ($_POST['email'] ?? '')), FILTER_VALIDATE_EMAIL);
        $phone = trim((string) ($_POST['phone'] ?? ''));
        $participants = (string) ($_POST['participants'] ?? '1');
        $notes = trim((string) ($_POST['notes'] ?? ''));
        $allowedSlugs = ['fun-day', 'rickshaw-ride', 'food-stalls', 'longhi-race', 'family-picnic', 'sack-race'];
        $maxBySlug = [
            'fun-day' => 6,
            'rickshaw-ride' => 4,
            'food-stalls' => 2,
            'longhi-race' => 8,
            'family-picnic' => 10,
            'sack-race' => 4,
        ];
        if (!in_array($activity_slug, $allowedSlugs, true)) {
            $errors[] = 'Invalid activity.';
        }
        if ($full_name === '') {
            $errors[] = 'Full name is required.';
        }
        if (!$email) {
            $errors[] = 'Valid email is required.';
        }
        $p = filter_var($participants, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
        $max = $maxBySlug[$activity_slug] ?? 4;
        if ($p === false || $p > $max) {
            $errors[] = 'Number of participants must be between 1 and ' . $max . '.';
        }
        $row['data'] = [
            'activity_slug' => $activity_slug,
            'full_name' => $full_name,
            'email' => $email,
            'phone' => $phone,
            'participants' => $p,
            'notes' => $notes,
        ];
        $subject = 'Activity registration (' . $activity_slug . '): ' . $full_name;
        $html = '<h2>Activity registration</h2>'
            . '<p><strong>Activity:</strong> ' . h($activity_slug) . '</p>'
            . '<p><strong>Full name:</strong> ' . h($full_name) . '</p>'
            . '<p><strong>Email:</strong> ' . h((string) $email) . '</p>'
            . '<p><strong>Phone:</strong> ' . h($phone) . '</p>'
            . '<p><strong>Participants:</strong> ' . h((string) $p) . '</p>'
            . '<p><strong>Notes:</strong><br>' . nl2br(h($notes)) . '</p>';
        break;

    case 'contact':
        $name = trim((string) ($_POST['name'] ?? ''));
        $email = filter_var(trim((string) ($_POST['email'] ?? '')), FILTER_VALIDATE_EMAIL);
        $phone = trim((string) ($_POST['phone'] ?? ''));
        $subject_line = trim((string) ($_POST['subject'] ?? ''));
        $message = trim((string) ($_POST['message'] ?? ''));
        if ($name === '') {
            $errors[] = 'Name is required.';
        }
        if (!$email) {
            $errors[] = 'Valid email is required.';
        }
        if ($subject_line === '') {
            $errors[] = 'Subject is required.';
        }
        if ($message === '') {
            $errors[] = 'Message is required.';
        }
        $row['data'] = compact('name', 'email', 'phone', 'subject_line', 'message');
        $subject = 'Contact: ' . $subject_line;
        $html = '<h2>Contact form</h2>'
            . '<p><strong>Name:</strong> ' . h($name) . '</p>'
            . '<p><strong>Email:</strong> ' . h((string) $email) . '</p>'
            . '<p><strong>Phone:</strong> ' . h($phone) . '</p>'
            . '<p><strong>Subject:</strong> ' . h($subject_line) . '</p>'
            . '<p><strong>Message:</strong><br>' . nl2br(h($message)) . '</p>';
        break;

    default:
        respond(false, 'Unsupported form.', 400);
}

if ($errors) {
    respond(false, implode(' ', $errors), 400);
}

log_submission($row);

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'info.mumbaicentral@gmail.com';
    $mail->Password   = 'otdgbpuudeygibad';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    $mail->setFrom('info.mumbaicentral@gmail.com', 'Charity Boat Race');
    $mail->addAddress('info.mumbaicentral@gmail.com');
    if (!empty($row['data']['email']) && is_string($row['data']['email']) && filter_var($row['data']['email'], FILTER_VALIDATE_EMAIL)) {
        $mail->addReplyTo($row['data']['email'], $row['data']['full_name'] ?? $row['data']['name'] ?? $row['data']['contact_name'] ?? '');
    }

    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body = $html;
    $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $html));

    $mail->send();

    $messages = [
        'event' => 'Thank you! Your team registration has been sent.',
        'stall' => 'Thank you! Your stall booking has been sent.',
        'activity' => "Thank you! You're registered — we'll be in touch with details.",
        'contact' => 'Thank you! Your message has been sent.',
    ];
    respond(true, $messages[$type] ?? 'Thank you! Your submission has been sent.');
} catch (Exception $e) {
    respond(false, 'Message could not be sent. Please try again later.', 500);
}
