<?php
/**
 * ===================================================================================
 * Teacher Actions Handler
 * ===================================================================================
 *
 * File: teacher_actions.php
 * Location: /homework_portal/admin/teacher_actions.php
 *
 * Purpose:
 * 1. A central, secure script to handle all actions related to teachers.
 * 2. It is not intended to be viewed directly, only to process requests.
 * 3. Currently handles teacher deletion.
 * 4. Redirects back to the manage_teachers.php page with a feedback message.
 */

require_once '../config.php';

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

// Get the action and ID from the URL
$action = $_GET['action'] ?? '';
$teacher_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$message_type = 'error';
$message = 'An unknown error occurred.';

if ($teacher_id > 0) {
    if ($action === 'delete') {
        try {
            // NOTE: Add logic here to re-assign or handle classes/subjects associated with this teacher before deletion if necessary.
            // For now, we will just delete the teacher record.
            
            $stmt = $pdo->prepare("DELETE FROM teachers WHERE id = ?");
            $stmt->execute([$teacher_id]);

            if ($stmt->rowCount() > 0) {
                $message = 'Teacher account has been deleted successfully.';
                $message_type = 'success';
            } else {
                $message = 'Could not find the specified teacher to delete.';
            }

        } catch (PDOException $e) {
            // If the teacher is linked to other tables (e.g., assignments), a foreign key constraint might prevent deletion.
            $message = 'Database error: Could not delete teacher. They may still be assigned to classes or have posted assignments.';
            // error_log($e->getMessage());
        }
    } else {
        $message = 'Invalid action specified.';
    }
} else {
    $message = 'Invalid Teacher ID specified.';
}

// Redirect back to the teacher management page with feedback.
header('Location: manage_teachers.php?' . $message_type . '=' . urlencode($message));
exit();
?>
