<?php
header('Content-Type: application/json');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Function to send email
function sendContactEmail($data) {
    $to = 'admin@kongutourister.com'; // Replace with actual admin email
    $subject = 'New Contact Form Submission - KONGU TOURISTER';
    
    $message = "
    <html>
    <head>
        <title>New Contact Form Submission</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: linear-gradient(135deg, #1e3a8a, #3b82f6); color: white; padding: 20px; text-align: center; }
            .content { padding: 20px; background: #f8fafc; }
            .field { margin-bottom: 15px; }
            .label { font-weight: bold; color: #1e3a8a; }
            .footer { background: #1f2937; color: white; padding: 15px; text-align: center; font-size: 12px; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2><i class='bi bi-compass-fill'></i> KONGU TOURISTER</h2>
                <h3>New Contact Form Submission</h3>
            </div>
            <div class='content'>
                <div class='field'>
                    <span class='label'>Name:</span> " . htmlspecialchars($data['name']) . "
                </div>
                <div class='field'>
                    <span class='label'>Email:</span> " . htmlspecialchars($data['email']) . "
                </div>
                <div class='field'>
                    <span class='label'>Mobile:</span> " . htmlspecialchars($data['mobile']) . "
                </div>
                <div class='field'>
                    <span class='label'>City:</span> " . htmlspecialchars($data['city']) . "
                </div>
                <div class='field'>
                    <span class='label'>Message:</span><br>
                    " . nl2br(htmlspecialchars($data['message'])) . "
                </div>
                <div class='field'>
                    <span class='label'>Submission Date:</span> " . date('Y-m-d H:i:s') . "
                </div>
                <div class='field'>
                    <span class='label'>IP Address:</span> " . $_SERVER['REMOTE_ADDR'] . "
                </div>
            </div>
            <div class='footer'>
                <p>&copy; 2024 KONGU TOURISTER. All rights reserved.</p>
                <p>Premium Travel Luggage & Accessories</p>
            </div>
        </div>
    </body>
    </html>";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: noreply@kongutourister.com" . "\r\n";
    $headers .= "Reply-To: " . $data['email'] . "\r\n";
    
    return mail($to, $subject, $message, $headers);
}

// Function to send WhatsApp message
function sendContactWhatsApp($data) {
    // WhatsApp API integration (you'll need to set up WhatsApp Business API)
    // For now, we'll create a WhatsApp link that can be clicked
    $adminPhone = '919876543210'; // Replace with actual admin WhatsApp number
    
    $message = urlencode(
        "📧 *New Contact Form Submission - KONGU TOURISTER*\n\n" .
        "👤 *Customer Details:*\n" .
        "📝 *Name:* " . $data['name'] . "\n" .
        "📧 *Email:* " . $data['email'] . "\n" .
        "📱 *Mobile:* " . $data['mobile'] . "\n" .
        "🏙️ *City:* " . $data['city'] . "\n\n" .
        "💬 *Message:*\n" . $data['message'] . "\n\n" .
        "📅 *Date:* " . date('Y-m-d H:i:s') . "\n" .
        "🌐 *IP:* " . $_SERVER['REMOTE_ADDR']
    );
    
    $whatsappUrl = "https://wa.me/{$adminPhone}?text={$message}";
    
    // In a real implementation, you would use WhatsApp Business API
    // For now, we'll return the URL that can be used to send the message
    return $whatsappUrl;
}

// Function to send auto-reply to customer
function sendContactReply($data) {
    $to = $data['email'];
    $subject = 'Thank you for contacting KONGU TOURISTER';
    
    $message = "
    <html>
    <head>
        <title>Thank you for contacting us</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: linear-gradient(135deg, #1e3a8a, #3b82f6); color: white; padding: 20px; text-align: center; }
            .content { padding: 20px; background: #f8fafc; }
            .footer { background: #1f2937; color: white; padding: 15px; text-align: center; font-size: 12px; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2><i class='bi bi-compass-fill'></i> KONGU TOURISTER</h2>
                <h3>Thank You for Contacting Us!</h3>
            </div>
            <div class='content'>
                <p>Dear " . htmlspecialchars($data['name']) . ",</p>
                <p>Thank you for reaching out to KONGU TOURISTER. We have received your message and our team will get back to you within 24 hours.</p>
                
                <h4>Your Message:</h4>
                <p><em>" . htmlspecialchars(substr($data['message'], 0, 300)) . "...</em></p>
                
                <h4>What We Offer:</h4>
                <ul>
                    <li>Premium luggage and travel accessories</li>
                    <li>Expert advice on travel gear</li>
                    <li>Competitive pricing and special offers</li>
                    <li>Lifetime warranty on selected products</li>
                    <li>Pan-India delivery and support</li>
                </ul>
                
                <h4>Need Immediate Assistance?</h4>
                <p>Call us at <strong>+1 234 567 8900</strong> for immediate support.</p>
                
                <p>Visit our showroom to explore our premium collection:</p>
                <p>
                    <strong>KONGU TOURISTER</strong><br>
                    123 Travel Street, City<br>
                    Open: Monday to Friday, 9AM - 6PM
                </p>
                
                <p>Best regards,<br>
                The KONGU TOURISTER Team</p>
            </div>
            <div class='footer'>
                <p>&copy; 2024 KONGU TOURISTER. All rights reserved.</p>
                <p>Premium Travel Luggage & Accessories</p>
                <p>📍 123 Travel Street, City | 📞 +1 234 567 8900 | 🌐 www.kongutourister.com</p>
            </div>
        </div>
    </body>
    </html>";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: noreply@kongutourister.com" . "\r\n";
    
    return mail($to, $subject, $message, $headers);
}

// Main execution
try {
    // Get POST data
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    // Validate required fields
    $requiredFields = ['name', 'email', 'mobile', 'city', 'message'];
    foreach ($requiredFields as $field) {
        if (empty($data[$field])) {
            throw new Exception("Missing required field: $field");
        }
    }
    
    // Validate email
    if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        throw new Exception("Invalid email address");
    }
    
    // Validate mobile (basic validation for Indian numbers)
    if (!preg_match('/^[6-9]\d{9}$/', $data['mobile'])) {
        throw new Exception("Invalid mobile number");
    }
    
    // Sanitize inputs
    $data['name'] = filter_var($data['name'], FILTER_SANITIZE_STRING);
    $data['city'] = filter_var($data['city'], FILTER_SANITIZE_STRING);
    $data['message'] = filter_var($data['message'], FILTER_SANITIZE_STRING);
    
    // Send email to admin
    $emailSent = sendContactEmail($data);
    
    // Send WhatsApp notification (returns URL for manual sending)
    $whatsappUrl = sendContactWhatsApp($data);
    
    // Send auto-reply to customer
    $customerReplySent = sendContactReply($data);
    
    // Log the contact submission for records
    $logEntry = date('Y-m-d H:i:s') . " - CONTACT - " . json_encode($data) . "\n";
    file_put_contents('contacts.log', $logEntry, FILE_APPEND | LOCK_EX);
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Contact form submitted successfully',
        'email_sent' => $emailSent,
        'customer_reply_sent' => $customerReplySent,
        'whatsapp_url' => $whatsappUrl
    ]);
    
} catch (Exception $e) {
    // Return error response
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
