๐Ÿ“‚ File Browser

//AgentAIv3
๐ŸŒ™ Dark Mode
๐ŸŽฏ Quick Launch:

๐Ÿ“ Directories

๐Ÿ“ tmp/ ๐Ÿ”“ Open
๐Ÿ“ vendor/ ๐Ÿ”“ Open

๐Ÿ“„ Files

๐Ÿ“„ README.md
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ“ README.txt
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ“ README_content.txt
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ chat_handler.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ check_auth.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ cleanup.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ“„ composer.json
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ database.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ debug_email.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ debug_email_parts.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ debug_emails.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ delete_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ fetch_emails.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ find_models.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ gemini_direct.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ get_chats.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ get_email.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ index.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ index_simple.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ index_test.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ logout.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ mark_read.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ new_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ oauth2callback.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ refresh_token.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ rename_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ session_config.php
โ–ถ Open ๐Ÿ“„ View Source
๐ŸŽจ style.css
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ switch_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ sync_emails.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_ajax.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_api.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_cmd.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_curl.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_db.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_db_ops.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_endpoint.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_ollama.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_ollama_direct.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_openrouter.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_shell.php
โ–ถ Open ๐Ÿ“„ View Source

๐Ÿ“„ Source: index.php

<?php
session_name('INBOXZERO');
session_set_cookie_params(0, '/', '', false, true);
session_start();

require_once 'vendor/autoload.php';

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$baseUrl = "http://createcraftweb.playit.plus/AgentAIv3";

$client = new Google\Client();
$client->setClientId('1082083393389-c5uekspcp2boc1gd0n0gr3v1a5vbb3jg.apps.googleusercontent.com');
$client->setClientSecret('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');
$client->setRedirectUri("$baseUrl/oauth2callback.php");
$client->addScope('https://www.googleapis.com/auth/gmail.readonly');
$client->setAccessType('offline');
$client->setPrompt('consent');

$isMobile = preg_match('/(android|iphone|ipad|mobile)/i', $_SERVER['HTTP_USER_AGENT']);
$lang = $_COOKIE['inboxzero_lang'] ?? 'en';

$isLoggedIn = isset($_SESSION['access_token']);
?>
<!DOCTYPE html>
<html lang="<?php echo $lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>InboxZero AI v3</title>
    <link rel="stylesheet" href="style.css">
</head>
<body data-theme="light">
<div class="container">
    <div class="header">
        <div class="header-top">
            <h1>๐Ÿ“ง InboxZero AI <span class="badge">v3.0</span></h1>
            <div class="controls">
                <button class="theme-toggle" id="themeBtn" onclick="toggleTheme()">๐ŸŒ™ Dark</button>
                <select class="lang-select" id="langSelect" onchange="changeLanguage()">
                    <option value="en" <?php echo $lang == 'en' ? 'selected' : ''; ?>>๐Ÿ‡ฌ๐Ÿ‡ง English</option>
                    <option value="ro" <?php echo $lang == 'ro' ? 'selected' : ''; ?>>๐Ÿ‡ท๐Ÿ‡ด Romรขnฤƒ</option>
                </select>
                <button class="settings-btn" onclick="openSettings()">โš™๏ธ Settings</button>
            </div>
        </div>
        <p id="headerDescription">Your intelligent email assistant - ask anything about your emails</p>
        <div class="status">๐Ÿ”ง <?php echo date('Y-m-d H:i:s'); ?></div>
    </div>
    <div class="content">
        <div class="sidebar">
            <div class="chat-history-section">
                <h3>๐Ÿ’ฌ Recent Chats</h3>
                <div id="chatHistoryList" class="chat-history-list"></div>
                <button onclick="newChat()" class="new-chat-btn" id="newChatBtn">+ New Chat</button>
            </div>
            <hr>
            <h3 id="inboxTitle">๐Ÿ“ฌ Your Inbox</h3>
            <?php if ($isLoggedIn): ?>
                <button onclick="logout()" class="logout-btn" id="logoutBtn">๐Ÿšช Logout</button>
                <div id="emailList" style="margin-top: 15px;">
                    <div class="loading" id="loadingEmails">๐Ÿ“ฅ Loading your emails...</div>
                </div>
            <?php else: ?>
                <p id="loginPrompt">๐Ÿ” Login to access your Gmail inbox</p>
                <a href="<?php echo $client->createAuthUrl(); ?>" class="login-btn" id="loginBtn">๐Ÿ”‘ Sign in with Google</a>
            <?php endif; ?>
        </div>
        <div class="chat-area">
            <div class="messages" id="messages">
                <div class="message ai-message" id="welcomeMessage">
                    ๐Ÿค– <strong>Hello! I'm InboxZero AI v3.</strong><br><br>
                    I can help you:<br>
                    โ€ข ๐Ÿ“Š Summarize unread emails<br>
                    โ€ข ๐Ÿ” Find specific messages<br>
                    โ€ข ๐Ÿ“… Extract important dates<br>
                    โ€ข โšก Answer questions about your emails<br><br>
                    <em>Try: "Show me emails from Steam" or "Do I have emails from ChatGPT?"</em>
                </div>
            </div>
            <?php if ($isLoggedIn): ?>
            <div class="input-area">
                <textarea id="userInput" placeholder="Ask about your emails..." rows="1" onkeypress="if(event.key==='Enter' && !event.shiftKey) { event.preventDefault(); sendMessage(); }" style="overflow-y: hidden; resize: none;"></textarea>
                <button onclick="sendMessage()" id="sendBtn">๐Ÿ“ค Send</button>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// ============================================
// CONFIGURARE INIศšIALฤ‚
// ============================================
let currentLang = '<?php echo $lang; ?>';
let currentEmails = [];
let currentConversationId = null;
let reminderTimeout = null;

// รŽncarcฤƒ setฤƒrile din localStorage
let maxEmailsSetting = parseInt(localStorage.getItem('inboxzero_max_emails')) || 50;
let aiModelSetting = localStorage.getItem('inboxzero_ai_model') || 'tinyllama';
let autoDeleteSetting = localStorage.getItem('inboxzero_auto_delete') || '3';
let fontSizeSetting = localStorage.getItem('inboxzero_font_size') || '16';

// Aplicฤƒ font size
document.body.style.fontSize = fontSizeSetting + 'px';

// ============================================
// TRADUCERI
// ============================================
const translations = {
    en: {
        headerDesc: "Your intelligent email assistant - ask anything about your emails",
        inboxTitle: "๐Ÿ“ฌ Your Inbox",
        logoutBtn: "๐Ÿšช Logout",
        loadingEmails: "๐Ÿ“ฅ Loading your emails...",
        loginPrompt: "๐Ÿ” Login to access your Gmail inbox",
        loginBtn: "๐Ÿ”‘ Sign in with Google",
        welcomeMsg: "๐Ÿค– <strong>Hello! I'm InboxZero AI v3.</strong><br><br>I can help you:<br>โ€ข ๐Ÿ“Š Summarize unread emails<br>โ€ข ๐Ÿ” Find specific messages<br>โ€ข ๐Ÿ“… Extract important dates<br>โ€ข โšก Answer questions about your emails<br><br><em>Try: \"Show me emails from Steam\" or \"Do I have emails from ChatGPT?\"</em>",
        inputPlaceholder: "Ask about your emails...",
        sendBtn: "๐Ÿ“ค Send",
        thinking: "๐Ÿค” Thinking...",
        error: "โŒ Error: ",
        noEmailsDetail: "๐Ÿ“ญ No emails found",
        failedToLoad: "โŒ Failed to load emails",
        newChatBtn: "+ New Chat"
    },
    ro: {
        headerDesc: "Asistentul tฤƒu inteligent pentru emailuri - รฎntreabฤƒ orice",
        inboxTitle: "๐Ÿ“ฌ Inbox-ul Tฤƒu",
        logoutBtn: "๐Ÿšช Deconectare",
        loadingEmails: "๐Ÿ“ฅ Se รฎncarcฤƒ emailurile...",
        loginPrompt: "๐Ÿ” Autentificฤƒ-te pentru a accesa Gmail",
        loginBtn: "๐Ÿ”‘ Conectare cu Google",
        welcomeMsg: "๐Ÿค– <strong>Salut! Sunt InboxZero AI v3.</strong><br><br>Te pot ajuta:<br>โ€ข ๐Ÿ“Š Rezumatul emailurilor necitite<br>โ€ข ๐Ÿ” Gฤƒsirea mesajelor specifice<br>โ€ข ๐Ÿ“… Extragerea datelor importante<br>โ€ข โšก Rฤƒspuns la รฎntrebฤƒri despre emailuri<br><br><em>รŽncearcฤƒ: \"Aratฤƒ-mi emailurile de la Steam\" sau \"Am emailuri de la ChatGPT?\"</em>",
        inputPlaceholder: "รŽntreabฤƒ despre emailurile tale...",
        sendBtn: "๐Ÿ“ค Trimite",
        thinking: "๐Ÿค” Analizez...",
        error: "โŒ Eroare: ",
        noEmailsDetail: "๐Ÿ“ญ Nu s-au gฤƒsit emailuri",
        failedToLoad: "โŒ Nu s-au putut รฎncฤƒrca emailurile",
        newChatBtn: "+ Chat Nou"
    }
};

// ============================================
// FUNCศšII UI (Limbฤƒ, Temฤƒ)
// ============================================
function updateLanguage() {
    const t = translations[currentLang];
    const headerDesc = document.getElementById('headerDescription');
    if (headerDesc) headerDesc.innerText = t.headerDesc;
    const inboxTitle = document.getElementById('inboxTitle');
    if (inboxTitle) inboxTitle.innerText = t.inboxTitle;
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) logoutBtn.innerText = t.logoutBtn;
    const loginPrompt = document.getElementById('loginPrompt');
    if (loginPrompt) loginPrompt.innerText = t.loginPrompt;
    const loginBtn = document.getElementById('loginBtn');
    if (loginBtn) loginBtn.innerText = t.loginBtn;
    const welcomeMessage = document.getElementById('welcomeMessage');
    if (welcomeMessage) welcomeMessage.innerHTML = t.welcomeMsg;
    const userInput = document.getElementById('userInput');
    if (userInput) userInput.placeholder = t.inputPlaceholder;
    const sendBtn = document.getElementById('sendBtn');
    if (sendBtn) sendBtn.innerText = t.sendBtn;
    const newChatBtn = document.getElementById('newChatBtn');
    if (newChatBtn) newChatBtn.innerText = t.newChatBtn;
    const loadingEmails = document.getElementById('loadingEmails');
    if (loadingEmails) loadingEmails.innerText = t.loadingEmails;
}

function changeLanguage() {
    const select = document.getElementById('langSelect');
    currentLang = select.value;
    document.documentElement.lang = currentLang;
    document.cookie = `inboxzero_lang=${currentLang}; path=/; max-age=${365 * 24 * 60 * 60}`;
    updateLanguage();
}

function toggleTheme() {
    const body = document.body;
    const currentTheme = body.getAttribute('data-theme');
    const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
    body.setAttribute('data-theme', newTheme);
    localStorage.setItem('inboxzero_theme', newTheme);
    const themeBtn = document.getElementById('themeBtn');
    if (themeBtn) themeBtn.innerHTML = newTheme === 'dark' ? 'โ˜€๏ธ Light' : '๐ŸŒ™ Dark';
}

const savedTheme = localStorage.getItem('inboxzero_theme') || 'light';
document.body.setAttribute('data-theme', savedTheme);
const themeBtn = document.getElementById('themeBtn');
if (themeBtn) themeBtn.innerHTML = savedTheme === 'dark' ? 'โ˜€๏ธ Light' : '๐ŸŒ™ Dark';

// ============================================
// REMINDER
// ============================================
function setReminder(text, minutes) {
    if (reminderTimeout) clearTimeout(reminderTimeout);
    addMessage('ai', `โฐ Reminder set for ${minutes} minute(s): "${text}"`);
    if (Notification.permission !== 'granted') Notification.requestPermission();
    reminderTimeout = setTimeout(() => {
        if (Notification.permission === 'granted') new Notification('InboxZero Reminder', { body: text });
        addMessage('ai', `๐Ÿ”” REMINDER: ${text}`);
    }, minutes * 60 * 1000);
}

// ============================================
// CHAT PRINCIPAL
// ============================================
async function sendMessage() {
    const input = document.getElementById('userInput');
    const message = input.value.trim();
    if (!message) return;
    
    addMessage('user', message);
    input.value = '';
    input.disabled = true;
    
    const t = translations[currentLang];
    const thinkingMsg = addMessage('ai', t.thinking, true);
    
    try {
        const response = await fetch('chat_handler.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
                query: message, 
                lang: currentLang, 
                conversation_id: currentConversationId,
                max_emails: maxEmailsSetting,
                ai_model: aiModelSetting
            })
        });
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const data = await response.json();
        if (thinkingMsg) thinkingMsg.remove();
        addMessage('ai', data.reply);
        if (data.reminder) setReminder(data.reminder.text, data.reminder.minutes);
        if (data.emails && data.emails.length > 0) {
            currentEmails = data.emails;
            displayEmails(currentEmails);
        }
        if (data.conversation_id && !currentConversationId) {
            currentConversationId = data.conversation_id;
        }
    } catch (error) {
        if (thinkingMsg) thinkingMsg.remove();
        console.error('Error:', error);
        addMessage('ai', t.error + error.message);
    }
    input.disabled = false;
    input.focus();
}

function addMessage(role, text, returnElement = false, isHtml = false) {
    const messagesDiv = document.getElementById('messages');
    const div = document.createElement('div');
    div.className = `message ${role === 'user' ? 'user-message' : 'ai-message'}`;
    if (isHtml) {
        div.innerHTML = (role === 'user' ? '๐Ÿ‘ค ' : '๐Ÿค– ') + text;
    } else {
        div.innerHTML = (role === 'user' ? '๐Ÿ‘ค ' : '๐Ÿค– ') + text.replace(/\n/g, '<br>');
    }
    messagesDiv.appendChild(div);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
    if (returnElement) return div;
    return div;
}

// ============================================
// EMAIL LIST
// ============================================
async function loadEmails() {
    const t = translations[currentLang];
    try {
        const response = await fetch('fetch_emails.php');
        const emails = await response.json();
        if (emails.error) {
            document.getElementById('emailList').innerHTML = `<div class="loading">โŒ ${emails.error}</div>`;
        } else if (emails.length === 0) {
            document.getElementById('emailList').innerHTML = `<div class="loading">${t.noEmailsDetail}</div>`;
        } else {
            currentEmails = emails;
            displayEmails(emails);
        }
    } catch (error) {
        document.getElementById('emailList').innerHTML = `<div class="loading">${t.failedToLoad}</div>`;
    }
}

function displayEmails(emails) {
    if (!emails || emails.length === 0) {
        document.getElementById('emailList').innerHTML = '<div class="loading">๐Ÿ“ญ No emails found</div>';
        return;
    }
    let html = '<ul class="email-list">';
    for (let i = 0; i < Math.min(emails.length, maxEmailsSetting); i++) {
        const email = emails[i];
        const fromShort = email.from.length > 35 ? email.from.substring(0, 32) + '...' : email.from;
        const subjectShort = email.subject.length > 45 ? email.subject.substring(0, 42) + '...' : email.subject;
        html += `<li class="email-item" onclick="viewEmail('${email.id}', '${email.threadId}')">
                    <div class="email-from">๐Ÿ“จ ${escapeHtml(fromShort)}</div>
                    <div class="email-subject">${escapeHtml(subjectShort)}</div>
                    <div class="email-date">๐Ÿ“… ${escapeHtml(email.date)}</div>
                </li>`;
    }
    html += '</ul>';
    document.getElementById('emailList').innerHTML = html;
}

async function viewEmail(emailId, threadId) {
    addMessage('ai', '๐Ÿ“– Opening email...');
    try {
        const response = await fetch('get_email.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email_id: emailId })
        });
        const data = await response.json();
        if (data.content) {
            addMessage('ai', data.content);
            if (threadId) {
                const gmailLink = `https://mail.google.com/mail/u/0/#inbox/${threadId}`;
                addMessage('ai', `<a href="${gmailLink}" target="_blank" class="gmail-link">๐Ÿ“ง Open in Gmail</a>`, false, true);
            }
        } else {
            addMessage('ai', 'โŒ Could not load email content.');
        }
    } catch (error) {
        addMessage('ai', 'โŒ Failed to load email.');
    }
}

// ============================================
// CHAT HISTORY
// ============================================
let lastChatLoad = 0;

async function loadChatHistory() {
    // Nu รฎncฤƒrca mai des de o datฤƒ la 2 secunde
    const now = Date.now();
    if (now - lastChatLoad < 2000) return;
    lastChatLoad = now;
    
    try {
        const response = await fetch('get_chats.php');
        const chats = await response.json();
        const container = document.getElementById('chatHistoryList');
        if (container && !chats.error) {
            if (chats.length === 0) {
                container.innerHTML = '<div class="chat-history-item" style="opacity:0.6;">No previous chats</div>';
            } else {
                container.innerHTML = chats.map(chat => `
                    <div class="chat-history-item-wrapper">
                        <div class="chat-history-item ${currentConversationId == chat.id ? 'active' : ''}" onclick="switchChat('${chat.id}')">
                            ${escapeHtml(chat.title)}
                        </div>
                        <div class="chat-history-actions">
                            <button onclick="event.stopPropagation(); renameChat('${chat.id}')">โœ๏ธ</button>
                            <button onclick="event.stopPropagation(); deleteChat('${chat.id}')">๐Ÿ—‘๏ธ</button>
                        </div>
                    </div>
                `).join('');
            }
        }
    } catch (e) {
        console.error('Load chat history error:', e);
    }
}

async function newChat() {
    try {
        const response = await fetch('new_chat.php', { method: 'POST' });
        const data = await response.json();
        if (data.success) {
            currentConversationId = data.chat_id;
            const messagesDiv = document.getElementById('messages');
            messagesDiv.innerHTML = '';
            const welcomeMsg = document.createElement('div');
            welcomeMsg.className = 'message ai-message';
            welcomeMsg.innerHTML = translations[currentLang].welcomeMsg;
            messagesDiv.appendChild(welcomeMsg);
            // Nu mai reรฎncฤƒrca emailurile - pฤƒstreazฤƒ lista existentฤƒ
            loadChatHistory(); // Doar asta, pentru a vedea chat-ul nou
        }
    } catch(e) {
        console.error('New chat error:', e);
    }
}

async function renameChat(chatId) {
    const newTitle = prompt('Enter new chat name:');
    if (newTitle && newTitle.trim()) {
        await fetch('rename_chat.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ chat_id: chatId, title: newTitle.trim() })
        });
        loadChatHistory();
    }
}

async function deleteChat(chatId) {
    if (confirm('Delete this chat?')) {
        await fetch('delete_chat.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ chat_id: chatId })
        });
        if (currentConversationId == chatId) {
            currentConversationId = null;
            const messagesDiv = document.getElementById('messages');
            messagesDiv.innerHTML = '';
            const welcomeMsg = document.createElement('div');
            welcomeMsg.className = 'message ai-message';
            welcomeMsg.innerHTML = translations[currentLang].welcomeMsg;
            messagesDiv.appendChild(welcomeMsg);
            const newChatResp = await fetch('new_chat.php', { method: 'POST' });
            const newChatData = await newChatResp.json();
            if (newChatData.success) currentConversationId = newChatData.chat_id;
        }
        loadChatHistory();
    }
}

async function switchChat(chatId) {
    if (currentConversationId == chatId) return; // Nu schimba la acelaศ™i chat
    
    currentConversationId = chatId;
    try {
        const response = await fetch('switch_chat.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ chat_id: chatId })
        });
        const data = await response.json();
        if (data.messages) {
            const messagesDiv = document.getElementById('messages');
            messagesDiv.innerHTML = '';
            for (const msg of data.messages) {
                addMessage(msg.role, msg.content);
            }
            if (data.messages.length === 0) {
                const welcomeMsg = document.createElement('div');
                welcomeMsg.className = 'message ai-message';
                welcomeMsg.innerHTML = translations[currentLang].welcomeMsg;
                messagesDiv.appendChild(welcomeMsg);
            }
        }
        // Actualizeazฤƒ doar clasa activฤƒ, fฤƒrฤƒ reรฎncฤƒrcare completฤƒ
        const chatItems = document.querySelectorAll('.chat-history-item');
        chatItems.forEach(item => {
            const onclickAttr = item.getAttribute('onclick');
            if (onclickAttr && onclickAttr.includes(`switchChat('${chatId}')`)) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        });
    } catch (e) {
        console.error('Switch chat error:', e);
        window.location.reload();
    }
}

function logout() {
    fetch('logout.php').then(() => window.location.reload());
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// ============================================
// SETฤ‚RI COMPLETE
// ============================================
function openSettings() {
    const currentMax = localStorage.getItem('inboxzero_max_emails') || '50';
    const currentModel = localStorage.getItem('inboxzero_ai_model') || 'tinyllama';
    const currentAutoDelete = localStorage.getItem('inboxzero_auto_delete') || '3';
    const currentFontSize = localStorage.getItem('inboxzero_font_size') || '16';
    
    const settingsHtml = `
        <div id="settingsModal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 1000;">
            <div style="background: var(--bg-secondary); border-radius: 15px; padding: 25px; max-width: 450px; width: 90%; box-shadow: 0 4px 20px rgba(0,0,0,0.3);">
                <h3 style="margin-top: 0;">โš™๏ธ Settings</h3>
                
                <div style="margin-bottom: 20px;">
                    <label>๐Ÿ“ง Max emails to show: <span id="maxEmailsValue">${currentMax}</span></label>
                    <input type="range" id="maxEmails" min="10" max="100" step="5" value="${currentMax}" style="width: 100%; margin: 10px 0;">
                </div>
                
                <div style="margin-bottom: 20px;">
                    <label>๐Ÿ”ค Font size: <span id="fontSizeValue">${currentFontSize}px</span></label>
                    <input type="range" id="fontSize" min="12" max="24" step="1" value="${currentFontSize}" style="width: 100%; margin: 10px 0;">
                </div>
                
                <div style="margin-bottom: 20px;">
                    <label>๐Ÿค– AI Model:</label>
                    <select id="aiModel" style="width: 100%; padding: 8px; margin-top: 5px; border-radius: 8px; border: 1px solid var(--border); background: var(--bg-primary); color: var(--text-primary);">
                        <option value="tinyllama" ${currentModel === 'tinyllama' ? 'selected' : ''}>TinyLlama (Fast - 1.1GB)</option>
                        <option value="llama3.2:3b" ${currentModel === 'llama3.2:3b' ? 'selected' : ''}>Llama 3.2 (Smarter - 2GB)</option>
                    </select>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <label>๐Ÿ—‘๏ธ Auto-delete old emails:</label>
                    <select id="autoDelete" style="width: 100%; padding: 8px; margin-top: 5px; border-radius: 8px; border: 1px solid var(--border); background: var(--bg-primary); color: var(--text-primary);">
                        <option value="0" ${currentAutoDelete === '0' ? 'selected' : ''}>Disabled</option>
                        <option value="3" ${currentAutoDelete === '3' ? 'selected' : ''}>After 3 months</option>
                        <option value="6" ${currentAutoDelete === '6' ? 'selected' : ''}>After 6 months</option>
                        <option value="9" ${currentAutoDelete === '9' ? 'selected' : ''}>After 9 months</option>
                        <option value="12" ${currentAutoDelete === '12' ? 'selected' : ''}>After 12 months</option>
                    </select>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <button onclick="syncEmailsNow()" style="width: 100%; padding: 10px; background: #28a745; color: white; border: none; border-radius: 8px; cursor: pointer;">๐Ÿ”„ Sync Emails Now</button>
                </div>
                
                <div style="display: flex; gap: 10px; justify-content: flex-end;">
                    <button onclick="closeSettings()" style="padding: 8px 16px; background: #666; color: white; border: none; border-radius: 8px; cursor: pointer;">Cancel</button>
                    <button onclick="saveSettings()" style="padding: 8px 16px; background: #667eea; color: white; border: none; border-radius: 8px; cursor: pointer;">Save</button>
                </div>
            </div>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', settingsHtml);
    
    const maxSlider = document.getElementById('maxEmails');
    const maxVal = document.getElementById('maxEmailsValue');
    maxSlider.addEventListener('input', function() { maxVal.innerText = this.value; });
    
    const fontSlider = document.getElementById('fontSize');
    const fontVal = document.getElementById('fontSizeValue');
    fontSlider.addEventListener('input', function() { 
        fontVal.innerText = this.value + 'px';
        document.body.style.fontSize = this.value + 'px';
    });
}

function closeSettings() {
    const modal = document.getElementById('settingsModal');
    if (modal) modal.remove();
}

function saveSettings() {
    const maxEmails = document.getElementById('maxEmails').value;
    const fontSize = document.getElementById('fontSize').value;
    const aiModel = document.getElementById('aiModel').value;
    const autoDelete = document.getElementById('autoDelete').value;
    
    localStorage.setItem('inboxzero_max_emails', maxEmails);
    localStorage.setItem('inboxzero_font_size', fontSize);
    localStorage.setItem('inboxzero_ai_model', aiModel);
    localStorage.setItem('inboxzero_auto_delete', autoDelete);
    
    document.body.style.fontSize = fontSize + 'px';
    maxEmailsSetting = parseInt(maxEmails);
    aiModelSetting = aiModel;
    
    closeSettings();
    addMessage('ai', 'โœ… Settings saved! Refresh page to see more emails.');
}

async function syncEmailsNow() {
    closeSettings();
    addMessage('ai', '๐Ÿ”„ Syncing emails... This may take a moment.');
    try {
        const response = await fetch('sync_emails.php');
        const text = await response.text();
        addMessage('ai', 'โœ… Sync completed!');
        setTimeout(() => loadEmails(), 2000);
    } catch (error) {
        addMessage('ai', 'โŒ Sync failed: ' + error.message);
    }
}

// Auto-resize textarea
const textarea = document.getElementById('userInput');
if (textarea) {
    textarea.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 100) + 'px';
    });
}

if ('Notification' in window && Notification.permission !== 'denied' && Notification.permission !== 'granted') {
    Notification.requestPermission();
}

updateLanguage();

<?php if ($isLoggedIn): ?>
window.onload = async function() {
    await loadEmails();
    await loadChatHistory();
    if (!currentConversationId) {
        const response = await fetch('new_chat.php', { method: 'POST' });
        const data = await response.json();
        if (data.success) currentConversationId = data.chat_id;
    }
};
<?php endif; ?>
</script>
</body>
</html>
โ† Back