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

// Load Composer's autoloader
require '../vendor/autoload.php';
session_start(); // required for rate limiting

// Return Base URL function
function url() {
    return sprintf(
        "%s://%s",
        isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
        $_SERVER['SERVER_NAME']
    );
}

// Server-side IP and Referrer
$ipaddress = $_SERVER['REMOTE_ADDR'];
$referrer_url = $_SERVER['HTTP_REFERER'] ?? 'No Referrer';

// Get sanitized values
$Name = htmlspecialchars(strip_tags($_POST['Name'] ?? ''));
$Email = filter_var($_POST['Email'] ?? '', FILTER_SANITIZE_EMAIL);
$Number = htmlspecialchars(strip_tags($_POST['Number'] ?? ''));
$Message = htmlspecialchars(strip_tags($_POST['Message'] ?? ''));
$FormName = htmlspecialchars(strip_tags($_POST['FormName'] ?? ''));
$NDA = isset($_POST['NDA']) ? "Checked (Required NDA)" : "Unchecked (Not Required)";
$cip = htmlspecialchars(strip_tags($_POST['cip'] ?? ''));
$locationURL = htmlspecialchars(strip_tags($_POST['locationURL'] ?? ''));

// Honeypot
if (!empty($_POST['honeypot'])) {
    die('Spam detected.');
}

// Rate limiting
if (!isset($_SESSION['last_submit'])) {
    $_SESSION['last_submit'] = time();
} else {
    $time_diff = time() - $_SESSION['last_submit'];
    if ($time_diff < 10) {
        die('Too many submissions. Please try again later.');
    }
    $_SESSION['last_submit'] = time();
}

// Referrer Validation
$allowedHost = 'timesquareprintsllc.com';
$referer = $_SERVER['HTTP_REFERER'] ?? '';
$parsedRefererHost = strtolower(parse_url($referer, PHP_URL_HOST));

if ($parsedRefererHost !== $allowedHost && $parsedRefererHost !== 'www.' . $allowedHost) {
    die('Unauthorized request.');
}



$recipient = "info@timesquareprintsllc.com";
$subject = "Time Square Prints LLC Form Query";
$sender = "info@timesquareprintsllc.com";
$location = "https://timesquareprintsllc.com/thank-you";
$subscriber_subject = "Thank you! One of our consultants will get back to you shortly.";

// Main validation
if (isset($_REQUEST['hiddencapcha']) && $_REQUEST['hiddencapcha'] == "") {
    if (!empty($Name) && !empty($Email) && !empty($Number)) {

        if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
            die("Invalid email address.");
        }

        // HTML body
        $body = "
            <p><strong>Name:</strong> {$Name}</p>
            <p><strong>Email:</strong> {$Email}</p>
            <p><strong>Number:</strong> {$Number}</p>
            <p><strong>IP Address:</strong> {$cip}</p>
            <p><strong>Message:</strong> {$Message}</p>
            <p><strong>Page URL:</strong> {$locationURL}</p>
            <p><strong>NDA Consent:</strong> {$NDA}</p>
        ";

        

        // Send Mail using PHPMailer
           // Create an instance; passing true enables exceptions
            $mail = new PHPMailer(true);
            $mail->isSMTP();                                            // Send using SMTP
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );
        try {
            $mail->Host       = 'mail.timesquareprintsllc.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'info@timesquareprintsllc.com';
            $mail->Password   = '4EEY]jeYRGFQXN?N';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = 465;

            $mail->setFrom('info@timesquareprintsllc.com', $Name);
            $mail->addAddress('info@timesquareprintsllc.com  ');
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;

            $mail->send();

        } catch (Exception $e) {
            die("Mail could not be sent. Error: " . $mail->ErrorInfo);
        }

        // Redirect to thank you page
        header("Location: $location");
        exit();
    }
}
?>
