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

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'siswa') {
    header('HTTP/1.1 403 Forbidden');
    exit;
}

$last_id = isset($_GET['last_id']) ? intval($_GET['last_id']) : 0;
$siswa_user_id = isset($_GET['siswa_id']) ? intval($_GET['siswa_id']) : 0;
$wali_user_id = isset($_GET['wali_id']) ? intval($_GET['wali_id']) : 0;

// Get new 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))
    AND cm.id > $last_id
    ORDER BY cm.timestamp ASC
");

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

header('Content-Type: application/json');
echo json_encode($messages);
?>