<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Support Panel</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary: #2481cc; --bg: #f5f7fb; --white: #ffffff; --border: #e1e4e8; --green: #2ecc71; --gray: #95a5a6; }
        body { margin: 0; padding: 0; font-family: Tahoma, sans-serif; background: var(--bg); color: #333; height: 100vh; overflow: hidden; display: flex; flex-direction: column; }
        
        /* Login Modal */
        #login-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 999; display: flex; align-items: center; justify-content: center; }
        .login-box { background: white; padding: 30px; border-radius: 10px; width: 300px; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
        .login-box input { width: 90%; padding: 10px; margin: 10px 0; border: 1px solid #ddd; border-radius: 5px; font-size: 16px; }
        .btn { background: var(--primary); color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-size: 16px; transition: 0.2s; }
        .btn:hover { opacity: 0.9; }

        /* Dashboard Layout */
        .main-container { display: flex; flex: 1; height: 100%; }
        
        /* Sidebar (Ticket List) */
        .sidebar { width: 350px; background: var(--white); border-left: 1px solid var(--border); display: flex; flex-direction: column; }
        .sidebar-header { padding: 15px; border-bottom: 1px solid var(--border); background: #fcfcfc; display: flex; justify-content: space-between; align-items: center; }
        .ticket-list { flex: 1; overflow-y: auto; }
        
        .ticket-item { padding: 15px; border-bottom: 1px solid var(--border); cursor: pointer; transition: 0.2s; position: relative; }
        .ticket-item:hover, .ticket-item.active { background: #eef2f5; border-right: 4px solid var(--primary); }
        .t-top { display: flex; justify-content: space-between; font-size: 14px; margin-bottom: 5px; }
        .t-id { font-weight: bold; color: var(--primary); }
        .t-status { font-size: 11px; padding: 2px 8px; border-radius: 10px; }
        .st-open { background: #fff3cd; color: #856404; }
        .st-answered { background: #d4edda; color: #155724; }
        .st-closed { background: #eee; color: #777; }
        .t-subject { font-size: 13px; color: #555; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .t-dept { font-size: 11px; color: var(--gray); margin-top: 5px; }

        /* Chat Area */
        .chat-area { flex: 1; display: flex; flex-direction: column; background: #eef1f5; }
        .chat-header { padding: 15px; background: var(--white); border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
        .chat-messages { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 10px; }
        
        .msg { max-width: 70%; padding: 12px 15px; border-radius: 10px; font-size: 14px; line-height: 1.5; position: relative; }
        .msg.user { align-self: flex-start; background: var(--white); border-top-left-radius: 0; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
        .msg.admin { align-self: flex-end; background: var(--primary); color: white; border-top-right-radius: 0; box-shadow: 0 1px 2px rgba(0,0,0,0.1); }
        .msg-time { font-size: 10px; opacity: 0.7; display: block; text-align: left; margin-top: 5px; }

        .chat-input { padding: 15px; background: var(--white); border-top: 1px solid var(--border); display: flex; gap: 10px; }
        .chat-input textarea { flex: 1; padding: 12px; border: 1px solid var(--border); border-radius: 8px; resize: none; height: 20px; outline: none; font-family: inherit; }
        
        .empty-state { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; color: var(--gray); }
        .badge { background: #e74c3c; color: white; font-size: 10px; padding: 2px 6px; border-radius: 50%; position: absolute; top: 15px; left: 10px; }

        /* Responsive */
        @media (max-width: 768px) {
            .main-container { flex-direction: column; }
            .sidebar { width: 100%; height: 40%; }
            .chat-area { height: 60%; }
        }
    </style>
</head>
<body>

    <div id="login-overlay">
        <div class="login-box">
            <h2>🔐 پنل مدیریت</h2>
            <p>لطفا رمز عبور ادمین را وارد کنید:</p>
            <input type="password" id="admin-pass" placeholder="رمز عبور...">
            <button class="btn" onclick="login()">ورود</button>
        </div>
    </div>

    <div class="main-container" id="dashboard" style="display:none;">
        
        <div class="sidebar">
            <div class="sidebar-header">
                <span><i class="fas fa-inbox"></i> تیکت‌ها</span>
                <button class="btn" style="padding: 5px 10px; font-size: 12px;" onclick="loadTickets()"><i class="fas fa-sync"></i></button>
            </div>
            <div class="ticket-list" id="ticket-list-container">
                </div>
        </div>

        <div class="chat-area">
            <div class="chat-header" id="chat-header" style="display:none;">
                <div id="header-title">تیکت #...</div>
                <div>
                    <button class="btn" style="background:#e74c3c" onclick="closeTicket()">بستن تیکت</button>
                </div>
            </div>
            
            <div class="chat-messages" id="chat-messages">
                <div class="empty-state">
                    <i class="fas fa-comments" style="font-size: 50px; margin-bottom: 20px;"></i>
                    <p>یک تیکت را جهت مشاهده انتخاب کنید</p>
                </div>
            </div>

            <div class="chat-input" id="chat-input-area" style="display:none;">
                <textarea id="reply-msg" placeholder="پاسخ شما..."></textarea>
                <button class="btn" onclick="sendReply()"><i class="fas fa-paper-plane"></i></button>
            </div>
        </div>
    </div>

<script>
    const API_URL = 'ticket_api.php';
    let PASSWORD = localStorage.getItem('admin_pass') || '';
    let activeTicketId = null;

    // --- Authentication ---
    async function login() {
        const pass = document.getElementById('admin-pass').value;
        const res = await apiRequest('admin_login', { password: pass });
        if (res.status === 'ok') {
            PASSWORD = pass;
            localStorage.setItem('admin_pass', pass);
            document.getElementById('login-overlay').style.display = 'none';
            document.getElementById('dashboard').style.display = 'flex';
            loadTickets();
            // رفرش خودکار هر 10 ثانیه
            setInterval(loadTickets, 10000);
        } else {
            alert('رمز عبور اشتباه است!');
        }
    }

    if(PASSWORD) {
        document.getElementById('admin-pass').value = PASSWORD;
        login();
    }

    // --- API Helper ---
    async function apiRequest(action, data = {}) {
        data.action = action;
        data.password = PASSWORD; // همیشه پسورد را بفرست
        try {
            const req = await fetch(API_URL, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });
            return await req.json();
        } catch(e) {
            console.error(e);
            return {status: 'error'};
        }
    }

    // --- Functions ---
    async function loadTickets() {
        const res = await apiRequest('admin_get_all_tickets');
        if(res.status !== 'ok') return;

        const container = document.getElementById('ticket-list-container');
        // ذخیره پوزیشن اسکرول
        const scrollPos = container.scrollTop;
        
        container.innerHTML = '';
        res.tickets.forEach(t => {
            const activeClass = (t.id == activeTicketId) ? 'active' : '';
            const statusClass = `st-${t.status}`;
            const statusText = t.status === 'open' ? 'باز' : (t.status === 'answered' ? 'پاسخ داده' : 'بسته');
            const deptText = t.department === 'Technical' ? 'فنی' : (t.department === 'Sales' ? 'مالی' : 'مدیریت');
            
            // نمایش دایره قرمز برای پیام جدید
            const badge = (t.status === 'open') ? `<span class="badge">New</span>` : '';

            const html = `
                <div class="ticket-item ${activeClass}" onclick="openTicket(${t.id}, '${t.status}')">
                    ${badge}
                    <div class="t-top">
                        <span class="t-id">#${t.id} - ${t.user_id}</span>
                        <span class="t-status ${statusClass}">${statusText}</span>
                    </div>
                    <div class="t-subject">${t.subject}</div>
                    <div class="t-dept"><i class="fas fa-tag"></i> ${deptText} | ${t.created_at}</div>
                </div>
            `;
            container.innerHTML += html;
        });

        container.scrollTop = scrollPos;
    }

    async function openTicket(tid, status) {
        activeTicketId = tid;
        document.getElementById('chat-header').style.display = 'flex';
        document.getElementById('chat-input-area').style.display = 'flex';
        document.getElementById('header-title').innerText = `تیکت #${tid}`;
        
        loadTickets(); // برای آپدیت استایل اکتیو
        loadMessages(tid);
    }

    async function loadMessages(tid) {
        const container = document.getElementById('chat-messages');
        const res = await apiRequest('get_messages', { ticket_id: tid });
        container.innerHTML = '';

        if(res.messages) {
            res.messages.forEach(m => {
                const type = m.sender_type; // admin or user
                const msgClass = type === 'admin' ? 'admin' : 'user';
                const senderName = type === 'admin' ? 'شما' : 'کاربر';
                
                const html = `
                    <div class="msg ${msgClass}">
                        <strong>${senderName}:</strong><br>
                        ${m.content}
                        <span class="msg-time">${m.created_at}</span>
                    </div>
                `;
                container.innerHTML += html;
            });
            container.scrollTop = container.scrollHeight;
        }
    }

    async function sendReply() {
        const txt = document.getElementById('reply-msg').value;
        if(!txt) return;

        // UI Optimistic Update
        const container = document.getElementById('chat-messages');
        container.innerHTML += `<div class="msg admin"><strong>شما:</strong><br>${txt}</div>`;
        container.scrollTop = container.scrollHeight;
        document.getElementById('reply-msg').value = '';

        await apiRequest('admin_reply', { ticket_id: activeTicketId, message: txt });
        loadTickets(); // رفرش لیست برای تغییر وضعیت
    }

    async function closeTicket() {
        if(confirm("آیا مطمئن هستید که می‌خواهید این تیکت را ببندید؟")) {
            await apiRequest('admin_close_ticket', { ticket_id: activeTicketId });
            loadTickets();
            openTicket(activeTicketId); // رفرش صفحه چت
        }
    }
</script>
</body>
</html>