<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

require_once 'connectiondb.php';

$errors = [];
$success_message = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Handle removal of student from batch
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_enrollment'])) {
    $batch_id = $_POST['batch_id_remove'] ?? '';
    $student_id = $_POST['student_id_remove'] ?? '';

    if (empty($batch_id) || empty($student_id)) {
        $errors[] = "Batch ID and Student ID are required to remove enrollment.";
    } else {
        // Check if student is enrolled in the batch
        $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM batch_enrollments WHERE batch_id = ? AND student_id = ?");
        $stmtCheck->execute([$batch_id, $student_id]);
        if ($stmtCheck->fetchColumn() == 0) {
            $errors[] = "Student is not enrolled in the selected batch.";
        } else {
            // Delete enrollment
            $stmtDelete = $pdo->prepare("DELETE FROM batch_enrollments WHERE batch_id = ? AND student_id = ?");
            if ($stmtDelete->execute([$batch_id, $student_id])) {
                $success_message = "Student removed from batch successfully.";
            } else {
                $errors[] = "Failed to remove student from batch.";
            }
        }
    }
}

// Fetch all batches
$stmt = $pdo->query("SELECT * FROM batches ORDER BY batch_name");
$batches = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch all students
$stmt = $pdo->query("SELECT id, student_id, name FROM students ORDER BY name");
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle single enrollment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['enroll'])) {
    $batch_id = $_POST['batch_id'] ?? '';
    $student_id = $_POST['student_id'] ?? '';

    if (empty($batch_id) || empty($student_id)) {
        $errors[] = "Please select both batch and student.";
    } else {
        // Check if already enrolled
        $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM batch_enrollments WHERE batch_id = ? AND student_id = ?");
        $stmtCheck->execute([$batch_id, $student_id]);
        if ($stmtCheck->fetchColumn() > 0) {
            $errors[] = "Student is already enrolled in this batch.";
        } else {
            $stmtInsert = $pdo->prepare("INSERT INTO batch_enrollments (batch_id, student_id) VALUES (?, ?)");
            if ($stmtInsert->execute([$batch_id, $student_id])) {
                $success_message = "Student enrolled successfully.";
            } else {
                $errors[] = "Failed to enroll student.";
            }
        }
    }
}

// Handle bulk enrollment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_enroll'])) {
    $batch_id = $_POST['batch_id_bulk'] ?? '';
    $student_ids = $_POST['student_ids_bulk'] ?? [];

    if (empty($batch_id) || empty($student_ids) || !is_array($student_ids)) {
        $errors[] = "Please select a batch and at least one student for bulk enrollment.";
    } else {
        $enrolled_count = 0;
        foreach ($student_ids as $student_id) {
            // Check if already enrolled
            $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM batch_enrollments WHERE batch_id = ? AND student_id = ?");
            $stmtCheck->execute([$batch_id, $student_id]);
            if ($stmtCheck->fetchColumn() == 0) {
                $stmtInsert = $pdo->prepare("INSERT INTO batch_enrollments (batch_id, student_id) VALUES (?, ?)");
                if ($stmtInsert->execute([$batch_id, $student_id])) {
                    $enrolled_count++;
                }
            }
        }
        $success_message = "Bulk enrollment completed. $enrolled_count student(s) enrolled.";
    }
}

// Handle transfer
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['transfer'])) {
    $old_batch_id = $_POST['old_batch_id'] ?? '';
    $new_batch_id = $_POST['new_batch_id'] ?? '';
    $student_id = $_POST['student_id_transfer'] ?? '';

    if (empty($old_batch_id) || empty($new_batch_id) || empty($student_id)) {
        $errors[] = "Please select old batch, new batch, and student.";
    } elseif ($old_batch_id == $new_batch_id) {
        $errors[] = "Old batch and new batch cannot be the same.";
    } else {
        // Check if student is enrolled in old batch
        $stmtCheckOld = $pdo->prepare("SELECT COUNT(*) FROM batch_enrollments WHERE batch_id = ? AND student_id = ?");
        $stmtCheckOld->execute([$old_batch_id, $student_id]);
        if ($stmtCheckOld->fetchColumn() == 0) {
            $errors[] = "Student is not enrolled in the old batch.";
        } else {
            // Check if already enrolled in new batch
            $stmtCheckNew = $pdo->prepare("SELECT COUNT(*) FROM batch_enrollments WHERE batch_id = ? AND student_id = ?");
            $stmtCheckNew->execute([$new_batch_id, $student_id]);
            if ($stmtCheckNew->fetchColumn() > 0) {
                $errors[] = "Student is already enrolled in the new batch.";
            } else {
                // Update enrollment
                $stmtUpdate = $pdo->prepare("UPDATE batch_enrollments SET batch_id = ? WHERE batch_id = ? AND student_id = ?");
                if ($stmtUpdate->execute([$new_batch_id, $old_batch_id, $student_id])) {
                    $success_message = "Student transferred successfully.";
                } else {
                    $errors[] = "Failed to transfer student.";
                }
            }
        }
    }
}

// Fetch enrollments for display
$stmtEnrollments = $pdo->query("
    SELECT be.id, be.batch_id, b.batch_name, s.student_id, s.name, s.id as student_internal_id
    FROM batch_enrollments be
    JOIN batches b ON be.batch_id = b.id
    JOIN students s ON be.student_id = s.id
    ORDER BY b.batch_name, s.name
");
$enrollments = $stmtEnrollments->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Admin - Batch Enrollments</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container my-4">
    <h2>Batch Enrollments</h2>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success_message): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
    <?php endif; ?>

    <h4>Enroll Student to Batch</h4>
    <form method="POST" action="admin_batch_enrollments.php" class="mb-4">
        <div class="mb-3">
            <label for="batch_id" class="form-label">Select Batch</label>
            <select name="batch_id" id="batch_id" class="form-select" required>
                <option value="">Select Batch</option>
                <?php foreach ($batches as $batch): ?>
                    <option value="<?php echo htmlspecialchars($batch['id']); ?>"><?php echo htmlspecialchars($batch['batch_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mb-3">
            <label for="student_id" class="form-label">Select Student</label>
            <select name="student_id" id="student_id" class="form-select" required>
                <option value="">Select Student</option>
                <?php foreach ($students as $student): ?>
                    <option value="<?php echo htmlspecialchars($student['id']); ?>"><?php echo htmlspecialchars($student['student_id'] . ' - ' . $student['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" name="enroll" class="btn btn-primary">Enroll</button>
    </form>

    <h4>Bulk Enroll Students to Batch</h4>
    <form method="POST" action="admin_batch_enrollments.php" class="mb-4">
        <div class="mb-3">
            <label for="batch_id_bulk" class="form-label">Select Batch</label>
            <select name="batch_id_bulk" id="batch_id_bulk" class="form-select" required>
                <option value="">Select Batch</option>
                <?php foreach ($batches as $batch): ?>
                    <option value="<?php echo htmlspecialchars($batch['id']); ?>"><?php echo htmlspecialchars($batch['batch_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mb-3">
            <label class="form-label">Select Students</label>
            <div style="max-height: 300px; overflow-y: auto; border: 1px solid #ced4da; padding: 10px;">
                <?php foreach ($students as $student): ?>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="student_ids_bulk[]" value="<?php echo htmlspecialchars($student['id']); ?>" id="student_bulk_<?php echo htmlspecialchars($student['id']); ?>">
                        <label class="form-check-label" for="student_bulk_<?php echo htmlspecialchars($student['id']); ?>">
                            <?php echo htmlspecialchars($student['student_id'] . ' - ' . $student['name']); ?>
                        </label>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <button type="submit" name="bulk_enroll" class="btn btn-primary">Bulk Enroll</button>
    </form>

    <h4>Transfer Student Between Batches</h4>
    <form method="POST" action="admin_batch_enrollments.php" class="mb-4">
        <div class="mb-3">
            <label for="old_batch_id" class="form-label">Old Batch</label>
            <select name="old_batch_id" id="old_batch_id" class="form-select" required>
                <option value="">Select Old Batch</option>
                <?php foreach ($batches as $batch): ?>
                    <option value="<?php echo htmlspecialchars($batch['id']); ?>"><?php echo htmlspecialchars($batch['batch_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mb-3">
            <label for="new_batch_id" class="form-label">New Batch</label>
            <select name="new_batch_id" id="new_batch_id" class="form-select" required>
                <option value="">Select New Batch</option>
                <?php foreach ($batches as $batch): ?>
                    <option value="<?php echo htmlspecialchars($batch['id']); ?>"><?php echo htmlspecialchars($batch['batch_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mb-3">
            <label for="student_id_transfer" class="form-label">Select Student</label>
            <select name="student_id_transfer" id="student_id_transfer" class="form-select" required>
                <option value="">Select Student</option>
                <?php foreach ($students as $student): ?>
                    <option value="<?php echo htmlspecialchars($student['id']); ?>"><?php echo htmlspecialchars($student['student_id'] . ' - ' . $student['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" name="transfer" class="btn btn-warning">Transfer</button>
    </form>

    <h4>Current Enrollments</h4>
    <?php if (empty($enrollments)): ?>
        <p>No enrollments found.</p>
    <?php else: ?>
        <?php
        // Count enrollments per student to check if enrolled in multiple batches
        $studentEnrollmentCounts = [];
        foreach ($enrollments as $enrollment) {
            $studentEnrollmentCounts[$enrollment['student_internal_id']] = ($studentEnrollmentCounts[$enrollment['student_internal_id']] ?? 0) + 1;
        }
        ?>
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Batch Name</th>
                    <th>Student ID</th>
                    <th>Student Name</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($enrollments as $enrollment): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($enrollment['batch_name']); ?></td>
                        <td><?php echo htmlspecialchars($enrollment['student_id']); ?></td>
                        <td><?php echo htmlspecialchars($enrollment['name']); ?></td>
                        <td>
                            <?php if (($studentEnrollmentCounts[$enrollment['student_internal_id']] ?? 0) > 1): ?>
                                <form method="POST" action="admin_batch_enrollments.php" onsubmit="return confirm('Are you sure you want to remove this student from this batch?');" style="display:inline;">
                                    <input type="hidden" name="batch_id_remove" value="<?php echo htmlspecialchars($enrollment['batch_id']); ?>" />
                                    <input type="hidden" name="student_id_remove" value="<?php echo htmlspecialchars($enrollment['student_internal_id']); ?>" />
                                    <button type="submit" name="remove_enrollment" class="btn btn-danger btn-sm">Remove</button>
                                </form>
                            <?php else: ?>
                                <span class="text-muted">N/A</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
