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

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

if (!isset($_SESSION['siswa_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Siswa ID not found']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pengirim_id = intval($_SESSION['siswa_id']);
    $penerima_id = intval($_POST['penerima_id']);
    $pesan = trim($_POST['pesan']);
    
    if (empty($pesan)) {
        echo json_encode(['success' => false, 'message' => 'Pesan tidak boleh kosong']);
        exit;
    }
    
    // Validasi bahwa penerima adalah wali kelas siswa
    $siswa_id = $_SESSION['siswa_id'];
    $qSiswa = mysqli_query($conn, "SELECT kelas FROM siswa WHERE id = $siswa_id");
    
    if (!$qSiswa) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . mysqli_error($conn)]);
        exit;
    }
    
    $siswa = mysqli_fetch_assoc($qSiswa);
    $kelas = $siswa['kelas'];
    
    // Cek apakah penerima adalah wali kelas dari kelas siswa
    $qWaliKelas = mysqli_query($conn, "SELECT wk.id, wk.nip_wali 
                                     FROM wali_kelas wk 
                                     WHERE wk.kelas = '$kelas'");
    
    if (!$qWaliKelas) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . mysqli_error($conn)]);
        exit;
    }
    
    if (mysqli_num_rows($qWaliKelas) === 0) {
        echo json_encode(['success' => false, 'message' => 'Wali kelas tidak ditemukan untuk kelas ' . $kelas]);
        exit;
    }
    
    $wali_kelas = mysqli_fetch_assoc($qWaliKelas);
    
    // Cek user_id wali kelas di tabel users
    $qUserWali = mysqli_query($conn, "SELECT id FROM users WHERE username = '{$wali_kelas['nip_wali']}' AND role = 'wali_kelas'");
    if (!$qUserWali || mysqli_num_rows($qUserWali) === 0) {
        echo json_encode(['success' => false, 'message' => 'User wali kelas tidak ditemukan']);
        exit;
    }
    
    $userWali = mysqli_fetch_assoc($qUserWali);
    
    // Validasi bahwa penerima_id sesuai dengan user_id wali kelas
    if ($penerima_id != $userWali['id']) {
        echo json_encode(['success' => false, 'message' => 'Penerima tidak valid']);
        exit;
    }
    
    // Simpan pesan ke database
    $pesan = mysqli_real_escape_string($conn, $pesan);
    $timestamp = date('Y-m-d H:i:s');
    
    $qInsert = mysqli_query($conn, "INSERT INTO chat_messages (pengirim_id, penerima_id, pesan, timestamp) 
                                   VALUES ($pengirim_id, $penerima_id, '$pesan', '$timestamp')");
    
    if ($qInsert) {
        echo json_encode(['success' => true, 'message_id' => mysqli_insert_id($conn)]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal menyimpan pesan: ' . mysqli_error($conn)]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
}
?>