<?php
/**
 * ===================================================================================
 * Teacher Message Actions Handler
 * ===================================================================================
 *
 * File: message_actions.php
 * Location: /homework_portal/teacher/message_actions.php
 *
 * Purpose:
 * 1. Securely handles a teacher deleting a message from their own inbox.
 */

require_once '../config.php';

// --- Security Check ---
if (!isset($_SESSION['teacher_id'])) {
    header('Location: login.php');
    exit();
}

$teacher_id = $_SESSION['teacher_id'];
$action = $_GET['action'] ?? '';
$message_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$message_type = 'error';
$message = 'An unknown error occurred.';

if ($message_id > 0 && $action === 'delete') {
    try {
        // This is a crucial security check to ensure a teacher can ONLY delete messages from their own inbox.
        $sql = "DELETE FROM teacher_messages WHERE id = ? AND teacher_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$message_id, $teacher_id]);

        if ($stmt->rowCount() > 0) {
            $message = 'Message has been deleted successfully.';
            $message_type = 'success';
        } else {
            $message = 'Could not find the message to delete, or you do not have permission.';
        }
    } catch (PDOException $e) {
        $message = "Database error: Could not delete the message.";
    }
} else {
    $message = "Invalid action or message ID.";
}

header('Location: inbox.php?' . $message_type . '=' . urlencode($message));
exit();
?>
