<?php
/**
 * VCB-AI Contact Form
 * Saves inquiries to MariaDB
 */

// Database configuration
$db_host = 'raven.aserv.co.za';
$db_port = 3306;
$db_name = 'vcbaioh8w6o6_vcb';
$db_user = 'vcbaioh8w6o6_svc';
$db_pass = '@nB6%#Z6!dvKMB';

$message = '';
$messageType = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $company = trim($_POST['company'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $inquiry = trim($_POST['inquiry'] ?? '');
    
    // Validation
    if (empty($name) || empty($email) || empty($inquiry)) {
        $message = 'Please fill in all required fields.';
        $messageType = 'error';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = 'Please enter a valid email address.';
        $messageType = 'error';
    } else {
        try {
            // Connect to database
            $pdo = new PDO(
                "mysql:host=$db_host;port=$db_port;dbname=$db_name;charset=utf8mb4",
                $db_user,
                $db_pass,
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            
            // Create table if not exists
            $pdo->exec("CREATE TABLE IF NOT EXISTS contact_inquiries (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(255) NOT NULL,
                email VARCHAR(255) NOT NULL,
                company VARCHAR(255),
                phone VARCHAR(50),
                subject VARCHAR(255),
                inquiry TEXT NOT NULL,
                ip_address VARCHAR(45),
                user_agent TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");
            
            // Insert inquiry
            $stmt = $pdo->prepare("INSERT INTO contact_inquiries (name, email, company, phone, subject, inquiry, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $name,
                $email,
                $company,
                $phone,
                $subject,
                $inquiry,
                $_SERVER['REMOTE_ADDR'] ?? '',
                $_SERVER['HTTP_USER_AGENT'] ?? ''
            ]);

            // --- PHP mail() notification (primary) ---
            $notifyTo = 'hello@vcb-ai.online';
            $mailSubject = '[VCB Contact] ' . ($subject ?: 'General Inquiry') . ' — from ' . $name;
            $mailBody  = "New contact form submission\r\n";
            $mailBody .= "===========================\r\n";
            $mailBody .= "Name:    $name\r\n";
            $mailBody .= "Email:   $email\r\n";
            $mailBody .= "Company: " . ($company ?: 'Not provided') . "\r\n";
            $mailBody .= "Phone:   " . ($phone ?: 'Not provided') . "\r\n";
            $mailBody .= "Subject: " . ($subject ?: 'Not provided') . "\r\n\r\n";
            $mailBody .= "Message:\r\n$inquiry\r\n\r\n";
            $mailBody .= "IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . "\r\n";
            $mailHeaders  = "From: noreply@vcb-ai.online\r\n";
            $mailHeaders .= "Reply-To: $email\r\n";
            $mailHeaders .= "X-Mailer: PHP/" . phpversion();
            @mail($notifyTo, $mailSubject, $mailBody, $mailHeaders);
            $configStmt = $pdo->prepare("SELECT key_name, key_value FROM config_keys WHERE is_active = 1");
            $configStmt->execute();
            $config = [];
            while ($row = $configStmt->fetch(PDO::FETCH_ASSOC)) {
                $config[$row['key_name']] = $row['key_value'];
            }
            
            if (!empty($config['emailjs_service_id'])) {
                $emailData = [
                    'service_id' => $config['emailjs_service_id'],
                    'template_id' => $config['emailjs_template_id'],
                    'user_id' => $config['emailjs_public_key'],
                    'accessToken' => $config['emailjs_private_key'],
                    'template_params' => [
                        'name' => $name,
                        'email' => $config['admin_email'],
                        'from_name' => $name,
                        'from_email' => $email,
                        'company' => $company ?: 'Not provided',
                        'phone' => $phone ?: 'Not provided',
                        'subject' => $subject ?: 'Contact Form',
                        'message' => $inquiry,
                        'form_type' => 'Contact Inquiry',
                        'reply_to' => $email
                    ]
                ];
                
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://api.emailjs.com/api/v1.0/email/send');
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($emailData));
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                $emailResult = curl_exec($ch);
                $emailError = curl_error($ch);
                curl_close($ch);
                
                if ($emailError) {
                    error_log('EmailJS Error: ' . $emailError);
                }
            }
            
            $message = 'Thank you for reaching out! We\'ll get back to you within 24 hours.';
            $messageType = 'success';
            
            // Clear form
            $name = $email = $company = $phone = $subject = $inquiry = '';
            
        } catch (PDOException $e) {
            $message = 'Sorry, there was an error processing your request. Please try again later.';
            $messageType = 'error';
            error_log('DB Error: ' . $e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" class="scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Us | VCB-AI</title>
    <meta name="description" content="Get in touch with VCB-AI for enterprise AI solutions, partnerships, and inquiries.">
    <link rel="icon" type="image/png" href="/vcb-logo-black.png">
    
    <!-- Fonts -->
    <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=Quicksand:wght@400;500;600;700&family=Inter:wght@300;400;500&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Sharp:opsz,wght,FILL,GRAD@24,400,0,0&display=swap" rel="stylesheet">
    
    <!-- Tailwind -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        'display': ['Quicksand', 'sans-serif'],
                        'body': ['Inter', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        body { font-family: 'Inter', sans-serif; }
        h1, h2, h3, h4, h5, h6 { font-family: 'Quicksand', sans-serif; font-weight: 400; }
        
        .form-input {
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            padding: 14px 18px;
            color: #111;
            font-size: 16px;
            width: 100%;
            transition: all 0.3s ease;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #000;
            box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.05);
        }
        
        .form-input::placeholder {
            color: #9ca3af;
        }
        
        .form-select {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%236b7280'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 12px center;
            background-size: 20px;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            padding-right: 40px;
        }
    </style>
</head>
<body class="bg-gray-50 text-gray-900 min-h-screen">
    
    <!-- Header -->
    <header class="fixed w-full z-50 top-0">
        <div class="absolute inset-0 bg-gradient-to-b from-black via-black/90 to-black/70 backdrop-blur-md border-b border-white/10"></div>
        <div class="relative max-w-6xl mx-auto flex items-center justify-between px-6 py-0 h-40 sm:h-56">
            <a href="/" class="flex items-center">
                <img src="/vcb-logo-black.png" alt="VCB Logo" class="h-40 sm:h-64 w-auto">
            </a>
            <a href="/" class="flex items-center gap-2 px-5 py-2.5 text-white hover:bg-white/10 rounded-full transition-all text-sm font-bold uppercase tracking-widest">
                <span class="material-symbols-sharp text-lg">arrow_back</span>
                Home
            </a>
        </div>
    </header>
    
    <!-- Main Content -->
    <main class="pt-48 sm:pt-64 pb-12 px-6">
        <div class="max-w-2xl mx-auto">
            
            <!-- Header -->
            <div class="text-center mb-12">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-black mb-6">
                    <span class="material-symbols-sharp text-3xl text-white">mail</span>
                </div>
                
                <h1 class="text-3xl sm:text-4xl font-bold mb-4">
                    Get in Touch
                </h1>
                
                <p class="text-gray-500 max-w-md mx-auto">
                    Have a question about our AI solutions? We'd love to hear from you.
                </p>
            </div>
            
            <?php if ($message): ?>
            <!-- Message -->
            <div class="mb-8 p-4 rounded-xl border <?php echo $messageType === 'success' ? 'bg-emerald-50 border-emerald-200 text-emerald-700' : 'bg-red-50 border-red-200 text-red-700'; ?>">
                <div class="flex items-center gap-3">
                    <span class="material-symbols-sharp"><?php echo $messageType === 'success' ? 'check_circle' : 'error'; ?></span>
                    <p class="font-medium"><?php echo htmlspecialchars($message); ?></p>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- Form -->
            <form method="POST" class="bg-white rounded-2xl p-8 shadow-sm border border-gray-100">
                <div class="space-y-6">
                    
                    <!-- Name & Email -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Full Name *</label>
                            <input type="text" name="name" required 
                                   value="<?php echo htmlspecialchars($name ?? ''); ?>"
                                   placeholder="John Smith"
                                   class="form-input">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Email Address *</label>
                            <input type="email" name="email" required 
                                   value="<?php echo htmlspecialchars($email ?? ''); ?>"
                                   placeholder="john@company.co.za"
                                   class="form-input">
                        </div>
                    </div>
                    
                    <!-- Company & Phone -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Company</label>
                            <input type="text" name="company" 
                                   value="<?php echo htmlspecialchars($company ?? ''); ?>"
                                   placeholder="Your Company (Pty) Ltd"
                                   class="form-input">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Phone Number</label>
                            <input type="tel" name="phone" 
                                   value="<?php echo htmlspecialchars($phone ?? ''); ?>"
                                   placeholder="+27 82 123 4567"
                                   class="form-input">
                        </div>
                    </div>
                    
                    <!-- Subject -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Subject</label>
                        <select name="subject" class="form-input form-select">
                            <option value="">Select a topic...</option>
                            <option value="general" <?php echo ($subject ?? '') === 'general' ? 'selected' : ''; ?>>General Inquiry</option>
                            <option value="sales" <?php echo ($subject ?? '') === 'sales' ? 'selected' : ''; ?>>Sales / Pricing</option>
                            <option value="partnership" <?php echo ($subject ?? '') === 'partnership' ? 'selected' : ''; ?>>Partnership Opportunity</option>
                            <option value="technical" <?php echo ($subject ?? '') === 'technical' ? 'selected' : ''; ?>>Technical Support</option>
                            <option value="media" <?php echo ($subject ?? '') === 'media' ? 'selected' : ''; ?>>Media / Press</option>
                            <option value="careers" <?php echo ($subject ?? '') === 'careers' ? 'selected' : ''; ?>>Careers</option>
                            <option value="other" <?php echo ($subject ?? '') === 'other' ? 'selected' : ''; ?>>Other</option>
                        </select>
                    </div>
                    
                    <!-- Message -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Your Message *</label>
                        <textarea name="inquiry" rows="5" required
                                  placeholder="Tell us how we can help..."
                                  class="form-input resize-none"><?php echo htmlspecialchars($inquiry ?? ''); ?></textarea>
                    </div>
                    
                    <!-- Submit -->
                    <div class="pt-4">
                        <button type="submit" 
                                class="w-full flex items-center justify-center gap-3 px-8 py-4 bg-black text-white font-bold uppercase tracking-wider rounded-xl hover:bg-gray-800 transition-all duration-300">
                            <span class="material-symbols-sharp">send</span>
                            Send Message
                        </button>
                    </div>
                </div>
            </form>
            
            <!-- Alternative Contact -->
            <div class="mt-8 text-center">
                <p class="text-sm text-gray-500 mb-4">Or reach us directly:</p>
                <a href="mailto:info@vcb-ai.online" class="inline-flex items-center gap-2 text-black font-medium hover:underline">
                    <span class="material-symbols-sharp text-lg">mail</span>
                    info@vcb-ai.online
                </a>
            </div>
            
            <!-- Trust Badges -->
            <div class="mt-12 pt-8 border-t border-gray-200">
                <div class="flex flex-wrap items-center justify-center gap-6 text-sm text-gray-400">
                    <div class="flex items-center gap-2">
                        <span class="material-symbols-sharp text-emerald-500 text-lg">verified</span>
                        <span>POPIA Compliant</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="material-symbols-sharp text-blue-500 text-lg">schedule</span>
                        <span>24hr Response</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="material-symbols-sharp text-amber-500 text-lg">location_on</span>
                        <span>Based in SA</span>
                    </div>
                </div>
            </div>
        </div>
    </main>
    
    <!-- Footer -->
    <footer class="py-12 px-6 bg-gray-50 border-t border-gray-100">
        <div class="max-w-6xl mx-auto flex flex-col md:flex-row justify-between items-center gap-6">
            <div class="flex items-center gap-4">
                <img src="/vcb-logo-white.png" alt="VCB Logo" class="h-32 w-auto">
                <div class="flex flex-col">
                    <span class="text-sm text-slate-600">© 2026 Viable Core Business. All rights reserved.</span>
                    <span class="text-xs text-slate-400">Built in South Africa 🇿🇦</span>
                </div>
            </div>
            <div class="flex gap-6">
                <a href="/contact.php" class="text-sm text-slate-500 hover:text-black transition-colors">Contact</a>
                <a href="/LEGAL.html" class="text-sm text-slate-500 hover:text-black transition-colors">Legal</a>
                <a href="/" class="text-sm text-slate-500 hover:text-black transition-colors">Home</a>
            </div>
        </div>
    </footer>
</body>
</html>
