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

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

if (!isset($_SESSION['siswa_id'])) {
    die("Data siswa tidak ditemukan, silakan login ulang.");
}

$siswa_id = intval($_SESSION['siswa_id']);
$username = $_SESSION['username'];

// Ambil data siswa
$q_siswa = mysqli_query($conn, "SELECT * FROM siswa WHERE id = $siswa_id");
if (!$q_siswa || mysqli_num_rows($q_siswa) === 0) {
    die("Data siswa tidak ditemukan.");
}
$siswa = mysqli_fetch_assoc($q_siswa);

// Ambil user_id siswa dari tabel users
$q_user_siswa = mysqli_query($conn, "SELECT id FROM users WHERE username = '$username' AND role = 'siswa'");
if (!$q_user_siswa || mysqli_num_rows($q_user_siswa) === 0) {
    die("User siswa tidak ditemukan.");
}
$user_siswa = mysqli_fetch_assoc($q_user_siswa);
$siswa_user_id = $user_siswa['id'];

// Ambil data wali kelas
$kelas = $siswa['kelas'];
$q_wali = mysqli_query($conn, "SELECT * FROM wali_kelas WHERE kelas = '$kelas'");
if (!$q_wali || mysqli_num_rows($q_wali) === 0) {
    die("Wali kelas untuk kelas $kelas tidak ditemukan.");
}
$wali_kelas = mysqli_fetch_assoc($q_wali);

// Ambil user_id wali kelas
$q_user_wali = mysqli_query($conn, "SELECT id FROM users WHERE username = '{$wali_kelas['nip_wali']}' AND role = 'wali_kelas'");
if (!$q_user_wali || mysqli_num_rows($q_user_wali) === 0) {
    die("User wali kelas tidak ditemukan.");
}
$user_wali = mysqli_fetch_assoc($q_user_wali);
$wali_user_id = $user_wali['id'];

// Handle send message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_message'])) {
    $pesan = mysqli_real_escape_string($conn, $_POST['pesan']);
    
    if (!empty($pesan)) {
        $query = "INSERT INTO chat_messages (pengirim_id, penerima_id, pesan, timestamp) 
                  VALUES ($siswa_user_id, $wali_user_id, '$pesan', NOW())";
        
        if (mysqli_query($conn, $query)) {
            $_SESSION['success'] = "Pesan berhasil dikirim!";
            header("Location: chat_wali_siswa.php");
            exit;
        } else {
            $error = "Gagal mengirim pesan: " . mysqli_error($conn);
        }
    } else {
        $error = "Pesan tidak boleh kosong";
    }
}

// Ambil pesan
$messages = [];
$q_messages = 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 = $siswa_user_id AND cm.penerima_id = $wali_user_id) 
       OR (cm.pengirim_id = $wali_user_id AND cm.penerima_id = $siswa_user_id)
    ORDER BY cm.timestamp ASC
");

if ($q_messages) {
    while ($row = mysqli_fetch_assoc($q_messages)) {
        $messages[] = $row;
    }
}
?>

<!DOCTYPE html>
<html lang="id" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Wali Kelas - Sistem Absensi QR</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #6366f1;
            --success: #10b981;
            --card-bg: #ffffff;
            --card-bg-dark: #374151;
            --text-primary: #1f2937;
            --text-primary-dark: #f9fafb;
            --border-radius: 12px;
            --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .dark {
            --card-bg: var(--card-bg-dark);
            --text-primary: var(--text-primary-dark);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
            color: var(--text-primary);
            line-height: 1.6;
        }

        .dark body {
            background: #0f172a;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }

        .header {
            background: linear-gradient(135deg, #25d366 0%, #128c7e 100%);
            color: white;
            padding: 2rem;
            border-radius: var(--border-radius);
            margin-bottom: 2rem;
            text-align: center;
        }

        .header h1 {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }

        .back-btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            background: #6b7280;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            margin-bottom: 2rem;
            transition: background 0.3s;
        }

        .back-btn:hover {
            background: #4b5563;
        }

        .chat-container {
            display: grid;
            grid-template-columns: 1fr;
            gap: 2rem;
            height: 70vh;
        }

        .chat-area {
            background: var(--card-bg);
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            display: flex;
            flex-direction: column;
            height: 70vh;
        }

        .chat-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e5e7eb;
            background: #f8fafc;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .dark .chat-header {
            background: #374151;
        }

        .user-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.2rem;
        }

        .user-info h3 {
            margin-bottom: 0.25rem;
        }

        .user-info .status {
            font-size: 0.875rem;
            opacity: 0.8;
        }

        .chat-messages {
            flex: 1;
            padding: 1.5rem;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .message {
            max-width: 70%;
            padding: 1rem;
            border-radius: var(--border-radius);
            position: relative;
        }

        .message.sent {
            align-self: flex-end;
            background: var(--primary);
            color: white;
            border-bottom-right-radius: 4px;
        }

        .message.received {
            align-self: flex-start;
            background: #f1f5f9;
            color: var(--text-primary);
            border-bottom-left-radius: 4px;
        }

        .dark .message.received {
            background: #4b5563;
        }

        .message-time {
            font-size: 0.75rem;
            opacity: 0.7;
            margin-top: 0.5rem;
            text-align: right;
        }

        .chat-input {
            padding: 1.5rem;
            border-top: 1px solid #e5e7eb;
        }

        .chat-form {
            display: flex;
            gap: 1rem;
        }

        .message-input {
            flex: 1;
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 1rem;
            resize: none;
            height: 60px;
        }

        .send-btn {
            padding: 0.75rem 1.5rem;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .send-btn:hover {
            background: #4f46e5;
        }

        .empty-chat {
            text-align: center;
            color: #6b7280;
            padding: 3rem;
        }

        .empty-chat i {
            font-size: 4rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }

        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }

        .dark .alert-success {
            background: #064e3b;
            color: #a7f3d0;
        }

        .alert-error {
            background: #fee2e2;
            color: #dc2626;
            border: 1px solid #fecaca;
        }

        .dark .alert-error {
            background: #7f1d1d;
            color: #fecaca;
        }

        .online-dot {
            width: 8px;
            height: 8px;
            background: #10b981;
            border-radius: 50%;
            display: inline-block;
            margin-right: 0.5rem;
        }

        @media (max-width: 768px) {
            .container {
                padding: 1rem;
            }
            
            .chat-container {
                height: 80vh;
            }
            
            .chat-area {
                height: 80vh;
            }
            
            .message {
                max-width: 85%;
            }
            
            .chat-form {
                flex-direction: column;
            }
            
            .send-btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="dashboard_siswa.php" class="back-btn">
            <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
        </a>

        <div class="header">
            <h1><i class="fas fa-comments"></i> Chat Wali Kelas</h1>
            <p>Komunikasi langsung dengan wali kelas <?php echo htmlspecialchars($siswa['kelas']); ?></p>
        </div>

        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; ?>
            </div>
            <?php unset($_SESSION['success']); ?>
        <?php endif; ?>

        <?php if (isset($error)): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <div class="chat-container">
            <div class="chat-area">
                <div class="chat-header">
                    <div class="user-avatar">
                        <i class="fas fa-chalkboard-teacher"></i>
                    </div>
                    <div class="user-info">
                        <h3><?php echo htmlspecialchars($wali_kelas['nama_wali']); ?></h3>
                        <div class="status">
                            <span class="online-dot"></span>
                            Wali Kelas <?php echo htmlspecialchars($siswa['kelas']); ?> • Online
                        </div>
                    </div>
                </div>

                <div class="chat-messages" id="chatMessages">
                    <?php if (empty($messages)): ?>
                        <div class="empty-chat">
                            <i class="fas fa-comments"></i>
                            <h3>Belum Ada Pesan</h3>
                            <p>Mulai percakapan dengan wali kelas Anda</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($messages as $msg): ?>
                            <div class="message <?php echo $msg['pengirim_id'] == $siswa_user_id ? 'sent' : 'received'; ?>">
                                <div class="message-text"><?php echo htmlspecialchars($msg['pesan']); ?></div>
                                <div class="message-time">
                                    <?php echo date('H:i', strtotime($msg['timestamp'])); ?>
                                    • <?php echo date('d/m/Y', strtotime($msg['timestamp'])); ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <div class="chat-input">
                    <form method="POST" class="chat-form" id="chatForm">
                        <textarea name="pesan" class="message-input" 
                                placeholder="Ketik pesan Anda..." required id="messageInput"></textarea>
                        <button type="submit" name="send_message" class="send-btn">
                            <i class="fas fa-paper-plane"></i> Kirim
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

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

        // Auto scroll when page loads
        document.addEventListener('DOMContentLoaded', function() {
            scrollToBottom();
            document.getElementById('messageInput').focus();
        });

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

        // Real-time message updates
        let lastMessageId = <?php echo empty($messages) ? 0 : end($messages)['id']; ?>;
        
        function checkNewMessages() {
            fetch(`get_messages_siswa.php?last_id=${lastMessageId}&siswa_id=<?php echo $siswa_user_id; ?>&wali_id=<?php echo $wali_user_id; ?>`)
                .then(response => response.json())
                .then(messages => {
                    if (messages.length > 0) {
                        const chatMessages = document.getElementById('chatMessages');
                        const emptyState = chatMessages.querySelector('.empty-chat');
                        
                        if (emptyState) {
                            emptyState.remove();
                        }
                        
                        messages.forEach(msg => {
                            const messageDiv = document.createElement('div');
                            messageDiv.className = `message ${msg.pengirim_id == <?php echo $siswa_user_id; ?> ? 'sent' : 'received'}`;
                            messageDiv.innerHTML = `
                                <div class="message-text">${msg.pesan}</div>
                                <div class="message-time">
                                    ${new Date(msg.timestamp).toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })}
                                    • ${new Date(msg.timestamp).toLocaleDateString('id-ID')}
                                </div>
                            `;
                            chatMessages.appendChild(messageDiv);
                            lastMessageId = Math.max(lastMessageId, msg.id);
                        });
                        
                        scrollToBottom();
                    }
                })
                .catch(error => console.error('Error fetching messages:', error));
        }

        // Check for new messages every 3 seconds
        setInterval(checkNewMessages, 3000);
    </script>
</body>
</html>