<?php
/**
 * Plugin Name: Coco Beauty Bar AI Chatbot
 * Description: AI-powered chatbot for customer inquiries and booking assistance.
 */

// 1. Add the Chatbot UI to the footer
add_action('wp_footer', function() {
    ?>
    <div id="coco-chat-container" style="position: fixed; bottom: 110px; right: 40px; z-index: 1000; font-family: 'Montserrat', sans-serif;">
        <div id="coco-chat-button" style="background: #D4AF37; color: white; width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; box-shadow: 0 4px 15px rgba(0,0,0,0.2); transition: transform 0.3s ease;">
            <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" viewBox="0 0 16 16">
                <path d="M14.5 3a.5.5 0 0 1 .5.5v9a.5.5 0 0 1-.5.5h-13a.5.5 0 0 1-.5-.5v-9a.5.5 0 0 1 .5-.5h13zm-13-1A1.5 1.5 0 0 0 0 3.5v9A1.5 1.5 0 0 0 1.5 14h13a1.5 1.5 0 0 0 1.5-1.5v-9A1.5 1.5 0 0 0 14.5 2h-13z"/>
                <path d="M5 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 5 8zm0-2.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm0 5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5z"/>
            </svg>
        </div>
        <div id="coco-chat-window" style="display: none; position: absolute; bottom: 80px; right: 0; width: 350px; height: 450px; background: white; border-radius: 15px; flex-direction: column; box-shadow: 0 10px 30px rgba(0,0,0,0.2); overflow: hidden; border: 1px solid #eee;">
            <div style="background: #D4AF37; color: white; padding: 15px; font-weight: 600; display: flex; justify-content: space-between; align-items: center;">
                <span><?php echo coco_i18n()->t('ai_assistant'); ?></span>
                <span id="close-chat" style="cursor: pointer;">&times;</span>
            </div>
            <div id="chat-messages" style="flex: 1; padding: 15px; overflow-y: auto; display: flex; flex-direction: column; gap: 10px; background: #fafafa;">
                <div style="background: #eee; padding: 10px; border-radius: 10px; align-self: flex-start; max-width: 80%; font-size: 14px;">
                    <?php echo coco_i18n()->t('ai_greeting'); ?>
                </div>
            </div>
            <div style="padding: 10px; border-top: 1px solid #eee; display: flex; gap: 5px;">
                <input type="text" id="chat-input" placeholder="<?php echo coco_i18n()->t('chat_placeholder'); ?>" style="flex: 1; border: 1px solid #ddd; padding: 8px; border-radius: 5px; outline: none;">
                <button id="send-chat" style="background: #D4AF37; color: white; border: none; padding: 8px 15px; border-radius: 5px; cursor: pointer;"><?php echo coco_i18n()->t('send'); ?></button>
            </div>
        </div>
    </div>

    <script>
        document.getElementById('coco-chat-button').addEventListener('click', function() {
            const window = document.getElementById('coco-chat-window');
            window.style.display = window.style.display === 'none' ? 'flex' : 'none';
            this.style.transform = window.style.display === 'flex' ? 'rotate(90deg)' : 'rotate(0deg)';
        });

        document.getElementById('close-chat').addEventListener('click', function() {
            document.getElementById('coco-chat-window').style.display = 'none';
            document.getElementById('coco-chat-button').style.transform = 'rotate(0deg)';
        });

        async function sendMessage() {
            const input = document.getElementById('chat-input');
            const message = input.value.trim();
            if (!message) return;

            const messagesContainer = document.getElementById('chat-messages');
            
            // Add user message
            const userMsg = document.createElement('div');
            userMsg.style = "background: #FFD1DC; padding: 10px; border-radius: 10px; align-self: flex-end; max-width: 80%; font-size: 14px; white-space: pre-wrap;";
            userMsg.textContent = message;
            messagesContainer.appendChild(userMsg);
            input.value = '';
            messagesContainer.scrollTop = messagesContainer.scrollHeight;

            // Show loading
            const loadingMsg = document.createElement('div');
            loadingMsg.style = "background: #eee; padding: 10px; border-radius: 10px; align-self: flex-start; max-width: 80%; font-size: 14px;";
            loadingMsg.textContent = "...";
            messagesContainer.appendChild(loadingMsg);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;

            try {
                const lang = document.documentElement.lang || 'en';
                const response = await fetch('/wp-admin/admin-ajax.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `action=coco_chat&message=${encodeURIComponent(message)}&lang=${lang}`
                });
                const data = await response.json();
                
                messagesContainer.removeChild(loadingMsg);
                
                const aiMsg = document.createElement('div');
                aiMsg.style = "background: #eee; padding: 10px; border-radius: 10px; align-self: flex-start; max-width: 80%; font-size: 14px; white-space: pre-wrap;";
                aiMsg.textContent = data.reply;
                messagesContainer.appendChild(aiMsg);
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            } catch (error) {
                loadingMsg.textContent = "Error occurred.";
            }
        }

        document.getElementById('send-chat').addEventListener('click', sendMessage);
        document.getElementById('chat-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') sendMessage();
        });
    </script>
    <?php
});

// 2. Handle the AI logic via admin-ajax
add_action('wp_ajax_coco_chat', 'coco_chat_handler');
add_action('wp_ajax_nopriv_coco_chat', 'coco_chat_handler');

function coco_chat_handler() {
    $message = isset($_POST['message']) ? sanitize_text_field($_POST['message']) : '';
    $lang = isset($_POST['lang']) ? sanitize_text_field($_POST['lang']) : 'en';
    
    if (empty($message)) {
        wp_send_json(['reply' => 'How can I help you?']);
    }

    require_once dirname(__DIR__, 2) . '/ai/LocalAIApi.php';

    $languageNames = ['en' => 'English', 'fr' => 'French', 'ar' => 'Arabic'];
    $targetLang = $languageNames[$lang] ?? 'English';

    $systemPrompt = "You are Coco, the AI assistant for 'Coco Beauty Bar' in Casablanca.
    Services: Manicure, Pedicure, Hair Styling, Facials, Massage.
    Tone: Elegant, Professional.

    RESPONSE RULES:
    1. Be EXTREMELY CONCISE and BRIEF.
    2. Use short, direct sentences.
    3. Use bullet points for lists or recommendations.
    4. No redundancy or lengthy explanations.
    5. Respond ONLY in {$targetLang}.

    Call to Action: Suggest booking on 'Contact' page or calling +212 5XX-XXXXXX.";

    $resp = LocalAIApi::createResponse([
        'input' => [
            ['role' => 'system', 'content' => $systemPrompt],
            ['role' => 'user', 'content' => $message],
        ],
    ]);

    if (!empty($resp['success'])) {
        $reply = LocalAIApi::extractText($resp);
    } else {
        $reply = "I'm sorry, I'm a bit overwhelmed right now. Please call us at +212 5XX-XXXXXX for assistance!";
    }

    wp_send_json(['reply' => $reply]);
}
