<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
require_once 'db/config.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Copilot - FinMox</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
        * {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
        }
        body {
            background-color: #fafafa;
            -webkit-font-smoothing: antialiased;
        }
        /* Make main content fill the screen */
        .main-content {
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .chat-layout {
            display: grid;
            grid-template-columns: 1fr 320px; /* Main chat area and right sidebar */
            gap: 0;
            height: 100%;
            width: 100%;
        }
        .chat-container {
            display: flex;
            flex-direction: column;
            height: 100%; /* Full height of its grid cell */
            background-color: #fafafa;
        }
        .chat-messages {
            flex-grow: 1;
            overflow-y: auto;
            padding: 1.5rem;
        }
        .message-bubble {
            max-width: 75%;
        }
        .user-message {
            background-color: #3B82F6;
            color: white;
        }
        .ai-message {
            background-color: #ffffff;
            color: #1F2937;
            border: 1px solid #e5e7eb;
        }

    </style>
</head>
<body class="bg-gray-100">
    <div class="flex h-screen bg-gray-200">
        <?php include '_sidebar.php'; ?>

        <!-- Main content -->
        <main class="flex-1 flex flex-col overflow-hidden">
            <div class="chat-layout">
                <!-- Main Chat Area -->
                <div class="chat-container" style="position: relative;">
                    <a href="chat.php" id="refresh-chat" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition-colors" title="Clear chat and refresh">
                        <i data-lucide="refresh-cw" class="w-5 h-5"></i>
                    </a>
                    <div class="chat-messages" id="chat-messages">
                        <!-- Initial Welcome Screen -->
                        <div id="welcome-screen" class="h-full flex flex-col justify-center items-center p-6">
                            <div class="w-full max-w-3xl text-center">
                                <div class="mb-8">
                                     <h1 class="text-3xl font-bold text-gray-800">Hi, I'm FinMox AI.</h1>
                                     <p class="text-lg text-gray-500 mt-2">Here are a few suggestions to get you started:</p>
                                </div>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <a href="#" class="suggestion-card bg-white p-4 rounded-lg border border-gray-200 hover:bg-gray-50 flex items-center gap-4 transition-colors" data-suggestion="Summarize active candidates">
                                        <div class="bg-purple-100 p-2 rounded-lg">
                                            <i data-lucide="users" class="w-6 h-6 text-purple-600"></i>
                                        </div>
                                        <span class="font-medium text-gray-700">Summarize active candidates</span>
                                    </a>
                                    <a href="#" class="suggestion-card bg-white p-4 rounded-lg border border-gray-200 hover:bg-gray-50 flex items-center gap-4 transition-colors" data-suggestion="List top compliance risks">
                                        <div class="bg-red-100 p-2 rounded-lg">
                                            <i data-lucide="shield-alert" class="w-6 h-6 text-red-600"></i>
                                        </div>
                                        <span class="font-medium text-gray-700">List top compliance risks</span>
                                    </a>
                                    <a href="#" class="suggestion-card bg-white p-4 rounded-lg border border-gray-200 hover:bg-gray-50 flex items-center gap-4 transition-colors" data-suggestion="Draft a new job description for a Senior Product Manager">
                                        <div class="bg-blue-100 p-2 rounded-lg">
                                            <i data-lucide="file-text" class="w-6 h-6 text-blue-600"></i>
                                        </div>
                                        <span class="font-medium text-gray-700">Draft a new job description</span>
                                    </a>
                                    <a href="#" class="suggestion-card bg-white p-4 rounded-lg border border-gray-200 hover:bg-gray-50 flex items-center gap-4 transition-colors" data-suggestion="Explain the latest HR policy update regarding remote work">
                                        <div class="bg-green-100 p-2 rounded-lg">
                                            <i data-lucide="info" class="w-6 h-6 text-green-600"></i>
                                        </div>
                                        <span class="font-medium text-gray-700">Explain the latest HR policy update</span>
                                    </a>
                                </div>
                            </div>
                        </div>
                        <!-- Chat messages will be appended here -->
                    </div>

                    <div class="p-4 border-t border-gray-200 bg-white">
                        <div class="typing-indicator text-sm text-gray-500 mb-2 hidden" id="typing-indicator">
                            AI is thinking...
                        </div>
                        <div id="chat-input-wrapper" class="flex items-center w-full bg-gray-50 border border-gray-200 rounded-lg p-2">
                            <div class="flex items-center gap-1">
                                <button id="plus-circle-btn" class="text-gray-500 hover:text-gray-700 p-2 rounded-full hover:bg-gray-200">
                                    <i data-lucide="plus-circle" class="w-5 h-5"></i>
                                </button>
                                <button id="mic-btn" class="text-gray-500 hover:text-gray-700 p-2 rounded-full hover:bg-gray-200">
                                    <i data-lucide="mic" class="w-5 h-5"></i>
                                </button>
                                <button id="image-btn" class="text-gray-500 hover:text-gray-700 p-2 rounded-full hover:bg-gray-200">
                                    <i data-lucide="image" class="w-5 h-5"></i>
                                </button>
                                <button id="settings-btn" class="text-gray-500 hover:text-gray-700 p-2 rounded-full hover:bg-gray-200">
                                    <i data-lucide="settings-2" class="w-5 h-5"></i>
                                </button>
                            </div>
                            <input type="text" id="chat-input" class="flex-grow bg-transparent border-none mx-2 p-2 text-sm focus:ring-0" placeholder="Ask me anything...">
                            <button id="send-btn" class="bg-blue-600 text-white rounded-lg p-2 hover:bg-blue-700">
                                <i data-lucide="send" class="w-5 h-5"></i>
                            </button>
                        </div>
                        <input type="file" id="file-input" class="hidden">
                        <input type="file" id="image-input" class="hidden" accept="image/*">
                    </div>
                </div>
                <!-- Right Tools Sidebar -->
                <aside class="bg-white border-l border-gray-200 p-6 flex-col gap-8 hidden lg:flex">
                    <div>
                        <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-4">Available Tools</h3>
                        <div class="space-y-3">
                            <button class="suggestion-btn flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors w-full text-left" data-suggestion="Get Weekly Metrics">
                                <i data-lucide="bar-chart-3" class="w-5 h-5 text-blue-600 flex-shrink-0 mt-1"></i>
                                <div>
                                    <p class="font-semibold text-gray-800">Get Weekly Metrics</p>
                                    <p class="text-sm text-gray-500">Retrieve key HR metrics for the current week</p>
                                </div>
                            </button>
                            <button class="suggestion-btn flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors w-full text-left" data-suggestion="Get Candidate Summaries">
                                <i data-lucide="users" class="w-5 h-5 text-purple-600 flex-shrink-0 mt-1"></i>
                                <div>
                                    <p class="font-semibold text-gray-800">Get Candidate Summaries</p>
                                    <p class="text-sm text-gray-500">AI-generated summaries of active candidates</p>
                                </div>
                            </button>
                            <button class="suggestion-btn flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors w-full text-left" data-suggestion="Search RAG">
                                <i data-lucide="search" class="w-5 h-5 text-emerald-600 flex-shrink-0 mt-1"></i>
                                <div>
                                    <p class="font-semibold text-gray-800">Search RAG</p>
                                    <p class="text-sm text-gray-500">Search company knowledge base and policies</p>
                                </div>
                            </button>
                             <button class="suggestion-btn flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors w-full text-left" data-suggestion="List Onboarding Risks">
                                <i data-lucide="alert-triangle" class="w-5 h-5 text-amber-600 flex-shrink-0 mt-1"></i>
                                <div>
                                    <p class="font-semibold text-gray-800">List Onboarding Risks</p>
                                    <p class="text-sm text-gray-500">Identify potential onboarding issues and delays</p>
                                </div>
                            </button>
                        </div>
                    </div>
                     <div>
                        <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-4">Quick Actions</h3>
                        <div class="space-y-2">
                           <button class="suggestion-btn w-full text-left p-2 rounded-md hover:bg-gray-100 text-gray-700 font-medium" data-suggestion="Generate the weekly HR report">Weekly Report</button>
                           <button class="suggestion-btn w-full text-left p-2 rounded-md hover:bg-gray-100 text-gray-700 font-medium" data-suggestion="List the top 5 candidates based on score">Top Candidates</button>
                           <button class="suggestion-btn w-full text-left p-2 rounded-md hover:bg-gray-100 text-gray-700 font-medium" data-suggestion="Check for any new onboarding risks">Check Risks</button>
                        </div>
                    </div>
                </aside>
            </div>
        </main>
    </div>

    <!-- Settings Modal -->
    <div id="settings-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-bold text-gray-800">Settings</h3>
                <button id="close-settings-modal" class="text-gray-500 hover:text-gray-800">
                    <i data-lucide="x" class="w-5 h-5"></i>
                </button>
            </div>
            <div>
                <p class="text-gray-600 mb-4">The following features are planned and will be available soon:</p>
                <ul class="list-disc list-inside space-y-2 text-gray-700">
                    <li>User Profile Management</li>
                    <li>Notification Preferences</li>
                    <li>API Key Configuration (OpenAI, Google, etc.)</li>
                    <li>Theme Customization (Light/Dark Mode)</li>
                    <li>Data Export Options</li>
                </ul>
            </div>
        </div>
    </div>
    <!-- Notification Container -->
    <div id="notification-container" class="fixed bottom-5 right-5 flex flex-col items-end gap-2 z-50"></div>

    <script>
        lucide.createIcons();

        const chatMessages = document.getElementById('chat-messages');
        const userInput = document.getElementById('chat-input');
        const sendBtn = document.getElementById('send-btn');
        const typingIndicator = document.getElementById('typing-indicator');
        const welcomeScreen = document.getElementById('welcome-screen');
        const refreshChat = document.getElementById('refresh-chat');
        const plusBtn = document.getElementById('plus-circle-btn');
        const micBtn = document.getElementById('mic-btn');
        const imageBtn = document.getElementById('image-btn');
        const settingsBtn = document.getElementById('settings-btn');
        const fileInput = document.getElementById('file-input');
        const imageInput = document.getElementById('image-input');
        const settingsModal = document.getElementById('settings-modal');
        const closeSettingsModal = document.getElementById('close-settings-modal');
        let welcomeMessageCleared = false;

        // Functions
        const showNotification = (message) => {
            const container = document.getElementById('notification-container');
            const notification = document.createElement('div');
            notification.className = 'bg-gray-800 text-white text-sm font-medium px-4 py-2 rounded-lg shadow-lg transform transition-all duration-300 ease-in-out';
            notification.textContent = message;

            notification.style.transform = 'translateX(100%)';
            notification.style.opacity = '0';
            
            container.appendChild(notification);

            setTimeout(() => {
                notification.style.transform = 'translateX(0)';
                notification.style.opacity = '1';
            }, 10);

            setTimeout(() => {
                notification.style.transform = 'translateX(100%)';
                notification.style.opacity = '0';
                setTimeout(() => {
                    if (container.contains(notification)) {
                        container.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        };
        
        const addMessage = (sender, content, isHtml = false) => {
            if (welcomeScreen && !welcomeMessageCleared) {
                welcomeScreen.style.display = 'none';
                chatMessages.innerHTML = '';
                welcomeMessageCleared = true;
            }

            const messageWrapper = document.createElement('div');
            messageWrapper.classList.add('flex', 'mb-4');
            
            const bubble = document.createElement('div');
            bubble.classList.add('p-3', 'rounded-lg', 'message-bubble');
            
            const contentContainer = document.createElement('div');
            if (isHtml) {
                contentContainer.innerHTML = content;
            } else {
                contentContainer.textContent = content;
            }
            bubble.appendChild(contentContainer);

            if (sender === 'user') {
                messageWrapper.classList.add('justify-end');
                bubble.classList.add('user-message');
            } else {
                messageWrapper.classList.add('justify-start');
                bubble.classList.add('ai-message');
            }
            
            messageWrapper.appendChild(bubble);
            chatMessages.appendChild(messageWrapper);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        };

        const sendMessage = async (messageOverride) => {
            const message = messageOverride || userInput.value.trim();
            if (!message) return;

            addMessage('user', message);
            userInput.value = '';
            sendBtn.disabled = true;
            typingIndicator.classList.remove('hidden');

            try {
                const response = await fetch('api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message })
                });

                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }

                const data = await response.json();
                const aiReply = data.reply || data.error || 'No reply from AI.';
                addMessage('ai', aiReply);

            } catch (error) {
                console.error('Error:', error);
                addMessage('ai', 'Sorry, something went wrong. Please check the console.');
            } finally {
                sendBtn.disabled = false;
                typingIndicator.classList.add('hidden');
            }
        }
        
        // Event Listeners
        sendBtn.addEventListener('click', () => sendMessage());
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                sendMessage();
            }
        });

        refreshChat.addEventListener('click', (e) => {
            e.preventDefault();
            window.location.reload();
        });

        document.querySelectorAll('.suggestion-card').forEach(card => {
            card.addEventListener('click', (e) => {
                e.preventDefault();
                const suggestion = e.currentTarget.dataset.suggestion;
                sendMessage(suggestion);
            });
        });

        document.querySelectorAll('.suggestion-btn').forEach(button => {
            button.addEventListener('click', (e) => {
                const suggestion = e.currentTarget.dataset.suggestion;
                sendMessage(suggestion);
            });
        });

        plusBtn.addEventListener('click', () => fileInput.click());
        micBtn.addEventListener('click', () => showNotification('Voice input is not yet implemented.'));
        imageBtn.addEventListener('click', () => imageInput.click());
        settingsBtn.addEventListener('click', () => settingsModal.classList.remove('hidden'));
        closeSettingsModal.addEventListener('click', () => settingsModal.classList.add('hidden'));


        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                addMessage('user', `Attached file: ${file.name}`);
                // Handle file upload here
            }
        });

        imageInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    const img = document.createElement('img');
                    img.src = event.target.result;
                    img.className = 'mt-2 rounded-lg max-w-xs';
                    
                    const messageContent = `Attached image: ${file.name}<br>`;
                    addMessage('user', messageContent + img.outerHTML, true);
                };
                reader.readAsDataURL(file);
            } else if (file) {
                addMessage('user', `Attached file: ${file.name}`);
                showNotification('This does not seem to be an image file.');
            }
        });

    </script>
</body>
</html>
