<?php
// delete_batch.php
// Handles the deletion of a batch securely.

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

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

require_once 'config/database.php';

// Get the batch ID from the URL and validate it.
$batch_id = isset($_GET['batch_id']) ? (int)$_GET['batch_id'] : 0;

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

        // Check if there are any student enrollments for this batch.
        // CORRECTED: Changed table name to course_enrollments
        $stmt_check_students = $pdo->prepare("SELECT COUNT(*) FROM course_enrollments WHERE batch_id = ?");
        $stmt_check_students->execute([$batch_id]);
        $student_count = $stmt_check_students->fetchColumn();

        if ($student_count > 0) {
            $_SESSION['message'] = "Cannot delete this batch. It has " . $student_count . " enrolled student(s).";
            $_SESSION['is_error'] = true;
            $pdo->rollBack();
            header("Location: index.php?page=manage_batches");
            exit();
        }

        // Delete associated records first to avoid foreign key constraints.
        // This query is a safety measure; your `batches` table doesn't have a direct link to `batch_schedules` in the provided schema, but it's good practice.
        $stmt_delete_schedule = $pdo->prepare("DELETE FROM batch_schedules WHERE batch_id = ?");
        $stmt_delete_schedule->execute([$batch_id]);

        // Now, delete the batch itself.
        $stmt_delete_batch = $pdo->prepare("DELETE FROM batches WHERE id = ?");
        $stmt_delete_batch->execute([$batch_id]);

        if ($stmt_delete_batch->rowCount() > 0) {
            $pdo->commit();
            $_SESSION['message'] = "Batch deleted successfully.";
            $_SESSION['is_error'] = false;
        } else {
            $pdo->rollBack();
            $_SESSION['message'] = "Batch 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("Batch Deletion Error: " . $e->getMessage());
    }
} else {
    $_SESSION['message'] = "Invalid batch ID for deletion.";
    $_SESSION['is_error'] = true;
}

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