<?php
/**
 * ===================================================================================
 * Admin Message Actions Handler
 * ===================================================================================
 *
 * File: message_actions.php
 * Location: /homework_portal/admin/message_actions.php
 *
 * Purpose:
 * 1. Securely handles actions related to messages, like deleting a thread.
 */

require_once '../config.php';

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

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

if ($thread_id > 0 && $action === 'delete') {
    try {
        // Delete the main message AND all replies linked to it.
        $sql = "DELETE FROM teacher_messages WHERE id = ? OR parent_message_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$thread_id, $thread_id]);

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

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