<?php include 'includes/header.php'; ?>

<?php
// Check if Contact page is enabled
if (!ENABLE_CONTACT) {
    $_SESSION['alert'] = displayAlert($lang_frontend['CONTACT_FORM_DISABLED_MESSAGE'] ?? 'The Contact page is currently disabled.', 'info');
    redirectTo('index');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_SECURITY_TOKEN'] ?? 'Invalid security token. Please try again.', 'danger');
        redirectTo('contact');
    }

    // Validate honeypot
    if (!validateHoneypot()) {
        // Bot detected, redirect with generic message
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_MESSAGE_SENT_HONEYPOT'] ?? 'Your message has been sent.', 'success');
        redirectTo('contact');
    }

    // Validate hCaptcha
    if (!validateHCaptcha($_POST['h-captcha-response'] ?? '')) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_CAPTCHA_VERIFICATION'] ?? 'Please complete the captcha verification to continue.', 'danger');
        redirectTo('contact');
    }

    // Use centralized email validation function
    $email_validation = validateEmail($_POST['email'] ?? '');
    if (!$email_validation['valid']) {
        $_SESSION['alert'] = displayAlert($email_validation['errors'][0] ?? $lang_alerts['ALERT_ERROR_INVALID_EMAIL_ADDRESS'] ?? 'Please enter a valid email address', 'danger');
        redirectTo('contact');
    }
    $email = $email_validation['sanitized'];

    // Check rate limiting
    $rate_limit_check = checkRateLimit('contact', $email);
    if (!$rate_limit_check['allowed']) {
        $_SESSION['alert'] = displayAlert($rate_limit_check['message'], 'warning');
        redirectTo('contact');
    }

    // Record this attempt for rate limiting
    recordSubmissionAttempt('contact', $email);

    $name = sanitizeInput($_POST['name']);
    $subject = sanitizeInput($_POST['subject']);
    $message = cleanHTML($_POST['message']);
    // Validate input
    if (empty($name) || empty($email) || empty($subject) || empty($message)) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_FILL_ALL_REQUIRED_FIELDS'] ?? 'Please fill in all required fields', 'danger');
    } else {
        // Send contact form email to admin
        $admin_email = ADMIN_EMAIL; // Use the admin email from config
        $email_subject = "[Contact Form] " . $subject;
        $email_body = "
        <html>
        <head><title>" . ($lang_frontend['CONTACT_FORM_SUBMISSION_TITLE'] ?? 'New Contact Form Submission') . "</title></head>
        <body>
            <h2>" . ($lang_frontend['CONTACT_FORM_SUBMISSION_TITLE'] ?? 'New Contact Form Submission') . "</h2>
            <table border='1' cellpadding='10' cellspacing='0' style='border-collapse: collapse; font-family: Arial, sans-serif;'>
                <tr>
                    <td><strong>" . ($lang_frontend['CONTACT_FORM_LABEL_NAME'] ?? 'Name:') . "</strong></td>
                    <td>" . htmlspecialchars($name) . "</td>
                </tr>
                <tr>
                    <td><strong>" . ($lang_frontend['CONTACT_FORM_LABEL_EMAIL'] ?? 'Email:') . "</strong></td>
                    <td>" . htmlspecialchars($email) . "</td>
                </tr>
                <tr>
                    <td><strong>" . ($lang_frontend['CONTACT_FORM_LABEL_SUBJECT'] ?? 'Subject:') . "</strong></td>
                    <td>" . htmlspecialchars($subject) . "</td>
                </tr>
                <tr>
                    <td><strong>" . ($lang_frontend['CONTACT_FORM_LABEL_DATE'] ?? 'Date:') . "</strong></td>
                    <td>" . date(DATETIME_FORMAT) . "</td>
                </tr>
                <tr>
                    <td><strong>" . ($lang_frontend['CONTACT_FORM_LABEL_MESSAGE'] ?? 'Message:') . "</strong></td>
                    <td>" . $message . "</td>  
                </tr>
                
            </table>
            <br>
            <p><small>" . sprintf($lang_frontend['CONTACT_FORM_EMAIL_FOOTER'] ?? 'This email was sent via the contact form on %s', SITE_NAME) . "</small></p>
        </body>
        </html>";

        // Set reply-to header so admin can reply directly to the sender
        $additional_headers = [
            'Reply-To' => $email
        ];

        // Send the email
        if (send_custom_email($admin_email, $email_subject, $email_body, $additional_headers)) {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_MESSAGE_SENT_CONTACT'] ?? 'Your message has been sent successfully. We will get back to you soon!', 'success');

            // Log successful contact form submission
            error_log("Contact form submitted successfully from: $email (Name: $name, Subject: $subject)");
        } else {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_MESSAGE_SEND_FAILED'] ?? 'Sorry, there was an error sending your message. Please try again later or contact us directly.', 'danger');

            // Log failed contact form submission
            error_log("Failed to send contact form email from: $email (Name: $name, Subject: $subject)");
        }

        redirectTo('contact');
    }
}
?>
<?php if (defined('USE_LOGO_LOGIN') && USE_LOGO_LOGIN && defined('LOGO_LOGIN_URL') && !empty(LOGO_LOGIN_URL)): ?>
    <center><img src="<?php echo LOGO_LOGIN_URL; ?>" alt="" <?php echo (defined('LOGO_LOGIN_WIDTH') && LOGO_LOGIN_WIDTH) ? 'width="' . LOGO_LOGIN_WIDTH . '"' : ''; ?>><br><br></center>

<?php endif; ?>
<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card shadow">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0"><?php echo $lang_frontend['CONTACT_HEADING'] ?? 'Contact Us'; ?></h4>
            </div>
            <div class="card-body">
                <div class="row mb-4">
                    <div class="col-md-6">
                        <?php if (!empty(SUPPORT_EMAIL) || !empty(CONTACT_EMAIL)): ?>
                            <h5><i class="bi bi-envelope"></i>
                                <?php echo $lang_frontend['CONTACT_SUBHEADING_EMAIL'] ?? 'Email'; ?></h5>
                            <?php if (!empty(SUPPORT_EMAIL)): ?>
                                <p><?php echo $lang_frontend['CONTACT_LABEL_SUPPORT'] ?? 'Support'; ?>:
                                    <?php echo SUPPORT_EMAIL; ?>
                                </p>
                            <?php endif; ?>
                            <?php if (!empty(CONTACT_EMAIL)): ?>
                                <p><?php echo $lang_frontend['CONTACT_LABEL_CONTACT'] ?? 'Contact'; ?>:
                                    <?php echo CONTACT_EMAIL; ?>
                                </p>
                            <?php endif; ?>
                        <?php endif; ?>

                        <?php if (!empty(CONTACT_PHONE_PRIMARY) || !empty(CONTACT_PHONE_SECONDARY)): ?>
                            <h5><i class="bi bi-telephone"></i>
                                <?php echo $lang_frontend['CONTACT_SUBHEADING_PHONE'] ?? 'Phone'; ?></h5>
                            <?php if (!empty(CONTACT_PHONE_PRIMARY)): ?>
                                <p><?php echo CONTACT_PHONE_PRIMARY; ?></p>
                            <?php endif; ?>
                            <?php if (!empty(CONTACT_PHONE_SECONDARY)): ?>
                                <p><?php echo CONTACT_PHONE_SECONDARY; ?></p>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-6">
                        <?php if (!empty(CONTACT_HOURS_WEEKDAY) || !empty(CONTACT_HOURS_SATURDAY) || !empty(CONTACT_HOURS_SUNDAY)): ?>
                            <h5><?php echo $lang_frontend['HEADING_BUSINESS_HOURS'] ?? 'Business Hours'; ?></h5>
                            <?php if (!empty(CONTACT_HOURS_WEEKDAY)): ?>
                                <p>
                                    <strong><?php echo $lang_frontend['CONTACT_TEXT_MON_FRI'] ?? 'Monday - Friday:'; ?></strong><br>
                                    <?php echo CONTACT_HOURS_WEEKDAY; ?>
                                </p>
                            <?php endif; ?>
                            <?php if (!empty(CONTACT_HOURS_SATURDAY)): ?>
                                <p>
                                    <strong><?php echo $lang_frontend['CONTACT_TEXT_SATURDAY'] ?? 'Saturday:'; ?></strong><br>
                                    <?php echo CONTACT_HOURS_SATURDAY; ?>
                                </p>
                            <?php endif; ?>
                            <?php if (!empty(CONTACT_HOURS_SUNDAY)): ?>
                                <p>
                                    <strong><?php echo $lang_frontend['CONTACT_TEXT_SUNDAY'] ?? 'Sunday:'; ?></strong><br>
                                    <?php echo CONTACT_HOURS_SUNDAY; ?>
                                </p>
                            <?php endif; ?>
                        <?php endif; ?>


                        <?php if (defined('SOCIAL_X') && SOCIAL_X !== ''): ?>
                            <a href="<?php echo htmlspecialchars(SOCIAL_X); ?>" target="_blank"><i
                                    class="bi bi-twitter-x"></i></a>&nbsp;&nbsp;
                        <?php endif; ?>
                        <?php if (defined('SOCIAL_FACEBOOK') && SOCIAL_FACEBOOK !== ''): ?>
                            <a href="<?php echo htmlspecialchars(SOCIAL_FACEBOOK); ?>" target="_blank"><i
                                    class="bi bi-facebook"></i></a>&nbsp;&nbsp;
                        <?php endif; ?>
                        <?php if (defined('SOCIAL_INSTAGRAM') && SOCIAL_INSTAGRAM !== ''): ?>
                            <a href="<?php echo htmlspecialchars(SOCIAL_INSTAGRAM); ?>" target="_blank"><i
                                    class="bi bi-instagram"></i></a>&nbsp;&nbsp;
                        <?php endif; ?>
                        <?php if (defined('SOCIAL_LINKEDIN') && SOCIAL_LINKEDIN !== ''): ?>
                            <a href="<?php echo htmlspecialchars(SOCIAL_LINKEDIN); ?>" target="_blank"><i
                                    class="bi bi-linkedin"></i></a>&nbsp;&nbsp;
                        <?php endif; ?>
                        <?php if (defined('SOCIAL_BLUESKY') && SOCIAL_BLUESKY !== ''): ?>
                            <a href="<?php echo htmlspecialchars(SOCIAL_BLUESKY); ?>" target="_blank"><i
                                    class="bi bi-bluesky"></i></a>&nbsp;&nbsp;
                        <?php endif; ?>
                        <?php if (defined('SOCIAL_THREADS') && SOCIAL_THREADS !== ''): ?>
                            <a href="<?php echo htmlspecialchars(SOCIAL_THREADS); ?>" target="_blank"><i
                                    class="bi bi-threads"></i></a>&nbsp;&nbsp;
                        <?php endif; ?>
                        <?php if (defined('SOCIAL_MASTODON') && SOCIAL_MASTODON !== ''): ?>
                            <a href="<?php echo htmlspecialchars(SOCIAL_MASTODON); ?>" target="_blank"><i
                                    class="bi bi-mastodon"></i></a>&nbsp;&nbsp;
                        <?php endif; ?>
                        <?php if (defined('SOCIAL_YOUTUBE') && SOCIAL_YOUTUBE !== ''): ?>
                            <a href="<?php echo htmlspecialchars(SOCIAL_YOUTUBE); ?>" target="_blank"><i
                                    class="bi bi-youtube"></i></a>&nbsp;&nbsp;
                        <?php endif; ?>
                    </div>
                </div>

                <hr>

                <?php if (defined('ENABLE_CONTACT_FORM') && ENABLE_CONTACT_FORM): ?>
                    <h5 class="text-center mb-4">
                        <?php echo $lang_frontend['CONTACT_FORM_HEADING'] ?? 'Send us a Message'; ?>
                    </h5>
                    <form action="<?php echo getCleanUrl('contact'); ?>" method="post" id="contactForm">
                        <?php if (isLoggedIn()): ?>
                            <input type="hidden" name="name"
                                value="<?php echo htmlspecialchars($_SESSION['name'], ENT_QUOTES, 'UTF-8'); ?>">
                            <input type="hidden" name="email"
                                value="<?php echo htmlspecialchars($_SESSION['email'], ENT_QUOTES, 'UTF-8'); ?>">
                        <?php else: ?>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="name"
                                        class="form-label"><?php echo $lang_frontend['FORM_LABEL_YOUR_NAME'] ?? 'Your Name'; ?></label>
                                    <input type="text" class="form-control" id="name" name="name" required>
                                </div>
                                <div class="col-md-6">
                                    <label for="email"
                                        class="form-label"><?php echo $lang_frontend['FORM_LABEL_EMAIL'] ?? 'Email Address'; ?></label>
                                    <input type="email" class="form-control" id="email" name="email" required>
                                </div>
                            </div>
                        <?php endif; ?>
                        <div class="mb-3">
                            <label for="subject"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_SUBJECT'] ?? 'Subject'; ?></label>
                            <input type="text" class="form-control" id="subject" name="subject" required>
                        </div>
                        <div class="mb-3">
                            <label for="message"
                                class="form-label"><?php echo $lang_frontend['CONTACT_FORM_LABEL_MESSAGE'] ?? 'Message'; ?></label>
                            <textarea class="form-control" id="summernote" name="message" rows="5" required></textarea>
                        </div>

                        <?php echo generateHCaptchaField(); ?>

                        <?php echo generateHoneypotField(); ?>

                        <!-- CSRF token -->
                        <input type="hidden" name="csrf_token" value="<?php echo generate_csrf_token(); ?>">

                        <div class="d-grid">
                            <button type="submit"
                                class="btn btn-primary"><?php echo $lang_frontend['CONTACT_BUTTON_SEND_MESSAGE'] ?? 'Send Message'; ?></button>
                        </div>
                    </form>
                    <script>
                        window.magicAIConfig = {
                            AI_OPENAI: '<?php echo AI_OPENAI; ?>',
                            AI_CLAUDE: '<?php echo AI_CLAUDE; ?>',
                            AI_GEMINI: '<?php echo AI_GEMINI; ?>',
                            AI_MISTRAL: '<?php echo AI_MISTRAL; ?>',
                            AI_DEEPSEEK: '<?php echo AI_DEEPSEEK; ?>'
                        };
                    </script>
                    <script>
                        $(document).ready(function () {
                            $('#summernote').summernote({
                                toolbar: [
                                    ['style', ['bold', 'italic', 'underline', 'clear']],
                                    ['para', ['ul', 'ol']],
                                    ['insert', ['link']],
                                    ['magic', ['SummernoteMagic']]
                                ],
                                height: 300,
                                minHeight: 150,
                                maxHeight: null,
                                dialogsFade: true,
                                dialogsInBody: true,
                                tabDisable: false,
                                spellCheck: true
                            });

                            // Bot detection for suspicious name patterns (only for guest users)
                            const nameField = document.getElementById('name');
                            const submitButton = document.querySelector('#contactForm button[type="submit"]');
                            const originalButtonText = submitButton ? submitButton.textContent : '';
                            let isNameSuspicious = false;

                            if (nameField && submitButton) {
                                nameField.addEventListener('input', function () {
                                    checkNamePattern(this.value.trim());
                                });

                                // Also check on form load if name has preserved value
                                if (nameField.value.trim()) {
                                    checkNamePattern(nameField.value.trim());
                                }
                            }

                            function checkNamePattern(name) {
                                if (!name || name.length < 2) {
                                    isNameSuspicious = false;
                                    enableSubmitButton();
                                    return;
                                }

                                // Check for suspicious patterns typical of bots
                                const suspiciousPatterns = [
                                    // All uppercase (but allow single letters/initials)
                                    /^[A-Z\s]{3,}$/,
                                    // Mixed case but with unusual patterns (alternating case, too many capitals)
                                    /^[A-Z][a-z][A-Z][a-z]/,  // Alternating case like "JoHn"
                                    /^[A-Z]{2,}[a-z]+[A-Z]{2,}/, // Multiple caps like "JOHNsmith" or "johnSMITH"
                                    // Too many capital letters in the middle
                                    /[a-z][A-Z]{2,}[a-z]/, // Like "joHNsmith"
                                    // Suspicious character combinations
                                    /[A-Z]{3,}/, // 3 or more consecutive capitals in any position
                                ];

                                // Check if name matches any suspicious pattern
                                isNameSuspicious = suspiciousPatterns.some(pattern => pattern.test(name));

                                if (isNameSuspicious) {
                                    disableSubmitButton();
                                } else {
                                    enableSubmitButton();
                                }
                            }

                            function disableSubmitButton() {
                                if (submitButton && !submitButton.disabled) {
                                    submitButton.disabled = true;
                                    submitButton.style.cursor = 'not-allowed';
                                }
                            }

                            function enableSubmitButton() {
                                if (submitButton && isNameSuspicious === false) {
                                    submitButton.disabled = false;
                                    submitButton.style.cursor = 'pointer';
                                }
                            }

                            // Prevent form submission if name is suspicious
                            document.getElementById('contactForm').addEventListener('submit', function (e) {
                                if (isNameSuspicious) {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    return false;
                                }
                            });
                        });
                    </script>


                <?php else: ?>
                    <div class="alert alert-info text-center">
                        <i
                            class="bi bi-info-circle me-2"></i><?php echo $lang_frontend['CONTACT_FORM_DISABLED_NOTICE'] ?? 'Contact form is currently disabled. Please use the contact information above to reach us.'; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>