<?php
// Load WordPress core functionality
require_once($_SERVER['DOCUMENT_ROOT'] . '/urreno/wp-load.php');

// Check if data is being submitted via POST method
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'process_donation_form') {
    // Sanitize and retrieve form data
    $first_name = sanitize_text_field($_POST['first_name']);
    $last_name = sanitize_text_field($_POST['last_name']);
    $phone = sanitize_text_field($_POST['phone']);
    $email = sanitize_email($_POST['email']);
    $donation_type = sanitize_text_field($_POST['donation_type']);
    $amount = sanitize_text_field($_POST['amount']);
    $donation_repeat = sanitize_text_field($_POST['donation_repeat']);
    $payment_method = sanitize_text_field($_POST['payment_method']);
    $additional_info = sanitize_textarea_field($_POST['additional_info']);

    // Compose email content
    $to = 'asiteza@lwegatech.com'; // Replace with your desired email address
    $subject = 'New Donation Form Submission';
    $message = "New Donation Form Submission:\n\n";
    $message .= "Name: $first_name $last_name\n";
    $message .= "Phone: $phone\n";
    $message .= "Email: $email\n";
    $message .= "Donation Type: $donation_type\n";
    if ($amount) {
        $message .= "Amount: $amount\n";
    }
    $message .= "Donation Repeat: $donation_repeat\n";
    $message .= "Payment Method: $payment_method\n";
    if ($additional_info) {
        $message .= "Additional Information: $additional_info\n";
    }

    // Send email
    $headers = array(
        'Content-Type: text/html; charset=UTF-8',
        'From: URRENO Donation Page <funds@urreno.org>'
    );
    wp_mail($to, $subject, $message, $headers);

    // Set a success response
    http_response_code(200); // HTTP status code for success

    // Output success message (JSON response)
    echo json_encode(array('status' => 'success'));
} else {
    // Set an error response for invalid form submission
    http_response_code(400); // HTTP status code for bad request
    echo json_encode(array('status' => 'error', 'message' => 'Invalid form submission.'));
}
