<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require 'phpmailer/Exception.php';
require 'phpmailer/PHPMailer.php';
require 'phpmailer/SMTP.php';

header('Content-Type: application/json');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    $mail = new PHPMailer(true);

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

        // Recipients
        $mail->setFrom('info.mumbaicentral@gmail.com', 'Charity Boat Race');
        $mail->addAddress('info.mumbaicentral@gmail.com');

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'New Form Submission: ' . ($_POST['registration_type'] ?? 'General Inquiry');
        
        $body = "<h2>New Form Submission</h2><hr>";
        foreach ($_POST as $key => $value) {
            if ($key != 'registration_type') {
                $label = ucwords(str_replace('_', ' ', $key));
                $body .= "<p><strong>$label:</strong> " . nl2br(htmlspecialchars($value)) . "</p>";
            }
        }
        
        $mail->Body = $body;

        $mail->send();
        echo json_encode(['success' => true, 'message' => 'Thank you! Your message has been sent successfully.']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
