<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Include PHPMailer files
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

// Define constants
error_reporting(E_ALL);
ini_set('display_errors', 1);

define('ADMIN_EMAIL', 'info@legacyonelimo.com');
define('WEBSITE_NAME', 'Dallas Black Cars Limo Service');
define('WEBSITE_URL', 'http://' . $_SERVER['HTTP_HOST']);
define('EMAIL_FROM', 'info@php-mail-system.site');

// SMTP Configuration
define('SMTP_HOST', 'mail.php-mail-system.site');
define('SMTP_USER', 'info@php-mail-system.site');
define('SMTP_PASS', 'Creative@9966332');
define('SMTP_PORT', 465); // Default SSL port
 
/**
 * Trims and strips HTML tags from a string.
 *
 * @param string $str
 * @return string
 */
function strict_secure($str) { 
    return htmlspecialchars(strip_tags(trim($str)), ENT_QUOTES, 'UTF-8');
}

/**
 * Sends an email using PHPMailer with improved debugging.
 *
 * @param string $to       Recipient email address.
 * @param string $subject  Email subject.
 * @param string $message  Email body (HTML allowed).
 * @param string $fromName Sender’s name.
 * @return bool            Returns TRUE if the mail was successfully sent, FALSE otherwise.
 */
function sendEmail($to, $subject, $message, $fromName = WEBSITE_NAME) {
    $mail = new PHPMailer(true);

    try {
        // Enable verbose debug output
        $mail->SMTPDebug = 3; // Set to 3 for more detailed logs
        $mail->Debugoutput = function($str, $level) {
            error_log(date('[Y-m-d H:i:s]') . " SMTP Debug [$level]: $str" . PHP_EOL, 3, 'smtp_debug_log.txt');
        };

        // Server settings
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USER;
        $mail->Password   = SMTP_PASS;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // SSL encryption
        $mail->Port       = SMTP_PORT;

        // Fallback to TLS if SSL fails
        if (!$mail->smtpConnect()) {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Switch to TLS
            $mail->Port = 587; // Change to TLS port
        }

        // Sender & Recipient
        $mail->setFrom(EMAIL_FROM, $fromName);
        $mail->addAddress($to);

        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $message;

        // Send the email
        $mail->send();
        return true;
    } catch (Exception $e) {
        // Log error
        error_log(date('[Y-m-d H:i:s]') . " PHPMailer Error: " . $mail->ErrorInfo . PHP_EOL, 3, 'smtp_debug_log.txt');
        echo '<strong>Mailer Error:</strong> ' . $mail->ErrorInfo; // Display error
        return false;
    }
}

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submitform') {
    $N = $_POST['formInput'] ?? [];
    $path = $_SERVER['HTTP_REFERER'] ?? '';

    // Build the admin message
    $admin_message = '<p>Dear Admin, a form was submitted on ' . WEBSITE_URL . '<br><br><b>Details are as follows:</b></p>';
    foreach ($N as $label => $value) {
        $admin_message .= '<p>' . ucwords($label) . ' : ' . strict_secure($value) . '</p>';
    }
    $admin_message .= '<p>IP address: ' . $_SERVER['REMOTE_ADDR'] . '</p>';
    $admin_message .= '<p>Form submitted on URL: <a href="' . strict_secure($path) . '">' . strict_secure($path) . '</a></p>';
    $admin_message .= '<p>Regards,<br>' . WEBSITE_NAME . '<br>' . WEBSITE_URL . '</p>';

    // Build the user message, if a name is provided
    $user_message = '';
    if (!empty($N['name'])) {
        $user_message  = '<p>Dear ' . strict_secure($N['name']) . ',</p>';
        $user_message .= '<p>Thank you very much for submitting your information. We will contact you shortly.</p>';
        $user_message .= '<p>Regards,<br>' . WEBSITE_NAME . '<br>' . WEBSITE_URL . '</p>';
    }

    // Define email subjects
    $admin_subject = 'Form Received From ' . WEBSITE_NAME;
    $user_subject  = 'Thank you - ' . WEBSITE_NAME;

    // Send email to the admin
    $sendToAdmin = sendEmail(ADMIN_EMAIL, $admin_subject, $admin_message);

    // Optionally, send an email to the user if an email address was provided
    $sendToUser = false;
    if (!empty($N['email'])) {
        $sendToUser = sendEmail(strict_secure($N['email']), $user_subject, $user_message);
    }

    // Display success/error message
    if ($sendToAdmin || $sendToUser) {
        echo 'Success::<div class="alert alert-success"><strong>Thank you! We will get back to you as soon as possible.</strong></div>';
    } else {
        echo 'Error::<div class="alert alert-danger"><strong><i class="fa fa-info message-icon"></i> Something Went Wrong While Sending Message.</strong></div>';
    }
    exit();
}
?>
