<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Alva İzleyici</title>
    <!-- Bootstrap CSS CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        .conversation-item {
            display: flex;
            align-items: center;
            padding: 5px 0px 0px 5px;
            margin: 5px 0;
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease, box-shadow 0.3s ease;
        }
        .conversation-item:hover {
            background-color: #e9ecef;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .conversation-item img {
            width: 24px;
            height: 24px;
            margin-right: 10px;
        }
		.conversation-item span {
			display: inline-block;
			max-width: 200px;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
        .message {
            margin: 5px 0;
            padding: 10px;
            border-radius: 5px;
        }
        .user-message {
            background-color: #d1e7dd;
            text-align: right;
        }
        .assistant-message {
            background-color: #f8d7da;
            text-align: left;
        }
        /* Scrollbar stilleri */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #888;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background-color: #555;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        * {
            scrollbar-width: thin;
            scrollbar-color: #888 #f1f1f1;
        }
		@media (max-width: 768px) {
			#conversation-list {
				height: auto !important;
			}
		}
		@media (max-width: 767.98px) {
			#conversation-list {
				overflow-y: visible !important;
				height: auto !important;
			}
		}

    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sol Panel -->
            <div id="conversation-list" class="col-12 col-md-4 border-end p-3" style="height: 97vh; auto; background-color: #f8f9fa;">
                <h5 class="d-none d-md-block">Görüşme Listesi</h5>
				<div class="dropdown d-md-none mb-3">
					<button class="btn btn-secondary dropdown-toggle w-100" type="button" id="conversationDropdown" data-bs-toggle="dropdown" aria-expanded="false">
						Görüşme Seçin
					</button>
					<ul class="dropdown-menu w-100" id="file-list-dropdown" aria-labelledby="conversationDropdown">
						<!-- JS ile doldurulacak -->
					</ul>
				</div>

				<!-- Masaüstü görünüm (768px üstü) için klasik liste -->
				<ul id="file-list" class="list-unstyled d-none d-md-block">
					<!-- JS ile doldurulacak -->
				</ul>
            </div>

            <!-- Sağ Panel -->
            <div id="chat-view" class="col-12 col-md-8 p-3" style="height: 97vh; overflow-y: auto;">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">Görüşme Detayları</h5>
                    <button id="delete-conversation" class="btn btn-warning btn-sm" style="display: none;">Temizle</button>
                </div>
                <div id="chat-box"></div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS (Opsiyonel: Popper dahil) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
const loadConversations = () => {
    fetch('alva_list_conversations.php')
        .then(response => response.json())
        .then(files => {
            const fileList = document.getElementById('file-list');
            const dropdownList = document.getElementById('file-list-dropdown');
            fileList.innerHTML = '';
            dropdownList.innerHTML = '';

            files.forEach(fileObj => {
                // Masaüstü liste görünümü
                const li = document.createElement('li');
                li.className = 'conversation-item d-flex align-items-start';
                li.style.cursor = 'pointer';
                li.onclick = () => loadConversation(fileObj.file);

                li.innerHTML = `
                    <img src="https://cdn.crmplus.com.tr/images/chat-icon.png" alt="Sohbet İkonu" style="width: 24px; height: 24px; margin-right: 10px;" />
                    <div>
                        <strong>${fileObj.datetime}</strong><br>
                        <span style="font-size: 0.9em; color: #555; display: inline-block; max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                            ${fileObj.preview}
                        </span>
                    </div>
                `;
                fileList.appendChild(li);

                // Mobil dropdown listesi
                const dropdownItem = document.createElement('li');
                dropdownItem.innerHTML = `<a class="dropdown-item" href="#">${fileObj.datetime} - ${fileObj.preview}</a>`;
                dropdownItem.querySelector('a').onclick = () => loadConversation(fileObj.file);
                dropdownList.appendChild(dropdownItem);
            });
        });
};


        const loadConversation = (fileName) => {
            fetch('alva_get_conversation.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ fileName })
            })
                .then(response => response.json())
                .then(data => {
                    const chatBox = document.getElementById('chat-box');
                    const deleteButton = document.getElementById('delete-conversation');
                    chatBox.innerHTML = '';
                    if (data.error) {
                        chatBox.textContent = data.error;
                        deleteButton.style.display = 'none';
                        return;
                    }
                    data.forEach(message => {
                        const div = document.createElement('div');
                        div.className = `message ${message.role === 'user' ? 'user-message' : 'assistant-message'}`;
                        div.textContent = message.content;
                        chatBox.appendChild(div);
                    });
                    deleteButton.style.display = 'inline-block';
                    deleteButton.onclick = () => deleteConversation(fileName);
                });
        };

        const deleteConversation = (fileName) => {
            if (!fileName) {
                alert('Silinecek görüşme adı tanımlı değil.');
                return;
            }
            if (!confirm('Bu görüşmeyi silmek istediğinizden emin misiniz?')) return;

            fetch('alva_delete_conversation.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ fileName })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Görüşme başarıyla silindi.');
                        loadConversations();
                        document.getElementById('chat-box').innerHTML = '';
                        document.getElementById('delete-conversation').style.display = 'none';
                    } else {
                        alert('Görüşme silinirken bir hata oluştu: ' + data.error);
                    }
                });
        };

        document.addEventListener('DOMContentLoaded', loadConversations);
    </script>
</body>
</html>