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

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

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

$courseId = (int)($_GET['course_id'] ?? 0);
if (!$courseId) redirect('my_courses.php');

$course = $courseModel->getById($courseId);
if (!$course || (int)$course['instructor_id'] !== (int)$user['id']) {
    setFlashMessage('error', 'Course not found or permission denied.');
    redirect('my_courses.php');
}

$errors = [];

// Handle add/edit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['action'])) {
    $action = $_POST['action'];
    if ($action === 'add') {
        $title = trim($_POST['title'] ?? '');
        $desc = trim($_POST['description'] ?? '');
        if (!$title) $errors[] = 'Title is required.';
        if (empty($errors)) {
            $courseModel->addModule($courseId, ['title' => $title, 'description' => $desc]);
            setFlashMessage('success', 'Module added.');
            header('Location: ' . APP_URL . '/lms/course_modules.php?course_id=' . $courseId);
            exit;
        }
    } elseif ($action === 'update' && !empty($_POST['module_id'])) {
        $mid = (int)$_POST['module_id'];
        $title = trim($_POST['title'] ?? '');
        $desc = trim($_POST['description'] ?? '');
        if (!$title) $errors[] = 'Title is required.';
        if (empty($errors)) {
            $courseModel->updateModule($mid, ['title' => $title, 'description' => $desc]);
            setFlashMessage('success', 'Module updated.');
            header('Location: ' . APP_URL . '/lms/course_modules.php?course_id=' . $courseId);
            exit;
        }
    } elseif ($action === 'delete' && !empty($_POST['module_id'])) {
        $mid = (int)$_POST['module_id'];
        $courseModel->deleteModule($mid);
        setFlashMessage('success', 'Module deleted.');
        header('Location: ' . APP_URL . '/lms/course_modules.php?course_id=' . $courseId);
        exit;
    }
}

$modules = $courseModel->getModules($courseId);

$pageTitle = 'Course Modules - ' . htmlspecialchars($course['title']);
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h4 mb-0">Course Modules</h1>
        <p class="text-muted mb-0">Manage modules for <?php echo htmlspecialchars($course['title']); ?></p>
    </div>
    <div>
        <a href="<?php echo APP_URL; ?>/lms/courses_edit.php?id=<?php echo (int)$courseId; ?>" class="btn btn-outline-secondary">Back to Course</a>
    </div>
</div>

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

<div class="row g-4">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header"><h6 class="mb-0">Modules</h6></div>
            <div class="card-body">
                <?php if (empty($modules)): ?>
                    <p class="text-muted">No modules yet.</p>
                <?php else: ?>
                    <ul class="list-group">
                        <?php foreach ($modules as $m): ?>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                <div>
                                    <strong><?php echo htmlspecialchars($m['title']); ?></strong>
                                    <div class="small text-muted"><?php echo htmlspecialchars(substr($m['description'] ?? '', 0, 120)); ?></div>
                                </div>
                                <div>
                                    <a href="<?php echo APP_URL; ?>/lms/lessons_edit.php?module_id=<?php echo (int)$m['id']; ?>&course_id=<?php echo (int)$courseId; ?>" class="btn btn-sm btn-outline-primary">Lessons</a>
                                    <button class="btn btn-sm btn-outline-secondary ms-1" onclick="openEdit(<?php echo (int)$m['id']; ?>, '<?php echo addslashes(htmlspecialchars($m['title'])); ?>', '<?php echo addslashes(htmlspecialchars($m['description'])); ?>')">Edit</button>
                                    <form method="post" class="d-inline ms-1" onsubmit="return confirm('Delete module?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="module_id" value="<?php echo (int)$m['id']; ?>">
                                        <button class="btn btn-sm btn-outline-danger">Delete</button>
                                    </form>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card">
            <div class="card-header"><h6 class="mb-0">Add Module</h6></div>
            <div class="card-body">
                <form method="post">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">Title</label>
                        <input type="text" name="title" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="4"></textarea>
                    </div>
                    <button class="btn btn-primary">Add Module</button>
                </form>

                <hr>
                <div id="editForm" style="display:none;">
                    <h6>Edit Module</h6>
                    <form method="post">
                        <input type="hidden" name="action" value="update">
                        <input type="hidden" name="module_id" id="edit_module_id" value="">
                        <div class="mb-3">
                            <label class="form-label">Title</label>
                            <input type="text" name="title" id="edit_title" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea name="description" id="edit_description" class="form-control" rows="4"></textarea>
                        </div>
                        <button class="btn btn-primary">Save</button>
                        <button type="button" class="btn btn-outline-secondary ms-2" onclick="closeEdit()">Cancel</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function openEdit(id, title, desc) {
    document.getElementById('editForm').style.display = 'block';
    document.getElementById('edit_module_id').value = id;
    document.getElementById('edit_title').value = title;
    document.getElementById('edit_description').value = desc;
}
function closeEdit() {
    document.getElementById('editForm').style.display = 'none';
}
</script>

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