<?php
require_once 'config/database.php';

if (isset($_POST['class_id'])) {
    $class_id = (int)$_POST['class_id'];
    
    if ($class_id > 0) {
        try {
            // Check if class has any ACTIVE students
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id = ? AND status = 'active'");
            $stmt->execute([$class_id]);
            $student_count = $stmt->fetchColumn();
            
            if ($student_count > 0) {
                echo "Error: Cannot delete class - it has $student_count active students";
            } else {
                $pdo->beginTransaction();
                
                // Delete all related records first
                $stmt = $pdo->prepare("DELETE FROM class_teachers WHERE class_id = ?");
                $stmt->execute([$class_id]);
                
                $stmt = $pdo->prepare("DELETE FROM class_subjects WHERE class_id = ?");
                $stmt->execute([$class_id]);
                
                // Finally delete the class itself
                $stmt = $pdo->prepare("DELETE FROM classes WHERE id = ?");
                $stmt->execute([$class_id]);
                
                $pdo->commit();
                echo "Success: Class deleted successfully";
            }
        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            echo "Error: " . $e->getMessage();
        }
    } else {
        echo "Error: Invalid class ID";
    }
} else {
    echo "Please provide a class_id parameter";
}
?>