<?php
// chats/index.php
// لوحة تحكم المحادثات - واجهة احترافية UI/UX حديثة (مع دعم PHP <7.4)
$directory = __DIR__;
$files = glob($directory . '/*.json');
$chats = [];
foreach ($files as $file) {
    $phone = basename($file, '.json');
    $raw = file_get_contents($file);
    $data = json_decode($raw, true);
    if (!is_array($data)) {
        continue;
    }
    // فلترة: تجاهل الرسائل النظامية
    $messages = array_filter($data, function($m) {
        return isset($m['role']) && in_array($m['role'], ['user', 'assistant']);
    });
    $chats[] = ['phone' => $phone, 'messages' => array_values($messages)];
}
?>
<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>لوحة تحكم المحادثات</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #007bff;
            --bg: #f0f2f5;
            --text: #333;
            --user-bg: #dcf8c6;
            --assistant-bg: #fff;
            --sidebar-bg: #fff;
            --border: #ddd;
            --header-bg: #fff;
        }
        * { box-sizing: border-box; }
        body { margin:0; font-family: 'Segoe UI', Tahoma, sans-serif; color: var(--text); background: var(--bg); }
        .container { display: flex; height: 100vh; }
        .sidebar { width: 280px; background: var(--sidebar-bg); border-right: 1px solid var(--border); display: flex; flex-direction: column; }
        .search { padding: 10px; border-bottom:1px solid var(--border); }
        .search input { width:100%; padding:8px; border:1px solid var(--border); border-radius:4px; }
        .chat-list { flex:1; overflow-y:auto; }
        .chat-item { padding:12px 16px; cursor:pointer; display:flex; align-items:center; border-bottom:1px solid var(--border); transition:background .2s; }
        .chat-item:hover, .chat-item.active { background: rgba(0,123,255,0.1); }
        .chat-item .icon { width:32px; text-align:center; margin-right:8px; color:var(--primary); }
        .chat-item .phone { flex:1; font-weight:500; }
        .content { flex:1; display:flex; flex-direction:column; }
        .header { padding: 12px 16px; background: var(--header-bg); border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content: space-between; }
        .header .title { font-size:1.1rem; font-weight:600; }
        .messages { flex:1; padding:16px; overflow-y:auto; background:var(--bg); }
        .message { max-width:70%; margin-bottom:12px; padding:10px 14px; border-radius:8px; position: relative; line-height:1.4; word-wrap: break-word; }
        .message.user { background: var(--user-bg); align-self:flex-end; border-bottom-right-radius:2px; }
        .message.assistant { background: var(--assistant-bg); align-self:flex-start; border-bottom-left-radius:2px; }
        .message .time { font-size:0.7rem; color:#888; position:absolute; bottom:-18px; right:10px; }
        .empty { flex:1; display:flex; align-items:center; justify-content:center; color:#666; font-size:1rem; }
    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <div class="search">
                <input id="search" placeholder="🔍 ابحث برقم...">
            </div>
            <div class="chat-list" id="chatList"></div>
        </div>
        <div class="content">
            <div class="header">
                <div class="title" id="chatTitle">اختر محادثة</div>
                <i id="refresh" class="fa-solid fa-rotate-right" style="cursor:pointer;color:var(--primary)"></i>
            </div>
            <div class="messages" id="messagesPane">
                <div class="empty">لم يتم تحديد محادثة.</div>
            </div>
        </div>
    </div>
    <script>
        var chats = <?php echo json_encode($chats, JSON_UNESCAPED_UNICODE); ?>;
        var selected = null;
        var chatListEl = document.getElementById('chatList');
        var messagesEl = document.getElementById('messagesPane');
        var titleEl = document.getElementById('chatTitle');
        var searchEl = document.getElementById('search');
        function renderList(filter) {
            filter = filter || '';
            chatListEl.innerHTML = '';
            for (var i = 0; i < chats.length; i++) {
                var c = chats[i];
                if (c.phone.indexOf(filter) === -1) continue;
                var item = document.createElement('div'); item.className = 'chat-item';
                if (i === selected) item.classList.add('active');
                (function(index){
                    item.onclick = function() { selected = index; renderConversation(); renderList(searchEl.value); };
                })(i);
                item.innerHTML = '<div class="icon"><i class="fa-solid fa-comments"></i></div><div class="phone">'+c.phone+'</div>';
                chatListEl.appendChild(item);
            }
        }
        function renderConversation() {
            messagesEl.innerHTML = '';
            if (selected === null) {
                titleEl.textContent = 'اختر محادثة';
                messagesEl.innerHTML = '<div class="empty">لم يتم تحديد محادثة.</div>';
                return;
            }
            var chat = chats[selected];
            titleEl.textContent = chat.phone;
            for (var j = 0; j < chat.messages.length; j++) {
                var msg = chat.messages[j];
                var m = document.createElement('div'); m.className = 'message ' + msg.role;
                m.textContent = msg.content;
                messagesEl.appendChild(m);
            }
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }
        searchEl.addEventListener('input', function(){ renderList(this.value.trim()); });
        document.getElementById('refresh').onclick = function(){ location.reload(); };
        renderList();
    </script>
</body>
</html>
