<?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 sendEmail($data) {
    $to = 'admin@kongutourister.com'; // Replace with actual admin email
    $subject = 'New Product Enquiry - KONGU TOURISTER';
    
    $message = "
    <html>
    <head>
        <title>New Product Enquiry</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 Product Enquiry</h3>
            </div>
            <div class='content'>
                <div class='field'>
                    <span class='label'>Product Name:</span> " . htmlspecialchars($data['productName']) . "
                </div>
                <div class='field'>
                    <span class='label'>Product ID:</span> #" . htmlspecialchars($data['productId']) . "
                </div>
                <div class='field'>
                    <span class='label'>Customer 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'>Enquiry Date:</span> " . date('Y-m-d H:i:s') . "
                </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 sendWhatsApp($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 Product Enquiry - KONGU TOURISTER*\n\n" .
        "📦 *Product:* " . $data['productName'] . "\n" .
        "🆔 *Product ID:* #" . $data['productId'] . "\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')
    );
    
    $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 sendCustomerReply($data) {
    $to = $data['email'];
    $subject = 'Thank you for your enquiry - KONGU TOURISTER';
    
    $message = "
    <html>
    <head>
        <title>Thank you for your enquiry</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 Your Enquiry!</h3>
            </div>
            <div class='content'>
                <p>Dear " . htmlspecialchars($data['name']) . ",</p>
                <p>Thank you for your interest in our <strong>" . htmlspecialchars($data['productName']) . "</strong>.</p>
                <p>We have received your enquiry and our team will contact you within 24 hours to discuss your requirements and provide you with detailed information.</p>
                
                <h4>What happens next?</h4>
                <ul>
                    <li>Our product specialist will review your enquiry</li>
                    <li>You'll receive a call within 24 hours</li>
                    <li>We'll provide personalized recommendations</li>
                    <li>Special offers may be available for you</li>
                </ul>
                
                <h4>Your Enquiry Details:</h4>
                <p><strong>Product:</strong> " . htmlspecialchars($data['productName']) . "</p>
                <p><strong>Message:</strong> " . htmlspecialchars(substr($data['message'], 0, 200)) . "...</p>
                
                <p>If you have any urgent questions, feel free to call us at +1 234 567 8900.</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 = ['productId', 'productName', '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");
    }
    
    // Send email to admin
    $emailSent = sendEmail($data);
    
    // Send WhatsApp notification (returns URL for manual sending)
    $whatsappUrl = sendWhatsApp($data);
    
    // Send auto-reply to customer
    $customerReplySent = sendCustomerReply($data);
    
    // Log the enquiry for records
    $logEntry = date('Y-m-d H:i:s') . " - " . json_encode($data) . "\n";
    file_put_contents('enquiries.log', $logEntry, FILE_APPEND | LOCK_EX);
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Enquiry sent 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()
    ]);
}
?>
