<?php
declare(strict_types=1);

/**
 * submit-prayer.php
 *
 * Receives prayer request submissions from Wix form embed
 * and emails them to the church secretary.
 */

// --------------------------------------------------
// CONFIG
// --------------------------------------------------
$allowedOrigins = [
    'https://www.weareunion.org',
    'https://weareunion.org',
    'https://editor.wix.com',
    'https://manage.wix.com',
    'null', // sometimes embeds/file previews can send null origin
];

$secretaryEmail = 'chess@weareunion.org';
$pastoralEmail  = ''; // optional extra recipient if pastoral contact requested
$fromEmail      = 'no-reply@weareunion.org';
$fromName       = 'Union Prayer Request Form';

// --------------------------------------------------
// HELPERS
// --------------------------------------------------
function respond(int $statusCode, string $message): void
{
    http_response_code($statusCode);
    header('Content-Type: text/plain; charset=UTF-8');
    echo $message;
    exit;
}

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

function cleanEmail(?string $value): string
{
    $value = trim((string)$value);
    $value = filter_var($value, FILTER_SANITIZE_EMAIL);
    return filter_var($value, FILTER_VALIDATE_EMAIL) ? $value : '';
}

function cleanPhone(?string $value): string
{
    $value = trim((string)$value);
    $digits = preg_replace('/\D+/', '', $value ?? '');

    if (strlen($digits) === 11 && str_starts_with($digits, '1')) {
        $digits = substr($digits, 1);
    }

    if (strlen($digits) !== 10) {
        return $value; // keep original display if not a full valid US number
    }

    return sprintf('(%s) %s-%s',
        substr($digits, 0, 3),
        substr($digits, 3, 3),
        substr($digits, 6, 4)
    );
}

function phoneDigits(?string $value): string
{
    $digits = preg_replace('/\D+/', '', (string)$value);
    if (strlen($digits) === 11 && str_starts_with($digits, '1')) {
        $digits = substr($digits, 1);
    }
    return $digits;
}

// --------------------------------------------------
// CORS
// --------------------------------------------------
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if ($origin !== '' && in_array($origin, $allowedOrigins, true)) {
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Vary: Origin');
} else {
    // If you prefer to lock it down harder, remove this line and reject unknown origins.
    header('Access-Control-Allow-Origin: *');
}

header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(405, 'Method not allowed.');
}

// --------------------------------------------------
// INPUTS
// --------------------------------------------------
$name             = cleanText($_POST['name'] ?? '');
$email            = cleanEmail($_POST['email'] ?? '');
$phoneRaw          = cleanText($_POST['phone'] ?? '');
$phone             = cleanPhone($phoneRaw);
$request           = cleanText($_POST['request'] ?? '');
$confidential      = isset($_POST['confidential']) ? 'Yes' : 'No';
$pastoralContact   = isset($_POST['pastoral_contact']) ? 'Yes' : 'No';
$honeypot          = trim((string)($_POST['website'] ?? ''));

// --------------------------------------------------
// SPAM CHECK
// --------------------------------------------------
if ($honeypot !== '') {
    respond(200, 'OK');
}

// --------------------------------------------------
// VALIDATION
// --------------------------------------------------
if ($request === '') {
    respond(400, 'Prayer request is required.');
}

if ($pastoralContact === 'Yes') {
    $digits = phoneDigits($phoneRaw);
    if (strlen($digits) !== 10) {
        respond(400, 'Phone number is required when requesting pastoral contact.');
    }
}

if ($name === '') {
    $name = 'Anonymous';
}

// --------------------------------------------------
// RECIPIENTS
// --------------------------------------------------
$to = $secretaryEmail;

if ($pastoralContact === 'Yes' && filter_var($pastoralEmail, FILTER_VALIDATE_EMAIL)) {
    $to .= ',' . $pastoralEmail;
}

// --------------------------------------------------
// SUBJECT
// --------------------------------------------------
$subject = 'New Prayer Request';

if ($confidential === 'Yes') {
    $subject = '[Confidential] ' . $subject;
}

if ($pastoralContact === 'Yes') {
    $subject .= ' - Pastoral Contact Requested';
}

// --------------------------------------------------
// MESSAGE
// --------------------------------------------------
$submittedAt = date('Y-m-d h:i:s A');

$messageLines = [
    'A new prayer request has been submitted.',
    '',
    'Submitted: ' . $submittedAt,
    'Name: ' . $name,
    'Email: ' . ($email !== '' ? $email : 'Not provided'),
    'Phone: ' . ($phone !== '' ? $phone : 'Not provided'),
    'Pastoral Contact Requested: ' . $pastoralContact,
    'Confidential: ' . $confidential,
    '',
    'Prayer Request:',
    $request,
    '',
    '---',
    'Sent from the Union Church prayer request web form.',
];

$message = implode("\n", $messageLines);

// --------------------------------------------------
// HEADERS
// --------------------------------------------------
$encodedFromName = mb_encode_mimeheader($fromName, 'UTF-8');
$headers = [];
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-Type: text/plain; charset=UTF-8';
$headers[] = 'From: ' . $encodedFromName . ' <' . $fromEmail . '>';
$headers[] = 'Reply-To: ' . ($email !== '' ? $email : $fromEmail);
$headers[] = 'X-Mailer: PHP/' . phpversion();

$headersString = implode("\r\n", $headers);

// --------------------------------------------------
// SEND
// --------------------------------------------------
$mailSent = mail($to, $subject, $message, $headersString);

if (!$mailSent) {
    respond(500, 'Failed to send email.');
}

respond(200, 'Success');