<?php
session_start();
include 'config.php';

if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'wali_kelas') {
    header("Location: index.php");
    exit;
}

$username = $_SESSION['username'];

// Ambil data wali kelas
$qWaliKelas = mysqli_query($conn, "SELECT kelas, nama_wali FROM wali_kelas WHERE nip_wali='$username'");
if (!$qWaliKelas || mysqli_num_rows($qWaliKelas) === 0) {
    die("Data wali kelas tidak ditemukan.");
}
$wali_kelas = mysqli_fetch_assoc($qWaliKelas);
$kelas_diampu = $wali_kelas['kelas'];

// Ambil user_id wali kelas
$qUserWali = mysqli_query($conn, "SELECT id FROM users WHERE username='$username' AND role='wali_kelas'");
$user_wali = mysqli_fetch_assoc($qUserWali);
$wali_kelas_id = $user_wali['id'];

// Ambil daftar siswa di kelas
$qSiswa = mysqli_query($conn, "
    SELECT s.id, s.nama, s.nis, u.id as user_id 
    FROM siswa s 
    JOIN users u ON s.nisn = u.username 
    WHERE s.kelas = '$kelas_diampu' 
    AND s.status = 'aktif'
    ORDER BY s.nama
");

$daftar_siswa = [];
if ($qSiswa) {
    while ($row = mysqli_fetch_assoc($qSiswa)) {
        $daftar_siswa[] = $row;
    }
}

// Handle selected student
$selected_siswa = null;
if (isset($_GET['siswa_id'])) {
    $siswa_id = intval($_GET['siswa_id']);
    foreach ($daftar_siswa as $siswa) {
        if ($siswa['id'] == $siswa_id) {
            $selected_siswa = $siswa;
            break;
        }
    }
}

// Handle send message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_message']) && $selected_siswa) {
    $pesan = trim($_POST['pesan']);
    
    if (!empty($pesan)) {
        $pesan = mysqli_real_escape_string($conn, $pesan);
        $penerima_id = $selected_siswa['user_id'];
        
        $query = "INSERT INTO chat_messages (pengirim_id, penerima_id, pesan, timestamp) 
                  VALUES ($wali_kelas_id, $penerima_id, '$pesan', NOW())";
        
        if (mysqli_query($conn, $query)) {
            echo json_encode(['status' => 'success', 'message' => 'Pesan berhasil dikirim!']);
            exit;
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal mengirim pesan: ' . mysqli_error($conn)]);
            exit;
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Pesan tidak boleh kosong']);
        exit;
    }
}

// API endpoint untuk mengambil pesan
if (isset($_GET['action']) && $_GET['action'] == 'get_messages' && isset($_GET['siswa_id'])) {
    $siswa_id = intval($_GET['siswa_id']);
    $selected_siswa = null;
    
    foreach ($daftar_siswa as $siswa) {
        if ($siswa['id'] == $siswa_id) {
            $selected_siswa = $siswa;
            break;
        }
    }
    
    if ($selected_siswa) {
        $qMessages = mysqli_query($conn, "
            SELECT cm.*, u.nama as pengirim_nama, u.role as pengirim_role 
            FROM chat_messages cm 
            JOIN users u ON cm.pengirim_id = u.id 
            WHERE (cm.pengirim_id = $wali_kelas_id AND cm.penerima_id = {$selected_siswa['user_id']}) 
               OR (cm.pengirim_id = {$selected_siswa['user_id']} AND cm.penerima_id = $wali_kelas_id)
            ORDER BY cm.timestamp ASC
        ");
        
        $messages = [];
        if ($qMessages) {
            while ($row = mysqli_fetch_assoc($qMessages)) {
                $messages[] = $row;
            }
        }
        
        header('Content-Type: application/json');
        echo json_encode($messages);
        exit;
    }
}

// Check for success message from session
$success = '';
if (isset($_SESSION['success'])) {
    $success = $_SESSION['success'];
    unset($_SESSION['success']);
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Wali Murid - Sistem Absensi QR</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Helvetica, Arial, sans-serif;
            background: #e5ddd5;
            height: 100vh;
            overflow: hidden;
        }

        .container {
            display: flex;
            height: 100vh;
            max-width: 1400px;
            margin: 0 auto;
            background: #fff;
            box-shadow: 0 1px 1px rgba(0,0,0,0.06);
        }

        /* Sidebar Styles */
        .sidebar {
            width: 350px;
            background: #fff;
            border-right: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
        }

        .sidebar-header {
            padding: 16px;
            background: #f0f0f0;
            border-bottom: 1px solid #e0e0e0;
        }

        .back-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            background: transparent;
            color: #54656f;
            text-decoration: none;
            border-radius: 20px;
            font-size: 14px;
            transition: background 0.3s;
        }

        .back-btn:hover {
            background: #f5f5f5;
            text-decoration: none;
            color: #54656f;
        }

        .sidebar-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin-top: 10px;
        }

        .sidebar-subtitle {
            font-size: 13px;
            color: #667781;
            margin-top: 4px;
        }

        .search-container {
            padding: 12px 16px;
            background: #fff;
            border-bottom: 1px solid #f0f0f0;
        }

        .search-box {
            width: 100%;
            padding: 10px 12px;
            background: #f0f2f5;
            border: none;
            border-radius: 20px;
            font-size: 14px;
            outline: none;
        }

        .search-box::placeholder {
            color: #667781;
        }

        .students-list {
            flex: 1;
            overflow-y: auto;
            background: #fff;
        }

        .student-item {
            display: flex;
            align-items: center;
            padding: 12px 16px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: background 0.3s;
            text-decoration: none;
            color: inherit;
        }

        .student-item:hover {
            background: #f5f5f5;
            text-decoration: none;
            color: inherit;
        }

        .student-item.active {
            background: #f0f2f5;
        }

        .student-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #25d366;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 18px;
            margin-right: 12px;
        }

        .student-info {
            flex: 1;
        }

        .student-name {
            font-weight: 500;
            color: #333;
            margin-bottom: 4px;
        }

        .student-nis {
            font-size: 13px;
            color: #667781;
        }

        /* Chat Area Styles */
        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #e5ddd5;
        }

        .chat-header {
            padding: 12px 16px;
            background: #f0f0f0;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .chat-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: #25d366;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 16px;
        }

        .chat-info {
            flex: 1;
        }

        .chat-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 2px;
        }

        .chat-status {
            font-size: 13px;
            color: #667781;
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #e5ddd5;
            background-image: url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z' fill='%239C92AC' fill-opacity='0.05' fill-rule='evenodd'/%3E%3C/svg%3E");
        }

        .message {
            max-width: 65%;
            margin-bottom: 8px;
            padding: 8px 12px;
            border-radius: 8px;
            position: relative;
            word-wrap: break-word;
            font-size: 14px;
            line-height: 1.4;
            animation: fadeIn 0.3s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .message.sent {
            align-self: flex-end;
            background: #dcf8c6;
            margin-left: auto;
            border-top-right-radius: 0;
        }

        .message.received {
            align-self: flex-start;
            background: #fff;
            margin-right: auto;
            border-top-left-radius: 0;
        }

        .message-time {
            font-size: 11px;
            color: #667781;
            margin-top: 4px;
            text-align: right;
        }

        .message.received .message-time {
            text-align: left;
        }

        .chat-input-container {
            padding: 12px 16px;
            background: #f0f0f0;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .message-input {
            flex: 1;
            padding: 12px 16px;
            background: #fff;
            border: none;
            border-radius: 20px;
            font-size: 14px;
            outline: none;
            resize: none;
            max-height: 100px;
            font-family: inherit;
        }

        .message-input::placeholder {
            color: #667781;
        }

        .send-btn {
            width: 45px;
            height: 45px;
            background: #25d366;
            border: none;
            border-radius: 50%;
            color: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s;
        }

        .send-btn:hover {
            background: #128c7e;
        }

        .send-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .empty-chat {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #667781;
            text-align: center;
        }

        .empty-chat i {
            font-size: 64px;
            margin-bottom: 16px;
            opacity: 0.3;
        }

        .empty-chat h3 {
            font-weight: 300;
            margin-bottom: 8px;
            color: #333;
        }

        .empty-chat p {
            font-size: 14px;
        }

        /* Alert Styles */
        .alert {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 14px;
            z-index: 1000;
            max-width: 300px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        .alert-success {
            background: #dcf8c6;
            color: #2d5016;
            border: 1px solid #b3e099;
        }

        .alert-error {
            background: #ffebee;
            color: #c62828;
            border: 1px solid #ffcdd2;
        }

        /* Scrollbar Styling */
        .students-list::-webkit-scrollbar,
        .chat-messages::-webkit-scrollbar {
            width: 6px;
        }

        .students-list::-webkit-scrollbar-track,
        .chat-messages::-webkit-scrollbar-track {
            background: transparent;
        }

        .students-list::-webkit-scrollbar-thumb,
        .chat-messages::-webkit-scrollbar-thumb {
            background: #ccc;
            border-radius: 3px;
        }

        .students-list::-webkit-scrollbar-thumb:hover,
        .chat-messages::-webkit-scrollbar-thumb:hover {
            background: #aaa;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                height: 40vh;
            }
            
            .chat-area {
                height: 60vh;
            }
            
            .message {
                max-width: 85%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Sidebar -->
        <div class="sidebar">
            <div class="sidebar-header">
                <a href="dashboard_wali_kelas.php" class="back-btn">
                    <i class="fas fa-arrow-left"></i> Kembali
                </a>
                <div class="sidebar-title">Chat Wali Murid</div>
                <div class="sidebar-subtitle">Kelas <?php echo htmlspecialchars($kelas_diampu); ?></div>
            </div>

            <div class="search-container">
                <input type="text" class="search-box" placeholder="Cari siswa...">
            </div>

            <div class="students-list">
                <?php foreach ($daftar_siswa as $siswa): ?>
                    <a href="chat_wali_murid.php?siswa_id=<?php echo $siswa['id']; ?>" 
                       class="student-item <?php echo $selected_siswa && $selected_siswa['id'] == $siswa['id'] ? 'active' : ''; ?>">
                        <div class="student-avatar">
                            <i class="fas fa-user-graduate"></i>
                        </div>
                        <div class="student-info">
                            <div class="student-name"><?php echo htmlspecialchars($siswa['nama']); ?></div>
                            <div class="student-nis">NIS: <?php echo htmlspecialchars($siswa['nis']); ?></div>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Chat Area -->
        <div class="chat-area">
            <?php if ($selected_siswa): ?>
                <div class="chat-header">
                    <div class="chat-avatar">
                        <i class="fas fa-user-graduate"></i>
                    </div>
                    <div class="chat-info">
                        <div class="chat-name"><?php echo htmlspecialchars($selected_siswa['nama']); ?></div>
                        <div class="chat-status">Online • NIS: <?php echo htmlspecialchars($selected_siswa['nis']); ?></div>
                    </div>
                </div>

                <div class="chat-messages" id="chatMessages">
                    <!-- Messages will be loaded dynamically -->
                </div>

                <div class="chat-input-container">
                    <form method="POST" class="chat-form" id="chatForm" style="display: flex; flex: 1; align-items: center; gap: 12px;">
                        <textarea name="pesan" class="message-input" 
                                  placeholder="Ketik pesan..." required id="messageInput"></textarea>
                        <button type="submit" name="send_message" class="send-btn">
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </form>
                </div>
            <?php else: ?>
                <div class="empty-chat">
                    <i class="fas fa-comments"></i>
                    <h3>Pilih Siswa</h3>
                    <p>Pilih siswa dari daftar untuk memulai percakapan</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        let currentSiswaId = <?php echo $selected_siswa ? $selected_siswa['id'] : 'null'; ?>;
        let lastMessageId = 0;
        let isPolling = false;

        // Load messages when page loads
        document.addEventListener('DOMContentLoaded', function() {
            if (currentSiswaId) {
                loadMessages();
                startPolling();
            }
            
            // Focus on input field if student is selected
            if (currentSiswaId) {
                document.getElementById('messageInput').focus();
            }
        });

        // Function to load messages via AJAX
        function loadMessages() {
            if (!currentSiswaId) return;
            
            fetch(`chat_wali_murid.php?action=get_messages&siswa_id=${currentSiswaId}`)
                .then(response => response.json())
                .then(messages => {
                    const chatMessages = document.getElementById('chatMessages');
                    chatMessages.innerHTML = '';
                    
                    if (messages.length === 0) {
                        chatMessages.innerHTML = `
                            <div class="empty-chat">
                                <i class="fas fa-comments"></i>
                                <h3>Belum Ada Pesan</h3>
                                <p>Mulai percakapan dengan <?php echo $selected_siswa ? htmlspecialchars($selected_siswa['nama']) : ''; ?></p>
                            </div>
                        `;
                    } else {
                        messages.forEach(msg => {
                            addMessageToChat(msg, false);
                        });
                        scrollToBottom();
                        
                        // Update last message ID for polling
                        if (messages.length > 0) {
                            lastMessageId = Math.max(...messages.map(m => m.id));
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading messages:', error);
                });
        }

        // Function to add message to chat
        function addMessageToChat(message, animate = true) {
            const chatMessages = document.getElementById('chatMessages');
            
            // Remove empty chat message if exists
            const emptyChat = chatMessages.querySelector('.empty-chat');
            if (emptyChat) {
                emptyChat.remove();
            }
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${message.pengirim_id == <?php echo $wali_kelas_id; ?> ? 'sent' : 'received'}`;
            
            if (animate) {
                messageDiv.style.animation = 'fadeIn 0.3s ease-in';
            }
            
            messageDiv.innerHTML = `
                <div class="message-text">${escapeHtml(message.pesan)}</div>
                <div class="message-time">
                    ${formatTime(message.timestamp)}
                </div>
            `;
            
            chatMessages.appendChild(messageDiv);
            
            if (animate) {
                scrollToBottom();
            }
        }

        // Function to check for new messages
        function checkNewMessages() {
            if (!currentSiswaId || isPolling) return;
            
            isPolling = true;
            fetch(`chat_wali_murid.php?action=get_messages&siswa_id=${currentSiswaId}`)
                .then(response => response.json())
                .then(messages => {
                    if (messages.length > 0) {
                        const newMessages = messages.filter(msg => msg.id > lastMessageId);
                        
                        if (newMessages.length > 0) {
                            newMessages.forEach(msg => {
                                addMessageToChat(msg, true);
                            });
                            
                            lastMessageId = Math.max(...messages.map(m => m.id));
                            
                            // Play notification sound for new received messages
                            const hasNewReceived = newMessages.some(msg => msg.pengirim_id != <?php echo $wali_kelas_id; ?>);
                            if (hasNewReceived) {
                                playNotificationSound();
                            }
                        }
                    }
                    isPolling = false;
                })
                .catch(error => {
                    console.error('Error checking new messages:', error);
                    isPolling = false;
                });
        }

        // Start polling for new messages
        function startPolling() {
            // Check every 2 seconds
            setInterval(checkNewMessages, 2000);
        }

        // Handle form submission with AJAX
        document.getElementById('chatForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();
            
            if (!message) return;
            
            const formData = new FormData();
            formData.append('pesan', message);
            formData.append('send_message', '1');
            
            // Disable send button
            const sendBtn = this.querySelector('.send-btn');
            sendBtn.disabled = true;
            
            fetch('chat_wali_murid.php?siswa_id=' + currentSiswaId, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(result => {
                if (result.status === 'success') {
                    // Clear input
                    messageInput.value = '';
                    messageInput.style.height = 'auto';
                    
                    // Reload messages to show the new one
                    loadMessages();
                    
                    showAlert('Pesan berhasil dikirim!', 'success');
                } else {
                    showAlert(result.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error sending message:', error);
                showAlert('Terjadi kesalahan saat mengirim pesan', 'error');
            })
            .finally(() => {
                sendBtn.disabled = false;
                messageInput.focus();
            });
        });

        // Auto scroll to bottom of chat
        function scrollToBottom() {
            const chatMessages = document.getElementById('chatMessages');
            if (chatMessages) {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        }

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

        // Search functionality
        const searchBox = document.querySelector('.search-box');
        const studentItems = document.querySelectorAll('.student-item');
        
        if (searchBox) {
            searchBox.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                
                studentItems.forEach(item => {
                    const studentName = item.querySelector('.student-name').textContent.toLowerCase();
                    const studentNis = item.querySelector('.student-nis').textContent.toLowerCase();
                    
                    if (studentName.includes(searchTerm) || studentNis.includes(searchTerm)) {
                        item.style.display = 'flex';
                    } else {
                        item.style.display = 'none';
                    }
                });
            });
        }

        // Utility functions
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function formatTime(timestamp) {
            const date = new Date(timestamp);
            return date.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' });
        }

        function showAlert(message, type) {
            const alert = document.createElement('div');
            alert.className = `alert alert-${type}`;
            alert.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i> ${message}
            `;
            
            document.body.appendChild(alert);
            
            setTimeout(() => {
                alert.remove();
            }, 3000);
        }

        function playNotificationSound() {
            // Create a simple notification sound
            const audio = new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA");
            audio.play().catch(e => console.log('Audio play failed:', e));
        }

        // Handle page visibility change
        document.addEventListener('visibilitychange', function() {
            if (!document.hidden) {
                // Page is visible, check for new messages
                checkNewMessages();
            }
        });
    </script>
</body>
</html>