<?php
require_once 'csp_config.php';
require_once 'config_loader.php';
require_once 'CsrfProtection.php';

$currentDir = trim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
$depth = ($currentDir === '') ? 0 : (substr_count($currentDir, '/') + 1);
$urlPrefix = ($depth === 0) ? '' : str_repeat('../', $depth);

// Generate and send CSP header
send_security_headers();

// Start session for CSRF protection
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$pageTitle = 'Contact Form - Mark\'s Tech Solution';
?>

<!DOCTYPE html>
<html lang="en">
<html lang="en">
<head>
    <script src="https://www.google.com/recaptcha/enterprise.js?render=6LeUoSksAAAAAG7oSdSl4zKoBxmo7e1Pq5nih2iU"></script>
    <meta name="google-adsense-account" content="ca-pub-9807741295373154">
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9807741295373154"
     crossorigin="anonymous"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Professional computer repair, network setup, and IT support services in East Weymouth, MA. On-site tech support, custom PC builds, and reliable tech solutions.">
    <meta name="keywords" content="computer repair, IT support, network setup, tech support, East Weymouth, MA, custom PC builds, wifi installation, computer services">
    <meta name="author" content="Mark's Tech Solution">
    <meta name="robots" content="index, follow">
    
    <!-- Open Graph / Facebook -->
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://markstechsolution.com/">
    <meta property="og:title" content="Mark's Tech Solution - Professional IT Services in East Weymouth, MA">
    <meta property="og:description" content="Expert computer repair, network setup, and IT support services. Serving East Weymouth and surrounding areas with reliable tech solutions.">
    <meta property="og:image" content="https://markstechsolution.com/images/og-image.jpg">
    <meta property="og:site_name" content="Mark's Tech Solution">
    <meta property="og:locale" content="en_US">
    
    <!-- Twitter -->
    <meta property="twitter:card" content="summary_large_image">
    <meta property="twitter:url" content="https://markstechsolution.com/">
    <meta property="twitter:title" content="Mark's Tech Solution - Professional IT Services">
    <meta property="twitter:description" content="Expert computer repair, network setup, and IT support services in East Weymouth, MA.">
    <meta property="twitter:image" content="https://markstechsolution.com/images/twitter-image.jpg">
    
    <!-- Additional SEO -->
    <link rel="canonical" href="https://markstechsolution.com/">
    <meta name="geo.region" content="US-MA">
    <meta name="geo.placename" content="East Weymouth">
    <meta name="geo.position" content="42.226008;-70.945108">
    <meta name="ICBM" content="42.226008, -70.945108">
    <title><?php echo htmlspecialchars($pageTitle ?? "Mark's Tech Solution - Your Local Tech Experts", ENT_QUOTES, 'UTF-8'); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap" rel="stylesheet">
    <title>Contact Us - Mark's Tech Solution</title>
    <?php if (!empty($extraHead)) { echo $extraHead; } ?>
    <link rel="stylesheet" href="contact_form_styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
    <!-- Skip Navigation -->
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark fixed-top">
    <div class="container">
        <a class="navbar-brand" href="<?php echo $urlPrefix; ?>Main_Site/index.php">
            <div class="logo-placeholder">MTS</div>
        </a>
        
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
       
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ms-auto">
                <li class="nav-item">
                    <a class="nav-link" href="tel:6173026011">
                        <i class="fas fa-phone-alt me-1"></i> (617) 302-6011
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="mailto:m.geden01@markstechsolution.com?subject=Website%20Inquiry">
                        <i class="fas fa-envelope me-2"></i>Email Us
                    </a>
                </li>
            </ul>
        </div>
    </div>
</nav>
    
    <div class="page-container">
        <!-- Orange Header Section -->
        <section class="header-section">
            <h1>Contact Mark's Tech Solution</h1>
            <p>Get in touch with your local tech experts in East Weymouth, MA</p>
            <div class="header-button">
            </div>
        </section>

        <!-- Middle Section - Contact Form -->
        <section class="middle-section">
            <div class="contact-form-wrapper">
                <h2>Send Us a Message</h2>
                
                <div id="formMessage" class="message hidden"></div>
                
                <form id="contactForm">
                    <?php
                    // Include CSRF token
                    require_once 'CsrfProtection.php';
                    echo CsrfProtection::getHtmlInput();
                    ?>
                    
                    <div class="form-group">
                        <label for="name">Name *</label>
                        <input type="text" id="name" name="name" required maxlength="100">
                    </div>
                    
                    <div class="form-group">
                        <label for="email">Email *</label>
                        <input type="email" id="email" name="email" required maxlength="255">
                    </div>
                    
                    <div class="form-group">
                        <label for="message">Message *</label>
                        <textarea id="message" name="message" required maxlength="5000"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <div class="g-recaptcha" data-sitekey="6Le34S8sAAAAAMfcryPhfaCmlXN48b3pQwdpw7so"></div>
                    </div>
                    
                    <button type="submit" id="submitBtn">Send Message</button>
                </form>
                
                <div class="recaptcha-badge">
                    This site is protected by reCAPTCHA and the Google 
                    <a href="https://policies.google.com/privacy">Privacy Policy</a> and 
                    <a href="https://policies.google.com/terms">Terms of Service</a> apply.
                </div>
                
                <div id="rateLimitInfo" class="rate-limit-info hidden"></div>
            </div>
        </section>

  <?php include __DIR__ . '/components/footer.php'; ?>
    </div>

    <script>
        // Configuration
        const RECAPTCHA_SITE_KEY = '6Le34S8sAAAAAMfcryPhfaCmlXN48b3pQwdpw7so';
        const RECAPTCHA_ACTION = 'submit';
        const CSRF_TOKEN = 'csrf_token';
        
        // Form elements
        const form = document.getElementById('contactForm');
        const submitBtn = document.getElementById('submitBtn');
        const messageDiv = document.getElementById('formMessage');
        const rateLimitDiv = document.getElementById('rateLimitInfo');
        
        // Show message
        function showMessage(message, type = 'info') {
            messageDiv.textContent = message;
            messageDiv.className = `message ${type}`;
            messageDiv.classList.remove('hidden');
            
            // Auto-hide success messages after 10 seconds
            if (type === 'success') {
                setTimeout(() => {
                    messageDiv.classList.add('hidden');
                }, 10000);
            }
        }
        
        // Hide message
        function hideMessage() {
            messageDiv.classList.add('hidden');
        }
        
        // Set loading state
        function setLoading(loading) {
            submitBtn.disabled = loading;
            submitBtn.textContent = loading ? 'Sending...' : 'Send Message';
        }
        
        // Show rate limit info
        function showRateLimitInfo(remaining, resetTime) {
            if (remaining < 3) {
                rateLimitDiv.textContent = `You have ${remaining} attempts remaining. Resets in ${resetTime} seconds.`;
                rateLimitDiv.classList.remove('hidden');
            } else {
                rateLimitDiv.classList.add('hidden');
            }
        }
        
        // Form submission
        form.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            hideMessage();
            setLoading(true);
            
            try {
                // Get reCAPTCHA response
                const recaptchaResponse = grecaptcha.getResponse();
                if (!recaptchaResponse) {
                    throw new Error('Please complete the reCAPTCHA challenge.');
                }
                
                // Prepare form data
                const formData = new FormData(form);
                formData.append('g-recaptcha-response', recaptchaResponse);
                
                // Debug: Check if CSRF token is included
                console.log('CSRF token value:', formData.get('csrf_token'));
                
                // Submit form
                const response = await fetch('process_form_secure.php', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showMessage(result.message, 'success');
                    form.reset();
                    
                    // Generate new CSRF token for next submission
                    const csrfResponse = await fetch('csrf_token.php');
                    const csrfData = await csrfResponse.json();
                    const csrfInput = form.querySelector(`input[name="${CSRF_TOKEN}"]`);
                    if (csrfInput && csrfData.token) {
                        csrfInput.value = csrfData.token;
                    }
                    
                    console.log('Form submission successful, redirecting to index.php...');
                    
                    // Redirect to index.php after 2 seconds
                    setTimeout(() => {
                        console.log('Executing redirect to index.php');
                        try {
                            window.location.href = 'index.php';
                        } catch (error) {
                            console.error('Error redirecting to index.php:', error);
                        }
                    }, 2000);
                } else {
                    throw new Error(result.message || 'An error occurred');
                }
                
            } catch (error) {
                console.error('Form submission error:', error);
                showMessage(error.message || 'An error occurred. Please try again.', 'error');
            } finally {
                setLoading(false);
            }
        });
        
        // Form validation
        form.addEventListener('input', function(e) {
            const input = e.target;
            const value = input.value.trim();
            
            // Basic validation
            if (input.required && !value) {
                input.style.borderColor = '#e74c3c';
            } else if (input.type === 'email' && value && !input.validity.valid) {
                input.style.borderColor = '#e74c3c';
            } else {
                input.style.borderColor = '#ddd';
            }
        });
        
        // Character counter for message field
        const messageTextarea = document.querySelector('textarea[name="message"]');
        messageTextarea.addEventListener('input', function() {
            const remaining = 5000 - this.value.length;
            if (remaining < 100) {
                console.log(`Characters remaining: ${remaining}`);
            }
        });
        
        // Initialize (reCAPTCHA loads automatically)
    </script>
</body>
</html>