<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Database connection
$servername = "localhost";
$username = "wipetearsafrica_wipetears";
$password = "9UwNNGyV3kl)";
$dbname = "wipetearsafrica_donations_db";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check database connection
if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => 'Database connection failed!']));
}

// Initialize response
$response = ['success' => false, 'message' => ''];

// Function to get user IP
function getUserIP() {
    return $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
}

// Function to sanitize input
function sanitizeInput($data) {
    return htmlspecialchars(strip_tags(trim($data)), ENT_QUOTES, 'UTF-8');
}

// Validate email using Bounce API
function validateEmailWithBounceAPI($email) {
    $apiKey = "5aW6oLb800BrwGwLJLoWxetJ5zXFebxTslWtryUR"; // Replace with a valid API key
    $url = "https://api.usebouncer.com/v1/email/verify?email=" . urlencode($email);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["x-api-key: $apiKey"],
    ]);

    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code !== 200) {
        return false;
    }

    $result = json_decode($response, true);
    return isset($result['status']) && $result['status'] === 'deliverable';
}

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!empty($_POST['website'])) { // Honeypot check
        $response['message'] = "Invalid submission detected!";
    } else {
        // Collect and sanitize form data
        $fname = sanitizeInput($_POST['fname'] ?? '');
        $occupation = sanitizeInput($_POST['occupation'] ?? '');
        $gender = sanitizeInput($_POST['gender'] ?? '');
        $telno = sanitizeInput($_POST['telno'] ?? '');
        $email = sanitizeInput($_POST['email'] ?? '');
        $country = sanitizeInput($_POST['country'] ?? '');
        $messageText = sanitizeInput($_POST['message'] ?? '');
        $donate_amount = is_numeric($_POST['donate_amount'] ?? null) ? $_POST['donate_amount'] : 0.00;
        $user_ip = getUserIP();

        // Check required fields
        if (!$fname || !$occupation || !$gender || !$telno || !$email || !$country || !$donate_amount) {
            $response['message'] = "Please fill all required fields!";
        } elseif (!validateEmailWithBounceAPI($email)) {
            $response['message'] = "Invalid email address!";
        } else {
            // Check if IP already submitted
            $stmt = $conn->prepare("SELECT COUNT(*) FROM donations WHERE ip_address = ?");
            if ($stmt) {
                $stmt->bind_param("s", $user_ip);
                $stmt->execute();
                $stmt->bind_result($submission_count);
                $stmt->fetch();
                $stmt->close();

                if ($submission_count > 0) {
                    $response['message'] = "You have already submitted a donation!";
                } else {
                    // Insert donation into database
                    $stmt = $conn->prepare("INSERT INTO donations (fname, occupation, gender, telno, email, country, donate_amount, message, ip_address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    if ($stmt) {
                        $stmt->bind_param("sssssssss", $fname, $occupation, $gender, $telno, $email, $country, $donate_amount, $messageText, $user_ip);

                        if ($stmt->execute()) {
                            sendEmailNotification($fname, $occupation, $gender, $telno, $email, $country, $donate_amount, $messageText, $user_ip);
                            $response['success'] = true;
                            $response['message'] = "Thank you for your donation! A confirmation email has been sent.";
                        } else {
                            $response['message'] = "Error: Unable to submit your donation.";
                        }
                        $stmt->close();
                    } else {
                        $response['message'] = "Database error: Unable to prepare statement.";
                    }
                }
            } else {
                $response['message'] = "Database error: Unable to prepare statement.";
            }
        }
    }
    $conn->close();
}

// Function to send email notifications
function sendEmailNotification($fname, $occupation, $gender, $telno, $email, $country, $donate_amount, $messageText, $user_ip) {
    $sendgridApiKey = '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'; // Replace with your SendGrid API key
    $url = 'https://api.sendgrid.com/v3/mail/send';

    $headers = [
        'Authorization: Bearer ' . $sendgridApiKey,
        'Content-Type: application/json'
    ];

    // Email content
    $adminEmail = [
        'personalizations' => [['to' => [['email' => 'senyonjodaniel6@gmail.com']], 'subject' => 'New Donation Received']],
        'from' => ['email' => 'senyonjokataswa6@gmail.com', 'name' => 'Donation System'],
        'content' => [['type' => 'text/plain', 'value' => "A new donation has been recorded.\n\nIP: $user_ip\nName: $fname\nEmail: $email\nPhone: $telno\nGender: $gender\nOccupation: $occupation\nCountry: $country\nDonation Amount: $$donate_amount\nMessage: $messageText\n"]]
    ];
    sendEmailRequest($url, $headers, $adminEmail);

    // Email to donor
    $donorEmail = [
        'personalizations' => [['to' => [['email' => $email]], 'subject' => 'Thank You for Your Donation!']],
        'from' => ['email' => 'senyonjokataswa6@gmail.com', 'name' => 'Wipe Tears Africa'],
        'content' => [['type' => 'text/plain', 'value' => "Thank you $fname for your donation of $$donate_amount to Wipe Tears Africa. \n\nYour support is highly appreciated and a representative from Wipe Years will engage directly with you on how the funds can be processed. \n\n We thank you for supporting our initiatives and projects."]]
    ];
    sendEmailRequest($url, $headers, $donorEmail);
}

// Send email using cURL
function sendEmailRequest($url, $headers, $emailData) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($emailData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_exec($ch);
    curl_close($ch);
}

// Return response
echo json_encode($response);
exit;
?>
