<?php

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

require_once __DIR__ . '/vendor/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/src/SMTP.php';

$mail = new PHPMailer(true);

// Environment-based configuration
$smtpHost = getenv('SMTP_HOST') ?: 'mail.smtp2go.com';
$smtpUser = getenv('SMTP_USERNAME') ?: 'dmxdigital';
$smtpPass = getenv('SMTP_PASSWORD') ?: 'okQLYLleqoNP'; // Consider securely storing this password
$vendorKey = getenv('VENDOR_KEY') ?: '6212FFE0-77D0-4CE9-8569-EB0581CC43DB';

$name = htmlspecialchars(trim($_POST["sname"] ?? ''));
$country_code = htmlspecialchars(trim($_POST["country_code"] ?? ''));
$phone = htmlspecialchars(trim($_POST["phone"] ?? ''));
$email = htmlspecialchars(trim($_POST["enq_email"] ?? ''));
$message = htmlspecialchars(trim($_POST["message"] ?? ''));
$flag = htmlspecialchars(trim($_POST["flag"] ?? ''));
$honeypot = htmlspecialchars(trim($_POST["company_name"] ?? ''));

$project = "VJ Palladio Balewadi";
$propertyFor = 'Buy';
$property = 'Flat';
$propertyType = 'BHK';
$location = 'Kharadi';

try {
    if ($honeypot) {
        header('Location: index.html?r=1');
        error_log("Alert IP: " . $_SERVER['REMOTE_ADDR'] . " is spammer."); // Log mailer errors
        exit("Spam detected!");
    }

    // Validate required fields
    if ($name && $country_code && is_numeric($phone) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Basic spam check
        if (preg_match('/www\.|http:|https:/i', $message) <= 0 && preg_match('/www\.|http:|https:/i', $name) <= 0) {
            // Set SMTP server settings
            $mail->isSMTP();
            $mail->Host = $smtpHost;
            $mail->SMTPAuth = true;
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->Username = $smtpUser;
            $mail->Password = $smtpPass;

            // Default message if flag is 0 and message is empty
            if ($flag == 0 && $message == "") {
                $message = "Pre-Registered for best offers.";
            }

            // Email content settings
            $mail->setFrom('leads@dmxdigital.in', 'VJ Palladio Balewadi');
            $mail->addAddress("rajesht1900@gmail.com", "Enquiry Email");
            $mail->addAddress("pathan.parvez@yahoo.com", "VJ Palladio Balewadi");
            $mail->addReplyTo('rajesht1900@gmail.com', 'VJ Palladio Balewadi');

            $mail->isHTML(true);
            $mail->Subject = "Email Enquiry from - VJ Palladio Balewadi";
            $mail->Body = '<b>See Below The Enquiry - </b><br><b>Name:</b> ' . htmlspecialchars($name) . 
                          ",<br><b>Email:</b> " . htmlspecialchars($email) . 
                          ",<br><b>Phone:</b> " . htmlspecialchars($country_code) . " " . htmlspecialchars($phone) . 
                          ",<br><b>Message:</b> " . htmlspecialchars($message) . ".";
            $mail->AltBody = 'See below the enquiry: Name: ' . $name . ', Email: ' . $email . ', Phone: ' . $country_code . ' ' . $phone . ', Message: ' . $message;

            // Send email
            $mail->send();

            // Lead data push to external service
            $url = "https://proprise.leadpluss.com/Services/api/TenantLeads/Submit";
            $data = http_build_query([
                'vendor_key' => $vendorKey,
                'PropertyFor' => $propertyFor,
                'Property' => $property,
                'PropertyType' => $propertyType,
                'Project' => $project,
                'Location' => $location,
                'Phone' => $phone,
                'FirstName' => $name,
                'EmailId' => $email,
                'Message' => $message
            ]);

            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded"]);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            $response = curl_exec($ch);
            if ($response === false) {
                error_log("cURL Error: " . curl_error($ch));
            }
            curl_close($ch);

            header('Location: index.html?r=1');
            exit;
        } else {
            header('Location: index.html?r=1'); // Suspected spam, redirect with a success code for simplicity
            exit;
        }
    } else {
        header('Location: index.html?r=0'); // Validation failed
        exit;
    }
} catch (Exception $e) {
    error_log("Mailer Error: " . $mail->ErrorInfo); // Log mailer errors
    header('Location: index.html?r=0');
    exit;
}

