<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../classes/Course.php';

requireLogin();
requireAnyRole(['instructor']);

$user = getCurrentUser();
$db = Database::getInstance();
$courseModel = new Course();

// Handle status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['action']) && !empty($_POST['enrollment_id'])) {
    $eid = (int)$_POST['enrollment_id'];
    $action = $_POST['action'];

    // Ensure enrollment belongs to one of instructor's courses
    $row = $db->get("SELECT ce.* FROM course_enrollments ce JOIN courses c ON ce.course_id = c.id WHERE ce.id = ? AND c.instructor_id = ?", [$eid, $user['id']]);
    if ($row) {
        if ($action === 'set_active') {
            $db->update('course_enrollments', ['status' => 'active'], 'id = ?', [$eid]);
            setFlashMessage('success', 'Enrollment set to active.');
        } elseif ($action === 'set_completed') {
            $db->update('course_enrollments', ['status' => 'completed'], 'id = ?', [$eid]);
            setFlashMessage('success', 'Enrollment marked completed.');
        } elseif ($action === 'revoke') {
            $db->update('course_enrollments', ['status' => 'revoked'], 'id = ?', [$eid]);
            setFlashMessage('success', 'Enrollment revoked.');
        }
    } else {
        setFlashMessage('error', 'Enrollment not found.');
    }

    header('Location: ' . APP_URL . '/lms/enrollments.php');
    exit;
}

$pageTitle = 'Enrollments';
include __DIR__ . '/includes/header.php';

$enrollments = $db->getAll(
    "SELECT ce.*, c.title as course_title, u.first_name, u.last_name
     FROM course_enrollments ce
     JOIN courses c ON ce.course_id = c.id
     JOIN users u ON ce.student_id = u.id
     WHERE c.instructor_id = ?
     ORDER BY ce.enrollment_date DESC",
    [$user['id']]
);
?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="m-0">Enrollments</h5>
        <a href="<?php echo APP_URL; ?>/lms/dashboards/instructor.php" class="btn btn-outline-secondary btn-sm">Back</a>
    </div>
    <div class="card-body">
        <?php if (empty($enrollments)): ?>
            <p class="text-muted">No enrollments found for your courses.</p>
        <?php else: ?>
            <table class="table table-striped">
                <thead>
                    <tr><th>Student</th><th>Course</th><th>Date</th><th>Status</th><th>Action</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($enrollments as $e): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($e['first_name'] . ' ' . $e['last_name']); ?></td>
                            <td><?php echo htmlspecialchars($e['course_title']); ?></td>
                            <td><?php echo htmlspecialchars($e['enrollment_date']); ?></td>
                            <td><?php echo htmlspecialchars($e['status']); ?></td>
                            <td>
                                <form method="post" class="d-inline">
                                    <input type="hidden" name="enrollment_id" value="<?php echo (int)$e['id']; ?>">
                                    <button name="action" value="set_active" class="btn btn-sm btn-outline-primary">Set Active</button>
                                </form>
                                <form method="post" class="d-inline ms-1">
                                    <input type="hidden" name="enrollment_id" value="<?php echo (int)$e['id']; ?>">
                                    <button name="action" value="set_completed" class="btn btn-sm btn-outline-success">Complete</button>
                                </form>
                                <form method="post" class="d-inline ms-1" onsubmit="return confirm('Revoke enrollment?');">
                                    <input type="hidden" name="enrollment_id" value="<?php echo (int)$e['id']; ?>">
                                    <button name="action" value="revoke" class="btn btn-sm btn-outline-danger">Revoke</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php';
