<?php
session_start();
if (!isset($_SESSION['student_id'])) {
    die("Student not logged in.");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $studentId = $_SESSION['student_id'];
    $recipientId = isset($_POST['recipient_id']) ? intval($_POST['recipient_id']) : 0;
    $message = isset($_POST['message']) ? trim($_POST['message']) : '';

    if ($recipientId && $message) {
        include('db_connection.php'); // Ensure this path is correct

        $query = "INSERT INTO student_messages (sender_id, receiver_id, message, timestamp, status) VALUES (?, ?, ?, NOW(), 'Unread')";
        $stmt = $conn->prepare($query);
        $stmt->bind_param('iis', $studentId, $recipientId, $message);
        $stmt->execute();

        $conn->close();

        header("Location: send_messages.php?student_id=" . urlencode($recipientId));
        exit;
    }
}
?>
