<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

include "../user/db.php";
include "back.php";

/* =========================
   Protect admin page
========================= */
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

/* =========================
   Handle reply
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $message_id = intval($_POST['message_id'] ?? 0);
    $reply      = trim($_POST['reply'] ?? '');

    // ✅ USE user_id as admin_id
    $admin_id = $_SESSION['user_id'];

    if ($message_id > 0 && !empty($reply)) {

        $stmt = $conn->prepare("
            INSERT INTO student_message_replies (message_id, admin_id, reply)
            VALUES (?, ?, ?)
        ");

        $stmt->bind_param("iis", $message_id, $admin_id, $reply);
        $stmt->execute();
        $stmt->close();
    }
}

header("Location: messages.php");
exit;
include "footer.php";