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

// 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">
<head>
    <!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-317231418"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'AW-317231418');
</script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-2LD3RECBYF"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-2LD3RECBYF');
</script><!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-Q9ZQXB9TDH">
</script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-Q9ZQXB9TDH');
  gtag('event', 'ads_conversion_click_1', {});
</script>
    <!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-W4G4XMPD');</script>
<!-- End Google Tag Manager -->
    <script src="https://www.google.com/recaptcha/api.js" async defer></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="Contact Mark's Tech Solution for computer repair, network setup, IT support, custom PC builds, and tech services in East Weymouth, MA. Request a free quote or schedule on-site service today.">
    <meta name="keywords" content="contact Mark's Tech Solution, computer repair quote, IT support request, network setup consultation, custom PC build quote, on-site tech support, East Weymouth, Weymouth, South Shore MA, Norfolk County, laptop repair, desktop repair, virus removal, WiFi repair, printer setup, business IT support, home computer repair">
    <meta name="author" content="Mark's Tech Solution">
    <meta name="robots" content="index, follow, max-image-preview:large">
    <meta name="theme-color" content="#ff6600">
    <meta name="msapplication-TileColor" content="#ff6600">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="strict-origin-when-cross-origin">
    <meta name="format-detection" content="telephone=yes">

    <!-- Open Graph / Facebook -->
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://markstechsolution.com/contact.php">
    <meta property="og:title" content="Contact Mark's Tech Solution - Computer Repair & IT Support in East Weymouth, MA">
    <meta property="og:description" content="Request a quote or schedule service for computer repair, network setup, IT support, and custom PC builds in East Weymouth, MA.">
    <meta property="og:image" content="https://markstechsolution.com/assets/square-white-logo-og-image.png">
    <meta property="og:image:width" content="1200">
    <meta property="og:image:height" content="630">
    <meta property="og:image:alt" content="Contact Mark's Tech Solution">
    <meta property="og:site_name" content="Mark's Tech Solution">
    <meta property="og:locale" content="en_US">
    <meta property="og:phone_number" content="+1-339-746-0995">

    <!-- Twitter -->
    <meta property="twitter:card" content="summary_large_image">
    <meta property="twitter:domain" content="markstechsolution.com">
    <meta property="twitter:url" content="https://markstechsolution.com/contact.php">
    <meta property="twitter:title" content="Contact Mark's Tech Solution - Computer Repair & IT Support in East Weymouth, MA">
    <meta property="twitter:description" content="Request a quote or schedule service for computer repair, network setup, IT support, and custom PC builds in East Weymouth, MA.">
    <meta property="twitter:image" content="https://markstechsolution.com/assets/square-white-logo-og-image.png">
    <meta property="twitter:image:alt" content="Contact Mark's Tech Solution">

    <!-- Additional SEO -->
    <link rel="canonical" href="https://markstechsolution.com/contact.php">
    <link rel="apple-touch-icon" href="assets/favicon.png">
    <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">
    <?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>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-W4G4XMPD"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
    <!-- Skip Navigation -->
    <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" id="contact-form">
            <div id="formContainer" 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" data-action="submit" data-callback="onRecaptchaSuccess"></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>

        <!-- Customer Reviews Section -->
        <section class="contact-reviews-section">
            <div class="container">
                <div class="contact-reviews-header">
                    <div class="contact-google-badge">
                        <span class="contact-badge-rating">4.6</span>
                        <span class="contact-badge-stars">
                            <i class="fas fa-star"></i>
                            <i class="fas fa-star"></i>
                            <i class="fas fa-star"></i>
                            <i class="fas fa-star"></i>
                            <i class="fas fa-star-half-alt"></i>
                        </span>
                        <span class="contact-badge-text">Google rating · 9 reviews</span>
                    </div>
                    <h2>Loved by Local Customers</h2>
                    <p>See why East Weymouth homeowners and businesses trust Mark with their tech.</p>
                </div>
                <div class="contact-reviews-grid">
                    <div class="contact-review-card">
                        <div class="contact-review-stars"><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i></div>
                        <p>"My laptop keyboard had not been working for several months and Mark both diagnosed and solved my issue same day, and most importantly was able to avoid a costly parts replacement. Very grateful!"</p>
                        <footer>— Dan Yotive</footer>
                    </div>
                    <div class="contact-review-card">
                        <div class="contact-review-stars"><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i></div>
                        <p>"Mark was incredibly responsive and helpful. He arrived on time, worked diligently through the troubleshooting process, and showed a genuine commitment to resolving the issue. It's clear he truly cares about his clients. A pleasure to work with."</p>
                        <footer>— Jill Collmer</footer>
                    </div>
                    <div class="contact-review-card">
                        <div class="contact-review-stars"><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i></div>
                        <p>"Fantastic service! Quick and efficient. Would recommend to all family & friends!"</p>
                        <footer>— Siobhan Carroll</footer>
                    </div>
                </div>
                <div class="text-center mt-4">
                    <a href="https://www.google.com/search?q=Mark%27s+Tech+Solution+Weymouth+reviews" target="_blank" rel="noopener noreferrer" class="contact-reviews-link">
                        <i class="fab fa-google me-2"></i>Read all reviews on Google
                    </a>
                </div>
            </div>
        </section>

  <?php include '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');
        
        // reCAPTCHA v3 token
        let recaptchaToken = null;
        
        // reCAPTCHA v3 success callback
        function onRecaptchaSuccess(token) {
            recaptchaToken = token;
            console.log('reCAPTCHA v3 token received');
        }
        
        // Execute reCAPTCHA v3
        window.onloadCallback = function() {
            grecaptcha.ready(function() {
                grecaptcha.execute('6Le34S8sAAAAAMfcryPhfaCmlXN48b3pQwdpw7so', {
                    action: RECAPTCHA_ACTION,
                    callback: onRecaptchaSuccess
                }).then(function(token) {
                    recaptchaToken = token;
                    console.log('reCAPTCHA v3 executed');
                });
            });
        };
        
        // 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 v3 token
                const recaptchaResponse = recaptchaToken;
                if (!recaptchaResponse) {
                    throw new Error('reCAPTCHA verification failed. Please refresh the page.');
                }
                
                // Prepare form data
                const formData = new FormData(form);
                formData.append('g-recaptcha-response', recaptchaResponse);
                formData.append('recaptcha-action', RECAPTCHA_ACTION);
                
                // 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>