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

if ($class_id > 0) {
    if ($action === 'delete') {
        try {
            // Before deleting a class, we need to check if any students are assigned to it.
            $check_stmt = $pdo->prepare("SELECT COUNT(id) FROM students WHERE class_id = ?");
            $check_stmt->execute([$class_id]);
            $student_count = $check_stmt->fetchColumn();

            if ($student_count > 0) {
                // Prevent deletion if students are in the class
                $message = "Cannot delete class. There are {$student_count} student(s) assigned to it. Please re-assign them first.";
            } else {
                // If no students, proceed with deletion
                $delete_stmt = $pdo->prepare("DELETE FROM classes WHERE id = ?");
                $delete_stmt->execute([$class_id]);

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

        } catch (PDOException $e) {
            $message = 'Database error: Could not delete class.';
            // error_log($e->getMessage());
        }
    } else {
        $message = 'Invalid action specified.';
    }
} else {
    $message = 'Invalid Class ID specified.';
}

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