<?php

declare(strict_types=1);

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

require __DIR__ . '/vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;

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

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

$name = trim((string) ($_POST['name'] ?? ''));
$email = trim((string) ($_POST['email'] ?? ''));
$phoneCountryCode = trim((string) ($_POST['phone_country_code'] ?? ''));
$phone = trim((string) ($_POST['phone'] ?? ''));
$experience = trim((string) ($_POST['experience'] ?? ''));
$duration = trim((string) ($_POST['duration'] ?? ''));
$budget = trim((string) ($_POST['budget'] ?? ''));
$readiness = trim((string) ($_POST['readiness'] ?? ''));
$agreeTerms = isset($_POST['agree_terms']);

if ($name === '' || $email === '' || $phone === '' || $experience === '' || $duration === '' || $budget === '' || $readiness === '') {
    respond(false, 'Please fill in all required fields.', 422);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    respond(false, 'Please provide a valid email address.', 422);
}

if (!$agreeTerms) {
    respond(false, 'You must agree to the Terms & Conditions and Privacy Policy.', 422);
}

$config = require __DIR__ . '/includes/mail-config.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = $config['host'];
    $mail->SMTPAuth = true;
    $mail->Username = $config['username'];
    $mail->Password = $config['password'];
    $mail->SMTPSecure = $config['encryption'];
    $mail->Port = $config['port'];

    $mail->setFrom($config['from_email'], $config['from_name']);
    $mail->addAddress($config['to_email'], $config['to_name']);
    $mail->addReplyTo($email, $name);

    $mail->isHTML(false);
    $mail->Subject = 'New investment application from ' . $name;
    $mail->Body = implode("\n", [
        'A new application was submitted on the SpaceX Foundation site.',
        '',
        'Name: ' . $name,
        'Email: ' . $email,
        'Phone: ' . $phoneCountryCode . ' ' . $phone,
        'Investment experience: ' . $experience,
        'Expected holding duration: ' . $duration,
        'Budget: ' . $budget,
        'Ready to start immediately: ' . $readiness,
    ]);

    $mail->send();

    respond(true, 'Application submitted successfully.');
} catch (PHPMailerException $e) {
    error_log('Mail send failed: ' . $mail->ErrorInfo);
    respond(false, 'Sorry, something went wrong sending your application. Please try again later.', 500);
}
