<?php
// delete_user.php
// Handles the deletion of a user (student/instructor) after crucial checks.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Ensure user is logged in and has the necessary role (admin).
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'admin') {
    $_SESSION['message'] = "Unauthorized access.";
    $_SESSION['is_error'] = true;
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;

if ($user_id > 0) {
    try {
        $pdo->beginTransaction();

        // 1. Determine the user's current role
        $stmt_role = $pdo->prepare("SELECT role FROM users WHERE id = ?");
        $stmt_role->execute([$user_id]);
        $user_role_to_delete = $stmt_role->fetchColumn();

        if (!$user_role_to_delete) {
            // User not found, but safe to continue to cleanup/end transaction
        }
        
        // --- Integrity Checks Based on Role ---
        
        // A. Check for Enrollments (Primary for Students)
        $stmt_check_enrollments = $pdo->prepare("SELECT COUNT(*) FROM course_enrollments WHERE student_id = ?");
        $stmt_check_enrollments->execute([$user_id]);
        $enrollment_count = $stmt_check_enrollments->fetchColumn();

        if ($enrollment_count > 0) {
            $_SESSION['message'] = "Cannot delete this user. They are currently enrolled in " . $enrollment_count . " course(s).";
            $_SESSION['is_error'] = true;
            $pdo->rollBack();
            header("Location: index.php?page=manage_users");
            exit();
        }

        // B. Check for Managed Batches (Primary for Instructors)
        // Assuming your 'batches' table has an 'instructor_id' column linked to 'users.id'
        if ($user_role_to_delete === 'instructor' || $user_role_to_delete === 'admin') {
            $stmt_check_batches = $pdo->prepare("SELECT COUNT(*) FROM batches WHERE instructor_id = ?");
            $stmt_check_batches->execute([$user_id]);
            $batch_count = $stmt_check_batches->fetchColumn();

            if ($batch_count > 0) {
                $_SESSION['message'] = "Cannot delete this " . $user_role_to_delete . ". They are currently assigned to " . $batch_count . " batch(es).";
                $_SESSION['is_error'] = true;
                $pdo->rollBack();
                header("Location: index.php?page=manage_users");
                exit();
            }
        }
        
        // --- Proceed with Deletion ---

        // The user has no active dependencies, now delete the record.
        $stmt_delete_user = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt_delete_user->execute([$user_id]);

        if ($stmt_delete_user->rowCount() > 0) {
            $pdo->commit();
            $_SESSION['message'] = "User deleted successfully.";
            $_SESSION['is_error'] = false;
        } else {
            $pdo->rollBack();
            $_SESSION['message'] = "User not found or could not be deleted.";
            $_SESSION['is_error'] = true;
        }

    } catch (PDOException $e) {
        $pdo->rollBack();
        $_SESSION['message'] = "Database error: " . $e->getMessage();
        $_SESSION['is_error'] = true;
        error_log("User Deletion Error: " . $e->getMessage());
    }
} else {
    $_SESSION['message'] = "Invalid user ID for deletion.";
    $_SESSION['is_error'] = true;
}

header("Location: index.php?page=manage_users");
exit();