<?php
declare(strict_types=1);

$to = 'info@stopchildcrueltytrust.org';

function clean_value(string $value): string
{
    $value = str_replace(["\r", "\n"], ' ', $value);
    return trim($value);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode([
        'ok' => false,
        'message' => 'Method not allowed.',
    ], JSON_UNESCAPED_SLASHES);
    exit;
}

$firstName = clean_value((string)($_POST['first_name'] ?? $_POST['First Name'] ?? ''));
$lastName  = clean_value((string)($_POST['last_name'] ?? $_POST['Last Name'] ?? ''));
$email     = clean_value((string)($_POST['email'] ?? $_POST['Email'] ?? ''));
$subject   = clean_value((string)($_POST['subject'] ?? $_POST['Subject'] ?? ''));
$message   = trim((string)($_POST['message'] ?? $_POST['Message'] ?? ''));

$errors = [];

if ($firstName === '') {
    $errors[] = 'First name is required.';
}

if ($lastName === '') {
    $errors[] = 'Last name is required.';
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'A valid email address is required.';
}

if ($subject === '') {
    $subject = 'Website contact form inquiry';
}

if ($message === '') {
    $errors[] = 'Message is required.';
}

if ($errors) {
    http_response_code(400);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode([
        'ok' => false,
        'message' => implode(' ', $errors),
        'errors' => $errors,
    ], JSON_UNESCAPED_SLASHES);
    exit;
}

$fullName = trim($firstName . ' ' . $lastName);
$body = "Name: {$fullName}\n";
$body .= "Email: {$email}\n";
$body .= "Subject: {$subject}\n\n";
$body .= "Message:\n{$message}\n";

$headers = [];
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-Type: text/plain; charset=UTF-8';
$headers[] = 'From: Stop Child Cruelty Trust <no-reply@stopchildcrueltytrust.org>';
$headers[] = 'Reply-To: ' . $email;

$sent = @mail($to, $subject, $body, implode("\r\n", $headers));

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

if ($sent) {
    echo json_encode([
        'ok' => true,
        'message' => 'Thanks. Your message has been sent to Stop Child Cruelty Trust.',
    ], JSON_UNESCAPED_SLASHES);
    exit;
}

http_response_code(500);
echo json_encode([
    'ok' => false,
    'message' => 'Message could not be sent. Please try again later or email info@stopchildcrueltytrust.org directly.',
], JSON_UNESCAPED_SLASHES);
exit;
