@extends('admin.layouts.app')

@push('libraries_top')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">
@endpush

@section('content')
    <section class="section">
        <div class="section-header">
            <h1>Manage Lecture Students</h1>
            <div class="section-header-breadcrumb">
                <div class="breadcrumb-item active"><a href="/admin">Dashboard</a></div>
                <div class="breadcrumb-item">Lecture Students</div>
            </div>
        </div>
    </section>

    <div class="section-body">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h4>
                            Lecture: 
                            <span class="text-primary">
                                {{ $lecture->title ?? 'Untitled' }}
                            </span>
                            <small class="text-muted">({{ ucfirst(str_replace('_', ' ', $lectureType)) }})</small>
                        </h4>
                    </div>
                    <div class="card-body">
                        <!-- Flash Messages -->
                        @if(session('success'))
                            <div class="alert alert-success alert-dismissible show fade">
                                <div class="alert-body">
                                    <button class="close" data-dismiss="alert">
                                        <span>&times;</span>
                                    </button>
                                    {{ session('success') }}
                                </div>
                            </div>
                        @endif

                        @if(session('error'))
                            <div class="alert alert-danger alert-dismissible show fade">
                                <div class="alert-body">
                                    <button class="close" data-dismiss="alert">
                                        <span>&times;</span>
                                    </button>
                                    {{ session('error') }}
                                </div>
                            </div>
                        @endif

                        <!-- Assign Student Form -->
                        <div class="card card-primary mb-4">
                            <div class="card-header">
                                <h4>Assign Student to Lecture</h4>
                            </div>
                            <div class="card-body">
                                <form id="assignStudentForm" method="POST" action="/admin/lectures/{{ $lecture->id }}/students/assign">
                                    @csrf
                                    <input type="hidden" name="lecture_type" value="{{ $lectureType }}">
                                    
                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="form-group">
                                                <label>Select User</label>
                                                <select name="user_id" id="userSelect" class="form-control select2" required>
                                                    <option value="">Choose a user...</option>
                                                    @foreach($allUsers as $user)
                                                        <option value="{{ $user->id }}">
                                                            {{ $user->full_name }} ({{ $user->email }}) - {{ ucfirst($user->role_name) }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>&nbsp;</label>
                                                <button type="submit" class="btn btn-primary btn-block">
                                                    <i class="fas fa-plus"></i> Assign Student
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Assigned Students List -->
                        <div class="card">
                            <div class="card-header">
                                <h4>Assigned Students ({{ $assignedUsers->count() }})</h4>
                            </div>
                            <div class="card-body">
                                @if($assignedUsers->count() > 0)
                                    <div class="table-responsive">
                                        <table class="table table-striped table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>Full Name</th>
                                                    <th>Email</th>
                                                    <th>Role</th>
                                                    <th>Assigned At</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach($assignedUsers as $index => $user)
                                                    <tr id="user-row-{{ $user->id }}">
                                                        <td>{{ $index + 1 }}</td>
                                                        <td>{{ $user->full_name }}</td>
                                                        <td>{{ $user->email }}</td>
                                                        <td>
                                                            <span class="badge badge-info">{{ ucfirst($user->role_name) }}</span>
                                                        </td>
                                                        <td>{{ dateTimeFormat($user->created_at) }}</td>
                                                        <td>
                                                            <button 
                                                                class="btn btn-sm btn-danger remove-student-btn" 
                                                                data-user-id="{{ $user->id }}"
                                                                data-user-name="{{ $user->full_name }}"
                                                                data-lecture-id="{{ $lecture->id }}"
                                                            >
                                                                <i class="fas fa-trash"></i> Remove
                                                            </button>
                                                        </td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                @else
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle"></i> No students assigned to this lecture yet.
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts_bottom')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    $(document).ready(function() {
        // Initialize Select2 for searchable dropdown
        $('#userSelect').select2({
            placeholder: 'Search and select a user...',
            allowClear: true,
            width: '100%'
        });

        // Handle assign form submission
        $('#assignStudentForm').on('submit', function(e) {
            e.preventDefault();
            
            const form = $(this);
            const submitBtn = form.find('button[type="submit"]');
            const originalText = submitBtn.html();
            
            submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Assigning...');
            
            $.ajax({
                url: form.attr('action'),
                method: 'POST',
                data: form.serialize(),
                success: function(response) {
                    if (response.code === 200) {
                        // Show success message
                        showFlashMessage('success', response.msg);
                        
                        // Reload page to show updated list
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    } else {
                        showFlashMessage('error', response.msg || 'An error occurred');
                        submitBtn.prop('disabled', false).html(originalText);
                    }
                },
                error: function(xhr) {
                    const message = xhr.responseJSON?.msg || 'An error occurred while assigning the student';
                    showFlashMessage('error', message);
                    submitBtn.prop('disabled', false).html(originalText);
                }
            });
        });

        // Handle remove student
        $(document).on('click', '.remove-student-btn', function(e) {
            e.preventDefault();
            
            const btn = $(this);
            const userId = btn.data('user-id');
            const userName = btn.data('user-name');
            const lectureId = btn.data('lecture-id');
            
            if (!confirm(`Are you sure you want to remove "${userName}" from this lecture?`)) {
                return;
            }
            
            btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Removing...');
            
            $.ajax({
                url: `/admin/lectures/${lectureId}/students/${userId}`,
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.code === 200) {
                        showFlashMessage('success', response.msg);
                        
                        // Remove row from table
                        $(`#user-row-${userId}`).fadeOut(function() {
                            $(this).remove();
                            
                            // If no more rows, reload to show empty message
                            if ($('tbody tr').length === 0) {
                                setTimeout(function() {
                                    location.reload();
                                }, 1000);
                            }
                        });
                    } else {
                        showFlashMessage('error', response.msg || 'An error occurred');
                        btn.prop('disabled', false).html('<i class="fas fa-trash"></i> Remove');
                    }
                },
                error: function(xhr) {
                    const message = xhr.responseJSON?.msg || 'An error occurred while removing the student';
                    showFlashMessage('error', message);
                    btn.prop('disabled', false).html('<i class="fas fa-trash"></i> Remove');
                }
            });
        });

        // Flash message helper
        function showFlashMessage(type, message) {
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            const icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
            
            const alert = `
                <div class="alert ${alertClass} alert-dismissible show fade">
                    <div class="alert-body">
                        <button class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                        <i class="fas ${icon}"></i> ${message}
                    </div>
                </div>
            `;
            
            $('.card-body').prepend(alert);
            
            // Auto-dismiss after 5 seconds
            setTimeout(function() {
                $('.alert').fadeOut(function() {
                    $(this).remove();
                });
            }, 5000);
        }
    });
</script>
@endpush

