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

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'siswa') {
    header('Content-Type: application/json');
    echo json_encode([]);
    exit;
}

if (!isset($_SESSION['siswa_id'])) {
    header('Content-Type: application/json');
    echo json_encode([]);
    exit;
}

$siswa_id = intval($_SESSION['siswa_id']);
$wali_kelas_id = isset($_GET['wali_kelas_id']) ? intval($_GET['wali_kelas_id']) : 0;

if ($wali_kelas_id <= 0) {
    echo json_encode([]);
    exit;
}

$qPesan = 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_id AND cm.penerima_id = $wali_kelas_id) 
       OR (cm.pengirim_id = $wali_kelas_id AND cm.penerima_id = $siswa_id)
    ORDER BY cm.timestamp ASC
");

$pesan = [];
if ($qPesan) {
    while ($row = mysqli_fetch_assoc($qPesan)) {
        $pesan[] = $row;
    }
}

echo json_encode($pesan);
?>