<?php
// Load Composer's autoloader
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/**
 * Function to send an email
 */
function sendMail(string $toEmail, string $subject, string $messageBody): bool|string {
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'hello.pixmango@gmail.com';
        $mail->Password   = 'qpzddfhpiqdijtud'; 
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        $mail->setFrom('server@pixmango.com', 'Pixmango');
        $mail->addAddress($toEmail);

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $messageBody;

        $mail->send();
        return true;
    } catch (Exception $e) {
        return "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // 1. Sanitize and Filter Input Fields
    $name     = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
    $email    = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    $phone    = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_SPECIAL_CHARS);
    $responseKey = $_POST['g-recaptcha-response'] ?? '';

    // Basic Validation
    if (!$name || !$email || !$phone) {
        die('Invalid input provided.');
    }

    // reCAPTCHA Verification
    $secretKey = "6LeoW_8qAAAAAFKXXf8ael_KdeKclilFVXkAcTPN";
    $userIP    = $_SERVER['REMOTE_ADDR'];
    $url       = "https://www.google.com/recaptcha/api/siteverify";
    
    $data = [
        'secret'   => $secretKey,
        'response' => $responseKey,
        'remoteip' => $userIP,
    ];

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    $response = curl_exec($curl);
    curl_close($curl);

    $resultCap = json_decode($response, true);

    if ($resultCap['success']) {
        $toEmail = 'contact@pixmango.com';
        $subject = "Contact Submission - " . $name;

        // Use sanitized variables in the HTML body
        $body = ' 
        <!DOCTYPE html>
        <html lang="en"> 
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <style>
                .button,.email-footer,.email-header{text-align:center}body{font-family:Arial,sans-serif;background-color:#f6f6f6;margin:0;padding:0}.email-container{max-width:600px;margin:20px auto;background-color:#fff;border-radius:8px;box-shadow:0 4px 8px rgba(0,0,0,.1);overflow:hidden}.button:hover,.email-header{background-color:#084258}.email-header{color:#fff;padding:20px}.email-body{padding:20px}.email-footer{background-color:#f1f1f1;color:#666;padding:10px;font-size:12px}.table{width:100%;border-collapse:collapse}.table td,.table th{text-align:left;padding:10px;border-bottom:1px solid #eee}.table th{background-color:#f7f7f7;font-weight:700}.button{display:inline-block;margin-top:20px;padding:10px 20px;color:#fff;background-color:#14a800;text-decoration:none;border-radius:4px}
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="email-header">
                    <h1>Contact Form Submission</h1>
                </div>
                <div class="email-body">
                <p>Hello Admin,</p>
                <p>You have received a new message from the contact form. Below are the details:</p>
                <table class="table">
                    <tr><th>Name</th><td>' . $name . '</td></tr>
                    <tr><th>Email</th><td>' . $email . '</td></tr>
                    <tr><th>Phone</th><td>' . $phone . '</td></tr>  
                </table>
                <p>To reply to this email, you can use the sender\'s email address provided above.</p>
                <a href="mailto:' . $email . '" class="button">Reply to Sender</a>
                </div>
            </div>
        </body>
        </html>';

        $result = sendMail($toEmail, $subject, $body);

        if ($result === true) {
            echo "<script>window.location.href='success.php'</script>";
        } else {
            echo 'Failed to send email.';
        }
    } else {
        echo 'Please check the recaptcha!';
    }
}
?>