@extends('layouts.app')

@section('content')
<div class="container">
    <div class="card border-success shadow-sm">
        <div class="card-header bg-success text-white">
            <strong>Course Registration</strong>
        </div>
        <div class="card-body">
            @if(session('success'))
                <div class="alert alert-success">{{ session('success') }}</div>
            @endif

            @if ($errors->any())
                <div class="alert alert-danger">
                    <strong>Validation Error:</strong> {{ $errors->first() }}
                </div>
            @endif

            <form method="POST" action="{{ route('student.registration.store') }}">
                @csrf

                <div class="form-group mb-3">
                    <label for="semester">Select Level & Semester</label>
                    <select name="semester" id="semester" class="form-select" required onchange="showCourses(this.value)">
                        <option value="">-- Choose Level & Semester --</option>
                        @foreach ($courses->keys() as $group)
                            <option value="{{ $group }}">{{ $group }}</option>
                        @endforeach
                    </select>
                </div>

                <div id="course-container" class="mt-3"></div>

                <button type="submit" class="btn btn-success mt-3">Submit Registration</button>
            </form>
        </div>
    </div>
</div>

<script>
    const allCourses = @json($courses);

    function showCourses(selectedGroup) {
        const container = document.getElementById('course-container');
        container.innerHTML = '';

        if (!selectedGroup || !allCourses[selectedGroup]) {
            return;
        }

        const courses = allCourses[selectedGroup];

        let html = `
            <h5 class="text-primary mb-2">${selectedGroup}</h5>
            <div class="table-responsive">
                <table class="table table-striped table-bordered">
                    <thead class="table-secondary">
                        <tr>
                            <th>Course Code</th>
                            <th>Course Description</th>
                            <th>Credits</th>
                            <th>Select</th>
                        </tr>
                    </thead>
                    <tbody>
        `;

        courses.forEach(course => {
            html += `
                <tr>
                    <td>${course.course_code}</td>
                    <td>${course.course_description}</td>
                    <td>${course.credits}</td>
                    <td><input type="checkbox" name="courses[]" value="${course.course_code}"></td>
                </tr>
            `;
        });

        html += `
                    </tbody>
                </table>
            </div>
        `;

        container.innerHTML = html;
    }
</script>
@endsection
