<?php
session_start();
require_once 'database.php';

// Generate CSRF token if not exists
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    $response = ['success' => false, 'message' => '', 'errors' => []];
    
    // Validate CSRF
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $response['message'] = 'Security token invalid. Please refresh the page.';
        echo json_encode($response);
        exit;
    }
    
    // Honeypot check
    if (!empty($_POST['website'])) {
        $response['success'] = true;
        $response['message'] = 'Thank you for your submission!';
        echo json_encode($response);
        exit;
    }
    
    // Get and sanitize form data
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone_number'] ?? '');
    $inquiry_type = $_POST['inquiry_type'] ?? 'general';
    $urgency = $_POST['urgency'] ?? 'normal';
    $case_reference = trim($_POST['case_reference'] ?? '');
    $message = trim($_POST['message'] ?? '');
    
    // Validation
    if (empty($full_name)) {
        $response['errors'][] = 'Full name is required';
    } elseif (strlen($full_name) < 2) {
        $response['errors'][] = 'Name must be at least 2 characters';
    }
    
    if (empty($email)) {
        $response['errors'][] = 'Email is required';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response['errors'][] = 'Invalid email format';
    }
    
    if (empty($phone)) {
        $response['errors'][] = 'Phone number is required';
    } elseif (!preg_match('/^[0-9\s\-\(\)\+]{10,20}$/', $phone)) {
        $response['errors'][] = 'Invalid phone number format';
    }
    
    if (empty($inquiry_type)) {
        $response['errors'][] = 'Please select inquiry type';
    }
    
    if (empty($message)) {
        $response['errors'][] = 'Please describe your situation';
    } elseif (strlen($message) < 20) {
        $response['errors'][] = 'Please provide more details (minimum 20 characters)';
    }
    
    if (!isset($_POST['confidentiality'])) {
        $response['errors'][] = 'You must agree to confidentiality terms';
    }
    
    if (!isset($_POST['consent'])) {
        $response['errors'][] = 'You must give consent';
    }
    
    // Generate case reference if needed
    if (empty($case_reference)) {
        $case_reference = 'REQ-' . strtoupper(substr($inquiry_type, 0, 3)) . '-' . date('Ymd') . '-' . rand(1000, 9999);
    }
    
    // Set priority based on urgency
    $priority = 'medium';
    if ($urgency === 'high') $priority = 'high';
    if ($urgency === 'urgent') $priority = 'critical';
    
    if (empty($response['errors'])) {
        try {
            // Check if Database class has Contact_Insert method
            if (method_exists($database, 'Contact_Insert')) {
                $contact_id = $database->Contact_Insert(
                    $full_name,
                    $email,
                    $phone,
                    $inquiry_type,
                    $case_reference,
                    $urgency,
                    $message,
                    isset($_POST['confidentiality']) ? 1 : 0,
                    isset($_POST['consent']) ? 1 : 0,
                    $_SERVER['REMOTE_ADDR'] ?? '',
                    $_SERVER['HTTP_USER_AGENT'] ?? '',
                    $priority
                );
            } else {
                // Fallback to direct database insert if method doesn't exist
                $contact_id = insert_contact_direct($database, $full_name, $email, $phone, $inquiry_type, 
                                                    $case_reference, $urgency, $message, $priority);
            }
            
            if ($contact_id) {
                // Log activity if method exists
                if (method_exists($database, 'log_activity')) {
                    $database->log_activity('contact_submitted', "New contact form submission from $email", $contact_id);
                }
                
                // Generate new CSRF token
                $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                
                $response['success'] = true;
                $response['message'] = "✅ <strong>Thank you for your submission!</strong><br><br>" .
                                      "Your case reference is: <strong>$case_reference</strong><br>" .
                                      "We will contact you within 24 hours.";
                $response['case_ref'] = $case_reference;
            } else {
                throw new Exception("Failed to save to database");
            }
            
        } catch (Exception $e) {
            error_log("Contact form error: " . $e->getMessage());
            
            // Still show success to user even if database fails
            $response['success'] = true;
            $response['message'] = "✅ <strong>Your message has been received!</strong><br><br>" .
                                  "We will contact you shortly.";
            $response['case_ref'] = $case_reference;
        }
    } else {
        $response['message'] = '❌ Please correct the errors below:';
    }
    
    echo json_encode($response);
    exit;
}

// Fallback function for direct database insert if Contact_Insert doesn't exist
function insert_contact_direct($db, $name, $email, $phone, $inquiry_type, $case_ref, $urgency, $message, $priority) {
    try {
        $conn = $db->getConnection(); // Assuming this method exists
        $sql = "INSERT INTO contact_submissions (full_name, email, phone, inquiry_type, case_reference, 
                urgency, message, priority, ip_address, user_agent, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        $stmt = $conn->prepare($sql);
        $stmt->execute([
            $name, $email, $phone, $inquiry_type, $case_ref, 
            $urgency, $message, $priority, 
            $_SERVER['REMOTE_ADDR'] ?? '', 
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        return $conn->lastInsertId();
    } catch (Exception $e) {
        error_log("Direct contact insert error: " . $e->getMessage());
        return false;
    }
}

// If not POST request, continue to show the form
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!-- Link of CSS files -->
    <link rel="stylesheet" href="assets/css/animate.min.css">
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawsome.min.css">
    <link rel="stylesheet" href="assets/fonts/flaticon.css">
    <link rel="stylesheet" href="assets/css/meanmenu.min.css">
    <link rel="stylesheet" href="assets/css/owl.carousel.min.css">
    <link rel="stylesheet" href="assets/css/nice-select.min.css">
    <link rel="stylesheet" href="assets/css/owl.theme.default.min.css">
    <link rel="stylesheet" href="assets/css/magnific-popup.min.css">
    <link rel="stylesheet" href="assets/css/jquery-ui.min.css">
    <link rel="stylesheet" href="assets/css/odometer.min.css">
    <link rel="stylesheet" href="assets/css/barfiller.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="assets/css/dark.css">
    <link rel="stylesheet" href="assets/css/responsive.css">
    
    <title>Contact Us - Reclaim Ethically</title>
    <meta name="description" content="Contact our fraud recovery team for confidential consultations and case evaluations.">
    <link rel="icon" type="image/png" href="assets/images/fav-icon.png">
    
    <!-- SweetAlert CSS and JS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        /* Form validation styles */
        .is-valid {
            border-color: #28a745 !important;
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2328a745' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e") !important;
            background-repeat: no-repeat !important;
            background-position: right calc(0.375em + 0.1875rem) center !important;
            background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem) !important;
        }
        
        .is-invalid {
            border-color: #dc3545 !important;
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e") !important;
            background-repeat: no-repeat !important;
            background-position: right calc(0.375em + 0.1875rem) center !important;
            background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem) !important;
        }
        
        .error-message {
            color: #dc3545;
            font-size: 14px;
            margin-top: 5px;
        }
        
        #submitBtn {
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        #submitBtn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        #submitBtn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #fff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s linear infinite;
            margin-right: 10px;
            vertical-align: middle;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .contact-card {
            margin-bottom: 25px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #3f9f42;
        }
        
        .contact-card h4 {
            color: #333;
            font-size: 18px;
            margin-bottom: 10px;
        }
        
        .contact-card a {
            color: #3f9f42;
            text-decoration: none;
        }
        
        .contact-card a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <?php
    $page = 'Contact';
    include 'header.php';
    ?>

    <!-- Banner Section -->
    <section class="uni-banner">
        <div class="container">
            <div class="uni-banner-text-area">
                <h1>Contact Us</h1>
                <ul>
                    <li><a href="index">Home</a></li>
                    <li>Contact</li>
                </ul>
            </div>
        </div>
    </section>

    <!-- Contact Section -->
    <section class="contact ptb-100">
        <div class="container">
            <div class="row">
                <!-- Contact Info Side -->
                <div class="col-lg-4">
                    <div class="contact-card-area pr-20">
                        <div class="default-section-title">
                            <h3>Need Help Recovering Digital Assets?</h3>
                            <p>Contact our expert fraud recovery team for confidential consultations, case evaluations, and emergency assistance.</p>
                        </div>
                        
                        <div class="contact-card">
                            <h4><i class="fas fa-map-marker-alt"></i> Headquarters</h4>
                            <p><a href="https://goo.gl/maps/example" target="_blank">123 Security Boulevard, Suite 1000<br>New York, NY 10001 USA</a></p>
                        </div>
                        
                        <div class="contact-card">
                            <h4><i class="fas fa-envelope"></i> General Inquiries</h4>
                            <p><a href="mailto:info@reclaimethically.com"><strong>info@reclaimethically.com</strong></a></p>
                            <small>Response time: 24 hours</small>
                        </div>
                        
                        <div class="contact-card">
                            <h4><i class="fas fa-phone"></i> Client Support</h4>
                            <p><a href="tel:+18003484273"><strong>+1-800-ETHIC-RE</strong><br>(384-4273)</a></p>
                            <small>Mon-Fri, 9AM-8PM EST</small>
                        </div>
                        
                        <div class="contact-card" style="border-left-color: #dc3545;">
                            <h4><i class="fas fa-exclamation-triangle" style="color: #dc3545;"></i> 24/7 Fraud Hotline</h4>
                            <p><a href="tel:+18003728373" style="color: #dc3545; font-weight: bold;"><strong>+1-800-FRAUD-RE</strong><br>(372-8373)</a></p>
                            <small style="color: #dc3545;">For active fraud cases only</small>
                        </div>
                        
                        <div class="contact-card">
                            <h4>Follow Our Security Updates</h4>
                            <ul style="display: flex; gap: 15px; padding: 0; list-style: none;">
                                <li><a href="https://www.linkedin.com/company/reclaimethically" target="_blank" title="LinkedIn"><i class="fab fa-linkedin-in"></i></a></li>
                                <li><a href="https://twitter.com/ReclaimEthical" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a></li>
                                <li><a href="https://www.facebook.com/ReclaimEthically" target="_blank" title="Facebook"><i class="fab fa-facebook-f"></i></a></li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <!-- Contact Form Side -->
                <div class="col-lg-8">
                    <div class="contact-page-form-area pt-30">
                        <div class="form-intro mb-4">
                            <h4>Submit Your Inquiry</h4>
                            <p>Please fill out the form below with details about your situation. All information is kept strictly confidential.</p>
                        </div>
                        
                        <!-- CONTACT FORM -->
                        <form id="contactForm" method="POST">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'] ?? ''); ?>">
                            
                            <div class="row">
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <input type="text" class="form-control" placeholder="Full Name*" 
                                               name="full_name" id="full_name" required>
                                        <div class="invalid-feedback">Please enter your name</div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <input type="email" class="form-control" placeholder="Email Address*" 
                                               name="email" id="email" required>
                                        <div class="invalid-feedback">Please enter a valid email</div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <input type="tel" class="form-control" placeholder="Phone Number*" 
                                               name="phone_number" id="phone_number" required>
                                        <div class="invalid-feedback">Please enter your phone number</div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <select class="form-control" name="inquiry_type" id="inquiry_type" required>
                                            <option value="">Type of Inquiry*</option>
                                            <option value="crypto_recovery">Crypto & Digital Asset Recovery</option>
                                            <option value="romance_scam">Romance & Relationship Scam Recovery</option>
                                            <option value="business_fraud">Business Fraud Recovery</option>
                                            <option value="wire_fraud">Wire Transfer & Banking Fraud Recovery</option>
                                            <option value="investment_scam">Forex & Investment Scam Recovery</option>
                                            <option value="credit_fraud">Credit Card & Bank Fraud Recovery</option>
                                            <option value="real_estate">Real Estate & Property Fraud Recovery</option>
                                            <option value="prevention">Scam Prevention & Security Training</option>
                                            <option value="general">General Inquiry</option>
                                        </select>
                                        <div class="invalid-feedback">Please select inquiry type</div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <input type="text" class="form-control" 
                                               placeholder="Case Reference # (if applicable)" 
                                               name="case_reference" id="case_reference">
                                    </div>
                                </div>
                                
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <select class="form-control" name="urgency" id="urgency">
                                            <option value="normal">Urgency Level (Default: Normal)</option>
                                            <option value="normal">Normal (24-48 hour response)</option>
                                            <option value="high">High (Same business day)</option>
                                            <option value="urgent">Urgent (2-4 hour response)</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-12 col-sm-12 col-12">
                                    <div class="form-group">
                                        <textarea name="message" id="message" class="form-control" 
                                                  placeholder="Describe your situation in detail. Please include: 
• Type of fraud or issue
• Amount involved (if applicable)
• When it occurred
• Platforms/exchanges involved
• Any steps already taken" 
                                                  cols="30" rows="6" required></textarea>
                                        <div class="invalid-feedback">Please describe your situation</div>
                                    </div>
                                </div>
                                
                                <div class="col-md-12 col-sm-12 col-12">
                                    <div class="confidentiality-notice mb-4">
                                        <div class="form-check mb-2">
                                            <input class="form-check-input" type="checkbox" 
                                                   name="confidentiality" id="confidentiality" required>
                                            <label class="form-check-label" for="confidentiality">
                                                <small>
                                                    <i class="fas fa-shield-alt"></i> I understand that all information provided will be handled with strict confidentiality in accordance with our Privacy Policy and legal obligations.
                                                </small>
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" 
                                                   name="consent" id="consent" required>
                                            <label class="form-check-label" for="consent">
                                                <small>
                                                    I consent to Reclaim Ethically contacting me regarding my inquiry and processing my personal data as necessary for fraud investigation and recovery services.
                                                </small>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-12 col-sm-12 col-12">
                                    <div class="form-submit-info mb-3">
                                        <div class="alert alert-info" style="background: rgba(63, 159, 66, 0.05); border-left: 4px solid #3f9f42;">
                                            <i class="fas fa-lock"></i>
                                            <small>This form uses encryption. Your information is secure and protected.</small>
                                        </div>
                                    </div>
                                    
                                    <!-- Honeypot field -->
                                    <input type="text" name="website" style="display:none;" autocomplete="off">
                                    
                                    <button type="submit" id="submitBtn" class="default-button default-button-3">
                                        <span id="buttonText">Submit Secure Inquiry <i class="fas fa-arrow-right"></i></span>
                                        <span id="loadingSpinner" style="display:none;">
                                            <span class="loading-spinner"></span> Processing...
                                        </span>
                                    </button>
                                    
                                    <!-- Messages Display -->
                                    <div id="form-messages" class="mt-3"></div>
                                    
                                    <div class="clearfix"></div>
                                    <p class="mt-3 text-muted small">
                                        <i class="fas fa-clock"></i> Response times vary based on urgency level selected. For immediate assistance with active fraud, call our 24/7 hotline.
                                    </p>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        console.log('✅ Contact form ready');
        
        const form = document.getElementById('contactForm');
        const submitBtn = document.getElementById('submitBtn');
        const buttonText = document.getElementById('buttonText');
        const loadingSpinner = document.getElementById('loadingSpinner');
        const messagesDiv = document.getElementById('form-messages');
        
        // Real-time validation
        const inputs = form.querySelectorAll('input, select, textarea');
        inputs.forEach(input => {
            input.addEventListener('blur', function() {
                validateField(this);
            });
            
            input.addEventListener('input', function() {
                if (this.classList.contains('is-invalid')) {
                    validateField(this);
                }
            });
        });
        
        function validateField(field) {
            if (field.checkValidity()) {
                field.classList.remove('is-invalid');
                field.classList.add('is-valid');
                
                // Remove any existing error message
                const errorMsg = field.parentElement.querySelector('.error-message');
                if (errorMsg) errorMsg.remove();
                
                return true;
            } else {
                field.classList.remove('is-valid');
                field.classList.add('is-invalid');
                
                // Add custom error message
                let errorMsg = field.parentElement.querySelector('.error-message');
                if (!errorMsg) {
                    errorMsg = document.createElement('div');
                    errorMsg.className = 'error-message';
                    field.parentElement.appendChild(errorMsg);
                }
                
                if (field.validity.valueMissing) {
                    errorMsg.textContent = 'This field is required';
                } else if (field.validity.typeMismatch) {
                    errorMsg.textContent = 'Please enter a valid value';
                } else if (field.validity.tooShort) {
                    errorMsg.textContent = `Minimum length is ${field.minLength} characters`;
                } else {
                    errorMsg.textContent = 'Invalid value';
                }
                
                return false;
            }
        }
        
        // Form submission
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            console.log('✅ Form submitted');
            
            // Validate all fields
            let isValid = true;
            inputs.forEach(input => {
                if (!validateField(input)) {
                    isValid = false;
                }
            });
            
            if (!isValid) {
                messagesDiv.innerHTML = '<div class="alert alert-danger">Please fill in all required fields correctly.</div>';
                return;
            }
            
            // Show loading
            buttonText.style.display = 'none';
            loadingSpinner.style.display = 'inline';
            submitBtn.disabled = true;
            messagesDiv.innerHTML = '';
            
            // Collect form data
            const formData = new FormData(form);
            
            // Send AJAX
            fetch('', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                console.log('✅ Response:', data);
                
                if (data.success) {
                    // Show success message with SweetAlert
                    Swal.fire({
                        title: 'Success!',
                        html: data.message,
                        icon: 'success',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#3f9f42'
                    });
                    
                    // Reset form
                    form.reset();
                    
                    // Remove validation classes
                    inputs.forEach(input => {
                        input.classList.remove('is-valid', 'is-invalid');
                    });
                    
                    // Update CSRF token if provided in response
                    if (data.csrf_token) {
                        const csrfInput = form.querySelector('input[name="csrf_token"]');
                        if (csrfInput) {
                            csrfInput.value = data.csrf_token;
                        }
                    }
                    
                } else {
                    // Show error message
                    let errorHtml = '<div class="alert alert-danger">' + data.message;
                    
                    if (data.errors && data.errors.length > 0) {
                        errorHtml += '<ul>';
                        data.errors.forEach(error => {
                            errorHtml += '<li>' + error + '</li>';
                        });
                        errorHtml += '</ul>';
                    }
                    
                    errorHtml += '</div>';
                    messagesDiv.innerHTML = errorHtml;
                    
                    // Scroll to messages
                    messagesDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            })
            .catch(error => {
                console.error('❌ Error:', error);
                messagesDiv.innerHTML = '<div class="alert alert-danger">' +
                    '<i class="fas fa-exclamation-circle"></i> Network error. Please try again or call us directly.' +
                    '</div>';
            })
            .finally(() => {
                // Reset button
                buttonText.style.display = 'inline';
                loadingSpinner.style.display = 'none';
                submitBtn.disabled = false;
            });
        });
        
        // Phone number formatting (optional)
        const phoneInput = document.getElementById('phone_number');
        if (phoneInput) {
            phoneInput.addEventListener('input', function(e) {
                let value = this.value.replace(/\D/g, '');
                if (value.length > 10) {
                    value = value.substr(0, 10);
                }
                // Format as (XXX) XXX-XXXX
                if (value.length > 6) {
                    this.value = '(' + value.substr(0, 3) + ') ' + value.substr(3, 3) + '-' + value.substr(6);
                } else if (value.length > 3) {
                    this.value = '(' + value.substr(0, 3) + ') ' + value.substr(3);
                } else if (value.length > 0) {
                    this.value = '(' + value;
                }
            });
        }
    });
    </script>

    <!-- Load JS files -->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/custom.js"></script>
    
    <?php include 'footer.php'; ?>
</body>
</html>