<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $to = "info@wipetearsafrica.org";

    $childName = trim($_POST['child_name'] ?? '');
    $firstName = trim($_POST['first_name'] ?? '');
    $lastName = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $plan = trim($_POST['plan'] ?? '');

    if ($childName === '' || $firstName === '' || $lastName === '' || $email === '') {
        die("Missing required fields.");
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        die("Invalid email address.");
    }

    $subject = "New Child Sponsorship Submission – $childName";

    $message = "NEW SPONSOR DETAILS\n\n";
    $message .= "Child: $childName\n";
    $message .= "Sponsor Name: $firstName $lastName\n";
    $message .= "Email: $email\n";
    $message .= "Phone: $phone\n";
    $message .= "Sponsorship Plan: $plan\n\n";
    $message .= "Submitted from Wipe Tears Africa website.";

    $headers = "From: Wipe Tears Africa <no-reply@wipetearsafrica.org>\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

    if (mail($to, $subject, $message, $headers)) {

        $confirmSubject = "Thank you for sponsoring $childName – Wipe Tears Africa";
        $confirmMessage = "Dear $firstName,\n\n"
            . "Thank you for choosing to sponsor $childName.\n"
            . "We have received your details and our team will contact you shortly.\n\n"
            . "if you are ready to sponsor now, you can visit our donate page and donate instantly.\n\n"
            . "Wipe Tears Africa";

        $confirmHeaders = "From: Wipe Tears Africa <info@wipetearsafrica.org>\r\n";
        mail($email, $confirmSubject, $confirmMessage, $confirmHeaders);

        header("Location: thank-you.html");
        exit;
    } else {
        echo "Email sending failed. Please try again later.";
        exit;
    }
} else {
    header("Location: index.html");
    exit;
}
?>