<?php
/**
 * ===================================================================================
 * Subject Actions Handler
 * ===================================================================================
 *
 * File: subject_actions.php
 * Location: /homework_portal/admin/subject_actions.php
 *
 * Purpose:
 * 1. A central, secure script to handle all actions related to subjects (e.g., delete).
 * 2. It is not intended to be viewed directly, only to process requests.
 * 3. Redirects back to the manage_subjects.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'] ?? '';
$subject_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$message_type = 'error';
$message = 'An unknown error occurred.';

if ($subject_id > 0) {
    if ($action === 'delete') {
        try {
            // Check if the subject is assigned to any teacher-class combination
            $check_stmt = $pdo->prepare("SELECT COUNT(*) FROM teacher_subject_class WHERE subject_id = ?");
            $check_stmt->execute([$subject_id]);
            $assignment_count = $check_stmt->fetchColumn();

            if ($assignment_count > 0) {
                // Prevent deletion if the subject is in use
                $message = "Cannot delete subject. It is currently assigned to {$assignment_count} teacher/class combination(s). Please unassign it first.";
            } else {
                // If not in use, proceed with deletion
                $delete_stmt = $pdo->prepare("DELETE FROM subjects WHERE id = ?");
                $delete_stmt->execute([$subject_id]);

                if ($delete_stmt->rowCount() > 0) {
                    $message = 'Subject has been deleted successfully.';
                    $message_type = 'success';
                } else {
                    $message = 'Could not find the specified subject to delete.';
                }
            }
        } catch (PDOException $e) {
            $message = 'Database error: Could not delete subject.';
            // error_log($e->getMessage());
        }
    } else {
        $message = 'Invalid action specified.';
    }
} else {
    $message = 'Invalid Subject ID specified.';
}

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