@csrf
<div class="row g-3">
    <div class="col-md-5"><label class="form-label">Subject Name <span class="text-danger">*</span></label>
        <input type="text" name="name" value="{{ old('name', $subject->name) }}" class="form-control @error('name') is-invalid @enderror" required>
        @error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror</div>
    <div class="col-md-3"><label class="form-label">Code</label>
        <input type="text" name="code" value="{{ old('code', $subject->code) }}" class="form-control"></div>
    <div class="col-md-2 d-flex align-items-end"><div class="form-check"><input type="checkbox" name="is_elective" value="1" id="is_elective" class="form-check-input" @checked(old('is_elective', $subject->is_elective))><label for="is_elective" class="form-check-label">Elective</label></div></div>
    <div class="col-md-2 d-flex align-items-end"><div class="form-check"><input type="checkbox" name="is_active" value="1" id="is_active" class="form-check-input" @checked(old('is_active', $subject->is_active ?? true))><label for="is_active" class="form-check-label">Active</label></div></div>

    <div class="col-12">
        <label class="form-label">Assign to Classes <span class="text-danger">*</span></label>
        @error('class_ids')<div class="text-danger small mb-1">{{ $message }}</div>@enderror
        <div class="d-flex align-items-center gap-2 mb-2">
            <button type="button" class="btn btn-sm btn-light border" id="selAllClasses">Select all</button>
            <button type="button" class="btn btn-sm btn-light border" id="clrAllClasses">Clear</button>
            <span class="text-muted small">Different classes can have different subjects — pick where this subject is taught.</span>
        </div>
        <div class="row g-2">
            @php $sel = collect(old('class_ids', $selectedClasses ?? [])); @endphp
            @foreach($classes as $class)
                <div class="col-md-3 col-sm-4">
                    <div class="form-check">
                        <input type="checkbox" name="class_ids[]" value="{{ $class->id }}" id="cls{{ $class->id }}" class="form-check-input cls-chk" @checked($sel->contains($class->id))>
                        <label for="cls{{ $class->id }}" class="form-check-label">{{ $class->name }}</label>
                    </div>
                </div>
            @endforeach
        </div>
    </div>
</div>
<div class="mt-3 d-flex gap-2">
    <button class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>{{ $submitLabel ?? 'Save' }}</button>
    <a href="{{ route('subjects.index') }}" class="btn btn-light border">Cancel</a>
</div>

@push('scripts')
<script>
    document.getElementById('selAllClasses')?.addEventListener('click', () => document.querySelectorAll('.cls-chk').forEach(c => c.checked = true));
    document.getElementById('clrAllClasses')?.addEventListener('click', () => document.querySelectorAll('.cls-chk').forEach(c => c.checked = false));
</script>
@endpush
