<?php
include_once './api/include-me-first.php';
include __DIR__ . '/system/dbconfig.php';


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

$host = "https://uspeeknow.com/";

// Domain validation - only allow requests from uspeeknow.com domain
$allowed_domains = ['uspeeknow.com', 'www.uspeeknow.com'];
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$referer_domain = '';

if (!empty($referer)) {
    $parsed_url = parse_url($referer);
    $referer_domain = isset($parsed_url['host']) ? $parsed_url['host'] : '';
}

// Check if the request is from an allowed domain
$is_allowed_domain = false;
foreach ($allowed_domains as $domain) {
    if ($referer_domain === $domain) {
        $is_allowed_domain = true;
        break;
    }
}

// If not from allowed domain, redirect to success page without processing
if (!$is_allowed_domain) {
    header('Location: ' . $host . 'contact-sales-success.html');
    exit;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $url = 'https://recaptchaenterprise.googleapis.com/v1/projects/uspeeknowcom-1743215712826/assessments?key=AIzaSyDozv87syfyJcDqoO1grRvzIxPRqJ0VOVE';
    $data = [
        'event' => [
            'token' => $_POST['g-recaptcha-response'],
            'siteKey' => $_POST['siteKey'],
            'expectedAction' => 'validate_captcha'
        ]
    ];

    $ch = curl_init($url);
    $payload = json_encode($data);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    # Takes a JSON encoded string and converts it into a PHP variable
    $res = json_decode($result, true);
    # END setting reCaptcha v3 validation data
    # Post form OR output alert and bypass post if false. NOTE: score conditional is optional
    # since the successful score default is set at >= 0.5 by Google. Some developers want to
    # be able to control score result conditions, so I included that in this example.

    if ($res['tokenProperties']['valid'] && $res['riskAnalysis']['score'] >= 0.5) {
        # Recipient email
        $mail_to = "support@uspeeknow.com";
        
        # Sender form data - Basic Contact Info
        $subject = 'Contact form - uSpeek Sales Inquiry';
        $name = str_replace(array("\r", "\n"), array(" ", " "), strip_tags(trim($_POST["name"])));
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $phone = trim($_POST["phone"]);
        $organization = isset($_POST["organization"]) ? str_replace(array("\r", "\n"), array(" ", " "), strip_tags(trim($_POST["organization"]))) : '';
        $city = isset($_POST["city"]) ? str_replace(array("\r", "\n"), array(" ", " "), strip_tags(trim($_POST["city"]))) : '';
        
        # Purpose of Enquiry
        $purpose = isset($_POST["purpose"]) ? trim($_POST["purpose"]) : '';
        $other_purpose = isset($_POST["other-purpose"]) ? str_replace(array("\r", "\n"), array(" ", " "), strip_tags(trim($_POST["other-purpose"]))) : '';
        
        # Need Description
        $need = isset($_POST["need"]) ? str_replace(array("\r", "\n"), array(" ", " "), strip_tags(trim($_POST["need"]))) : '';
        
        # Urgency / Timeline
        $urgency = isset($_POST["urgency"]) ? trim($_POST["urgency"]) : '';
        
        # Preferred Mode of Contact
        $contact_mode = isset($_POST["contact_mode"]) ? trim($_POST["contact_mode"]) : '';

        # Validate required fields
        if (empty($name) || !filter_var($email, FILTER_VALIDATE_EMAIL) || empty($phone) || empty($purpose) || empty($need)) {
            # Set a 400 (bad request) response code and exit
            http_response_code(400);
            echo '<p class="alert-warning">Please complete all required fields and try again.</p>';
            exit;
        }

        # Mail content - Beautiful HTML Email Template with inline styling
        $content = '
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>New Contact Form Submission - uSpeek Sales Inquiry</title>
        </head>
        <body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4; line-height: 1.6;">
            <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="background-color: #f4f4f4;">
                <tr>
                    <td style="padding: 20px 0;">
                        <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="600" style="margin: 0 auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); overflow: hidden;">
                            
                            <!-- Header -->
                            <tr>
                                <td style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px 40px; text-align: center;">
                                    <img src="https://uspeeknow.com/img/logo.png" alt="uSpeek Logo" style="max-width: 200px; height: auto; margin-bottom: 15px;">
                                    <h1 style="color: #ffffff; margin: 0; font-size: 28px; font-weight: 600; text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);">New Sales Inquiry</h1>
                                    <p style="color: #ffffff; margin: 10px 0 0 0; font-size: 16px; opacity: 0.9;">We have received a new contact form submission</p>
                                </td>
                            </tr>
                            
                            <!-- Main Content -->
                            <tr>
                                <td style="padding: 40px;">
                                    
                                    <!-- Contact Information Section -->
                                    <div style="background-color: #f8f9fa; border-left: 4px solid #667eea; padding: 25px; margin-bottom: 30px; border-radius: 0 8px 8px 0;">
                                        <h2 style="color: #333333; margin: 0 0 20px 0; font-size: 22px; font-weight: 600;">Contact Information</h2>
                                        <table style="width: 100%; border-collapse: collapse;">
                                            <tr>
                                                <td style="padding: 8px 0; width: 120px; font-weight: 600; color: #555555;">Name:</td>
                                                <td style="padding: 8px 0; color: #333333;">' . htmlspecialchars($name) . '</td>
                                            </tr>
                                            <tr>
                                                <td style="padding: 8px 0; width: 120px; font-weight: 600; color: #555555;">Email:</td>
                                                <td style="padding: 8px 0; color: #333333;">
                                                    <a href="mailto:' . htmlspecialchars($email) . '" style="color: #667eea; text-decoration: none;">' . htmlspecialchars($email) . '</a>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="padding: 8px 0; width: 120px; font-weight: 600; color: #555555;">Phone:</td>
                                                <td style="padding: 8px 0; color: #333333;">
                                                    <a href="tel:' . htmlspecialchars($phone) . '" style="color: #667eea; text-decoration: none;">' . htmlspecialchars($phone) . '</a>
                                                </td>
                                            </tr>';
        
        if (!empty($organization)) {
            $content .= '
                                            <tr>
                                                <td style="padding: 8px 0; width: 120px; font-weight: 600; color: #555555;">Organization:</td>
                                                <td style="padding: 8px 0; color: #333333;">' . htmlspecialchars($organization) . '</td>
                                            </tr>';
        }
        
        if (!empty($city)) {
            $content .= '
                                            <tr>
                                                <td style="padding: 8px 0; width: 120px; font-weight: 600; color: #555555;">Location:</td>
                                                <td style="padding: 8px 0; color: #333333;">' . htmlspecialchars($city) . '</td>
                                            </tr>';
        }
        
        $content .= '
                                        </table>
                                    </div>
                                    
                                    <!-- Purpose Section -->
                                    <div style="background-color: #f8f9fa; border-left: 4px solid #764ba2; padding: 25px; margin-bottom: 30px; border-radius: 0 8px 8px 0;">
                                        <h2 style="color: #333333; margin: 0 0 20px 0; font-size: 22px; font-weight: 600;">Purpose of Inquiry</h2>
                                        <p style="margin: 0 0 10px 0; color: #555555; font-weight: 600;">What are you looking for:</p>
                                        <p style="margin: 0; color: #333333; font-size: 16px; padding: 12px; background-color: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0;">' . htmlspecialchars($purpose) . '</p>';
        
        if (!empty($other_purpose)) {
            $content .= '
                                        <p style="margin: 15px 0 10px 0; color: #555555; font-weight: 600;">Additional Details:</p>
                                        <p style="margin: 0; color: #333333; font-size: 16px; padding: 12px; background-color: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0;">' . htmlspecialchars($other_purpose) . '</p>';
        }
        
        $content .= '
                                    </div>
                                    
                                    <!-- Need Description Section -->
                                    <div style="background-color: #f8f9fa; border-left: 4px solid #667eea; padding: 25px; margin-bottom: 30px; border-radius: 0 8px 8px 0;">
                                        <h2 style="color: #333333; margin: 0 0 20px 0; font-size: 22px; font-weight: 600;">Need Description</h2>
                                        <p style="margin: 0; color: #333333; font-size: 16px; padding: 15px; background-color: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0; line-height: 1.6;">' . nl2br(htmlspecialchars($need)) . '</p>
                                    </div>
                                    
                                    <!-- Additional Details Section -->
                                    <div style="background-color: #f8f9fa; border-left: 4px solid #764ba2; padding: 25px; margin-bottom: 30px; border-radius: 0 8px 8px 0;">';
        
        if (!empty($urgency)) {
            $urgency_text = '';
            switch($urgency) {
                case 'immediately':
                    $urgency_text = 'Immediately';
                    break;
                case '1_week':
                    $urgency_text = 'Within 1 week';
                    break;
                case '1_month':
                    $urgency_text = 'Within 1 month';
                    break;
                case 'exploring':
                    $urgency_text = 'Just exploring';
                    break;
                default:
                    $urgency_text = $urgency;
            }
            $content .= '
                                        <h2 style="color: #333333; margin: 0 0 20px 0; font-size: 22px; font-weight: 600;">Timeline & Contact Preferences</h2>
                                        <table style="width: 100%; border-collapse: collapse;">
                                            <tr>
                                                <td style="padding: 8px 0; width: 200px; font-weight: 600; color: #555555;">When to get started:</td>
                                                <td style="padding: 8px 0; color: #333333;">' . $urgency_text . '</td>
                                            </tr>';
        }
        
        if (!empty($contact_mode)) {
            $contact_mode_text = '';
            switch($contact_mode) {
                case 'whatsapp':
                    $contact_mode_text = 'WhatsApp';
                    break;
                case 'phone':
                    $contact_mode_text = 'Phone Call';
                    break;
                case 'email':
                    $contact_mode_text = 'Email';
                    break;
                case 'any':
                    $contact_mode_text = 'Any of the above';
                    break;
                default:
                    $contact_mode_text = $contact_mode;
            }
            $content .= '
                                            <tr>
                                                <td style="padding: 8px 0; width: 200px; font-weight: 600; color: #555555;">Preferred contact method:</td>
                                                <td style="padding: 8px 0; color: #333333;">' . $contact_mode_text . '</td>
                                            </tr>';
        }
        
        $content .= '
                                        </table>
                                    </div>
                                    
                                    <!-- Action Button -->
                                    <div style="text-align: center; margin: 40px 0;">
                                        <a href="mailto:' . htmlspecialchars($email) . '?subject=Re: Your uSpeek Inquiry" style="display: inline-block; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #ffffff; text-decoration: none; padding: 15px 30px; border-radius: 25px; font-weight: 600; font-size: 16px; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4); transition: all 0.3s ease;">Reply to Inquiry</a>
                                    </div>
                                    
                                    <!-- Footer Info -->
                                    <div style="border-top: 1px solid #e0e0e0; padding-top: 20px; margin-top: 30px;">
                                        <p style="color: #888888; font-size: 12px; margin: 5px 0;">📧 Submitted from: ' . htmlspecialchars($referer) . '</p>
                                        <p style="color: #888888; font-size: 12px; margin: 5px 0;">🕒 Submission time: ' . date('F j, Y \a\t g:i A') . '</p>
                                    </div>
                                    
                                </td>
                            </tr>
                            
                            <!-- Footer -->
                            <tr>
                                <td style="background-color: #2c3e50; padding: 30px 40px; text-align: center;">
                                    <img src="https://uspeeknow.com/img/logo.png" alt="uSpeek Logo" style="max-width: 150px; height: auto; margin-bottom: 15px; filter: brightness(0) invert(1);">
                                    <p style="color: #ffffff; margin: 0 0 10px 0; font-size: 16px; font-weight: 600;">uSpeek - Empowering Communication</p>
                                    <p style="color: #bdc3c7; margin: 0; font-size: 14px;">Thank you for choosing uSpeek for your communication needs</p>
                                    <div style="margin-top: 20px;">
                                        <a href="https://uspeeknow.com" style="color: #3498db; text-decoration: none; margin: 0 10px; font-size: 14px;">Visit Website</a>
                                        <span style="color: #bdc3c7;">|</span>
                                        <a href="mailto:support@uspeeknow.com" style="color: #3498db; text-decoration: none; margin: 0 10px; font-size: 14px;">Contact Support</a>
                                    </div>
                                </td>
                            </tr>
                            
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>';

        # Email headers
        $headers = "From: $name <$email>";
        
        # Send the email using PHPMailer
        $mail = new PHPMailer(true);
        $appName = 'uSpeek';
        try {
            $mail->isSMTP();
            $mail->Host = SMTP_HOST;
            $mail->SMTPAuth = true;
            $mail->Username = SMTP_USER;
            $mail->Password = SMTP_PASSWORD;
            $mail->SMTPSecure = SMTP_SECURITY;
            $mail->Port = SMTP_PORT;
            $mail->setFrom(SMTP_EMAIL, SMTP_SENDER_NAME);
            // Add a recipient
            $mail->addAddress($mail_to);
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $content;
            //plain text for non-HTML mail clients
            $mail->AltBody = strip_tags($content);
            $mail->send();
            header('Location: ' . $host . 'contact-sales-success.html');
        } catch (Exception $e) {
            return 'Exception' . $mail->ErrorInfo;
        }
    } else {
        header('Location: ' . $host . 'contact-sales-success.html');
        echo '<div class="alert alert-danger">
        Error! The security token has expired or you are a bot.
       </div>';
    }
} else {
    header('Location: ' . $host . 'contact-sales-success.html');
    # Not a POST request, set a 403 (forbidden) response code
    echo '<p class="alert-warning">There was a problem with your submission, please try again.</p>';
}