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

include 'config.php';

// Filter data
$filter_tanggal = isset($_GET['tanggal']) ? $_GET['tanggal'] : date('Y-m-d');
$filter_kelas = isset($_GET['kelas']) ? $_GET['kelas'] : '';
$filter_pengirim = isset($_GET['pengirim']) ? $_GET['pengirim'] : '';

// Query data chat dengan join yang benar
$query = "SELECT 
            cm.*,
            u_pengirim.username as pengirim_username,
            u_pengirim.nama as pengirim_nama,
            u_pengirim.role as pengirim_role,
            u_penerima.username as penerima_username, 
            u_penerima.nama as penerima_nama,
            u_penerima.role as penerima_role,
            s.nama as siswa_nama,
            s.kelas as siswa_kelas,
            s.nis as siswa_nis,
            wk.nama_wali as wali_kelas_nama
          FROM chat_messages cm
          LEFT JOIN users u_pengirim ON cm.pengirim_id = u_pengirim.id
          LEFT JOIN users u_penerima ON cm.penerima_id = u_penerima.id
          LEFT JOIN siswa s ON (
            (u_pengirim.role = 'siswa' AND u_pengirim.username = s.nisn) OR 
            (u_penerima.role = 'siswa' AND u_penerima.username = s.nisn)
          )
          LEFT JOIN wali_kelas wk ON s.kelas = wk.kelas
          WHERE (u_pengirim.role IN ('siswa', 'wali_kelas') OR u_penerima.role IN ('siswa', 'wali_kelas'))
          AND (u_pengirim.role != u_penerima.role)";

$params = [];
if (!empty($filter_tanggal)) {
    $query .= " AND DATE(cm.timestamp) = ?";
    $params[] = $filter_tanggal;
}
if (!empty($filter_kelas) && $filter_kelas != 'all') {
    $query .= " AND s.kelas = ?";
    $params[] = $filter_kelas;
}
if (!empty($filter_pengirim) && $filter_pengirim != 'all') {
    $query .= " AND u_pengirim.role = ?";
    $params[] = $filter_pengirim;
}

$query .= " ORDER BY cm.timestamp DESC";

// Eksekusi query
$chats = [];
if (!empty($params)) {
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        $types = str_repeat('s', count($params));
        mysqli_stmt_bind_param($stmt, $types, ...$params);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_assoc($result)) {
            $chats[] = $row;
        }
        mysqli_stmt_close($stmt);
    }
} else {
    $result = mysqli_query($conn, $query);
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $chats[] = $row;
        }
    }
}

// Query untuk filter kelas
$kelas_query = mysqli_query($conn, "SELECT DISTINCT kelas FROM siswa WHERE status='aktif' ORDER BY kelas");

// Hitung statistik
$total_chats = count($chats);
$chat_siswa = array_filter($chats, function($chat) {
    return $chat['pengirim_role'] == 'siswa';
});
$chat_wali = array_filter($chats, function($chat) {
    return $chat['pengirim_role'] == 'wali_kelas';
});
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Riwayat Chat - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        .chat-container {
            max-height: 70vh;
            overflow-y: auto;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 15px;
            background: #f8f9fa;
        }
        .chat-message {
            margin-bottom: 15px;
            padding: 10px 15px;
            border-radius: 15px;
            max-width: 70%;
            word-wrap: break-word;
            position: relative;
        }
        .message-siswa {
            background: #e3f2fd;
            margin-right: auto;
            border-bottom-left-radius: 5px;
        }
        .message-wali {
            background: #f3e5f5;
            margin-left: auto;
            border-bottom-right-radius: 5px;
        }
        .message-header {
            font-size: 0.8rem;
            font-weight: 600;
            margin-bottom: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .message-sender {
            color: #666;
        }
        .message-time {
            color: #999;
            font-size: 0.7rem;
        }
        .message-content {
            margin: 0;
            line-height: 1.4;
        }
        .chat-info {
            font-size: 0.75rem;
            color: #6c757d;
            text-align: center;
            margin: 10px 0;
            padding: 5px;
            background: rgba(255,255,255,0.7);
            border-radius: 10px;
        }
        .empty-chat {
            text-align: center;
            color: #6c757d;
            padding: 40px;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            text-align: center;
        }
        .filter-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .role-badge {
            font-size: 0.7rem;
            padding: 2px 8px;
            border-radius: 10px;
        }
        .badge-siswa {
            background: #2196f3;
            color: white;
        }
        .badge-wali {
            background: #9c27b0;
            color: white;
        }
    </style>
</head>
<body class="container py-4">
    <h2 class="text-center mb-4"><i class="fas fa-comments"></i> Riwayat Chat Wali Murid & Wali Kelas</h2>

    <a href="dashboard.php" class="btn btn-secondary mb-3">← Kembali ke Dashboard</a>

    <!-- Statistik -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="stat-card">
                <h4><?php echo $total_chats; ?></h4>
                <small>Total Pesan</small>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-card">
                <h4><?php echo count($chat_siswa); ?></h4>
                <small>Dari Siswa/Wali</small>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-card">
                <h4><?php echo count($chat_wali); ?></h4>
                <small>Dari Wali Kelas</small>
            </div>
        </div>
    </div>

    <!-- Filter Form -->
    <div class="card filter-card">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-filter"></i> Filter Chat</h5>
        </div>
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label for="tanggal" class="form-label">Tanggal</label>
                    <input type="date" class="form-control" id="tanggal" name="tanggal" 
                           value="<?php echo $filter_tanggal; ?>">
                </div>
                <div class="col-md-3">
                    <label for="kelas" class="form-label">Kelas</label>
                    <select class="form-control" id="kelas" name="kelas">
                        <option value="all">Semua Kelas</option>
                        <?php while($kelas = mysqli_fetch_assoc($kelas_query)): ?>
                            <option value="<?php echo $kelas['kelas']; ?>" 
                                    <?php echo $filter_kelas == $kelas['kelas'] ? 'selected' : ''; ?>>
                                <?php echo $kelas['kelas']; ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="pengirim" class="form-label">Pengirim</label>
                    <select class="form-control" id="pengirim" name="pengirim">
                        <option value="all">Semua Pengirim</option>
                        <option value="siswa" <?php echo $filter_pengirim == 'siswa' ? 'selected' : ''; ?>>Siswa/Wali Murid</option>
                        <option value="wali_kelas" <?php echo $filter_pengirim == 'wali_kelas' ? 'selected' : ''; ?>>Wali Kelas</option>
                    </select>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-search"></i> Filter
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Container Chat -->
    <div class="card">
        <div class="card-header bg-info text-white">
            <strong><i class="fas fa-comment-dots"></i> Percakapan</strong>
            <span class="badge bg-light text-dark"><?php echo $total_chats; ?> Pesan</span>
        </div>
        <div class="card-body p-0">
            <?php if (empty($chats)): ?>
                <div class="empty-chat">
                    <i class="fas fa-comment-slash fa-3x mb-3"></i>
                    <h5>Tidak ada percakapan</h5>
                    <p class="text-muted">Tidak ada chat yang ditemukan untuk filter yang dipilih</p>
                </div>
            <?php else: ?>
                <div class="chat-container">
                    <?php
                    $current_date = null;
                    foreach ($chats as $chat):
                        $message_date = date('Y-m-d', strtotime($chat['timestamp']));
                        if ($current_date != $message_date):
                            $current_date = $message_date;
                    ?>
                            <div class="chat-info">
                                <i class="fas fa-calendar"></i> 
                                <?php echo date('d F Y', strtotime($current_date)); ?>
                            </div>
                        <?php endif; ?>

                        <div class="chat-message <?php echo $chat['pengirim_role'] == 'siswa' ? 'message-siswa' : 'message-wali'; ?>">
                            <div class="message-header">
                                <span class="message-sender">
                                    <?php 
                                    $sender_name = $chat['pengirim_nama'] ?: $chat['pengirim_username'];
                                    $role_badge = $chat['pengirim_role'] == 'siswa' ? 'badge-siswa' : 'badge-wali';
                                    $role_text = $chat['pengirim_role'] == 'siswa' ? 'Siswa/Wali' : 'Wali Kelas';
                                    ?>
                                    <span class="role-badge <?php echo $role_badge; ?>">
                                        <?php echo $role_text; ?>
                                    </span>
                                    <?php echo htmlspecialchars($sender_name); ?>
                                    
                                    <?php if ($chat['siswa_nama'] && $chat['pengirim_role'] == 'siswa'): ?>
                                        <br><small>(<?php echo $chat['siswa_nama']; ?> - <?php echo $chat['siswa_kelas']; ?>)</small>
                                    <?php endif; ?>
                                </span>
                                <span class="message-time">
                                    <?php echo date('H:i', strtotime($chat['timestamp'])); ?>
                                </span>
                            </div>
                            <p class="message-content"><?php echo nl2br(htmlspecialchars($chat['pesan'])); ?></p>
                            
                            <?php if ($chat['penerima_nama']): ?>
                                <div class="message-footer" style="font-size: 0.7rem; color: #666; margin-top: 5px;">
                                    <i class="fas fa-share"></i> Kepada: 
                                    <?php echo htmlspecialchars($chat['penerima_nama']); ?>
                                    (<?php echo ucfirst(str_replace('_', ' ', $chat['penerima_role'])); ?>)
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto scroll ke bawah chat container
        document.addEventListener('DOMContentLoaded', function() {
            const chatContainer = document.querySelector('.chat-container');
            if (chatContainer) {
                chatContainer.scrollTop = chatContainer.scrollHeight;
            }
        });

        // Set tanggal default ke hari ini
        document.getElementById('tanggal').value = '<?php echo date('Y-m-d'); ?>';
    </script>
</body>
</html>