@extends('layouts.app')

@section('title', 'ক্লাস রুটিন')

@section('content')
<div class="container-fluid">
    <!-- Header -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="card card-primary card-outline">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fa fa-calendar-alt"></i> ক্লাস রুটিন ম্যানেজমেন্ট</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>শ্রেণি <span class="text-danger">*</span></label>
                                <select id="classSelect" class="form-control">
                                    <option value="">শ্রেণি নির্বাচন করুন</option>
                                    @foreach($classes as $class)
                                    <option value="{{ $class->id }}" data-section="{{ $class->section }}">
                                        {{ $class->class_name_bn }} @if($class->section)({{ $class->section }})@endif
                                    </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>শাখা</label>
                                <input type="text" id="sectionInput" class="form-control" placeholder="যেমন: A">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <button type="button" class="btn btn-info btn-block" id="loadRoutine" style="margin-top: 32px;">
                                <i class="fa fa-search"></i> রুটিন দেখুন
                            </button>
                        </div>
                    </div>

                    <div class="row mt-3" id="actionButtons" style="display: none;">
                        <div class="col-12 text-center">
                            <button type="button" class="btn btn-success" data-toggle="modal" data-target="#addPeriodModal">
                                <i class="fa fa-plus-circle"></i> নতুন পিরিয়ড যোগ করুন
                            </button>
                            <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#generateModal">
                                <i class="fa fa-cog"></i> অটো জেনারেট
                            </button>
                            <button type="button" class="btn btn-info" id="printRoutine">
                                <i class="fa fa-print"></i> প্রিন্ট
                            </button>
                            <button type="button" class="btn btn-primary" id="exportPdf">
                                <i class="fa fa-file-pdf"></i> PDF
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Routine Display -->
    <div class="row" id="routineContainer" style="display: none;">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0" id="routineTitle"></h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover" id="routineTable">
                            <thead class="bg-secondary text-white">
                                <tr>
                                    <th style="width: 100px;">পিরিয়ড</th>
                                    <th style="width: 120px;">সময়</th>
                                    @foreach($days as $day)
                                    <th>{{ $day }}</th>
                                    @endforeach
                                    <th style="width: 80px;">একশন</th>
                                </tr>
                            </thead>
                            <tbody id="routineBody">
                                <!-- Dynamic content will be loaded here -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Period Modal -->
<div class="modal fade" id="addPeriodModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">নতুন পিরিয়ড যোগ করুন</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form action="{{ route('routines.store') }}" method="POST">
                @csrf
                <input type="hidden" name="class_id" id="modal_class_id">
                <input type="hidden" name="section" id="modal_section">
                
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>দিন <span class="text-danger">*</span></label>
                                <select name="day_of_week" class="form-control" required>
                                    @foreach($days as $key => $day)
                                    <option value="{{ $key }}">{{ $day }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>পিরিয়ড <span class="text-danger">*</span></label>
                                <select name="period" class="form-control" required>
                                    @foreach($periods as $key => $period)
                                    <option value="{{ $key }}">{{ $period }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>শুরুর সময় <span class="text-danger">*</span></label>
                                <input type="time" name="start_time" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>শেষের সময় <span class="text-danger">*</span></label>
                                <input type="time" name="end_time" class="form-control" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox" class="custom-control-input" id="isBreak" name="is_break" value="1">
                            <label class="custom-control-label" for="isBreak">এটি কি বিরতির সময়?</label>
                        </div>
                    </div>
                    
                    <div id="classPeriodFields">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>বিষয়</label>
                                    <input type="text" name="subject" class="form-control" placeholder="বাংলা ১ম পত্র">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>শিক্ষক</label>
                                    <select name="teacher_id" class="form-control">
                                        <option value="">শিক্ষক নির্বাচন করুন</option>
                                        @foreach($teachers as $teacher)
                                        <option value="{{ $teacher->id }}">{{ $teacher->name_bn }} ({{ $teacher->subject_specialization }})</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>রুম নম্বর</label>
                                    <input type="text" name="room_number" class="form-control" placeholder="১০১">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div id="breakFields" style="display: none;">
                        <div class="form-group">
                            <label>বিরতির নাম</label>
                            <input type="text" name="break_name" class="form-control" placeholder="দুপুরের বিরতি">
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">বাতিল</button>
                    <button type="submit" class="btn btn-success">সংরক্ষণ করুন</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Generate Template Modal -->
<div class="modal fade" id="generateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">রুটিন টেমপ্লেট জেনারেট</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form action="{{ route('routines.generate-template') }}" method="GET">
                <input type="hidden" name="class_id" id="gen_class_id">
                <input type="hidden" name="section" id="gen_section">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label>স্কুল শুরুর সময় <span class="text-danger">*</span></label>
                        <input type="time" name="start_time" class="form-control" value="09:00" required>
                    </div>
                    
                    <div class="form-group">
                        <label>স্কুল শেষের সময় <span class="text-danger">*</span></label>
                        <input type="time" name="end_time" class="form-control" value="16:00" required>
                    </div>
                    
                    <div class="form-group">
                        <label>প্রতি পিরিয়ডের সময় (মিনিট) <span class="text-danger">*</span></label>
                        <input type="number" name="period_duration" class="form-control" value="45" min="30" max="60" required>
                    </div>
                    
                    <div class="form-group">
                        <label>কত তম পিরিয়ডের পর বিরতি? <span class="text-danger">*</span></label>
                        <input type="number" name="break_after" class="form-control" value="3" min="1" max="4" required>
                    </div>
                    
                    <div class="form-group">
                        <label>বিরতির সময় (মিনিট) <span class="text-danger">*</span></label>
                        <input type="number" name="break_duration" class="form-control" value="30" min="10" max="30" required>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">বাতিল</button>
                    <button type="submit" class="btn btn-warning">টেমপ্লেট তৈরি করুন</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Period Modal -->
<div class="modal fade" id="editPeriodModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title">পিরিয়ড এডিট করুন</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body" id="editFormContainer">
                <!-- Dynamic edit form will be loaded here -->
            </div>
        </div>
    </div>
</div>

@section('scripts')
<script>
    $(document).ready(function() {
        // Toggle break/class fields
        $('#isBreak').change(function() {
            if ($(this).is(':checked')) {
                $('#classPeriodFields').hide();
                $('#breakFields').show();
            } else {
                $('#classPeriodFields').show();
                $('#breakFields').hide();
            }
        });

        // Load routine
        $('#loadRoutine').click(function() {
            var classId = $('#classSelect').val();
            var section = $('#sectionInput').val() || 'A';
            
            if (!classId) {
                alert('দয়া করে শ্রেণি নির্বাচন করুন');
                return;
            }

            // Set modal values
            $('#modal_class_id, #gen_class_id').val(classId);
            $('#modal_section, #gen_section').val(section);
            
            // Get class name
            var className = $('#classSelect option:selected').text();
            $('#routineTitle').text(className + ' - ' + section + ' শাখার রুটিন');
            
            // Load routine data
            $.ajax({
                url: '{{ route("routines.get") }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    class_id: classId,
                    section: section
                },
                success: function(response) {
                    renderRoutine(response);
                    $('#routineContainer, #actionButtons').show();
                },
                error: function() {
                    alert('রুটিন লোড করতে সমস্যা হয়েছে');
                }
            });
        });

        // Render routine table
        function renderRoutine(data) {
            var html = '';
            var days = ['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
            var periods = @json($periods);
            
            for (var p = 1; p <= 8; p++) {
                html += '<tr>';
                html += '<td class="text-center font-weight-bold">' + periods[p] + '</td>';
                html += '<td class="text-center" id="time_' + p + '">--:--</td>';
                
                for (var d = 0; d < days.length; d++) {
                    var day = days[d];
                    var cellData = '';
                    var hasData = false;
                    
                    if (data[day]) {
                        data[day].forEach(function(item) {
                            if (item.period == p) {
                                hasData = true;
                                if (item.is_break) {
                                    cellData = '<div class="break-cell">' +
                                             '<span class="badge badge-warning p-2">বিরতি</span><br>' +
                                             '<small>' + (item.break_name || 'বিরতি') + '</small>' +
                                             '</div>';
                                } else {
                                    cellData = '<div class="class-cell">' +
                                             '<strong>' + item.subject + '</strong><br>' +
                                             '<small>' + (item.teacher ? item.teacher.name_bn : '') + '</small><br>' +
                                             '<span class="badge badge-info">Room ' + (item.room_number || '-') + '</span>' +
                                             '</div>';
                                }
                                
                                // Set time for first occurrence
                                if (d == 0) {
                                    $('#time_' + p).html(item.start_time.substr(0,5) + ' - ' + item.end_time.substr(0,5));
                                }
                            }
                        });
                    }
                    
                    if (!hasData) {
                        cellData = '<div class="empty-cell text-muted">--</div>';
                    }
                    
                    html += '<td class="text-center">' + cellData + 
                           '<button class="btn btn-sm btn-link edit-period" data-day="' + day + '" data-period="' + p + '">' +
                           '<i class="fa fa-edit"></i></button></td>';
                }
                
                html += '<td class="text-center">' +
                       '<button class="btn btn-sm btn-danger delete-period" data-period="' + p + '">' +
                       '<i class="fa fa-trash"></i></button></td>';
                html += '</tr>';
            }
            
            $('#routineBody').html(html);
        }

        // Edit period
        $(document).on('click', '.edit-period', function() {
            var day = $(this).data('day');
            var period = $(this).data('period');
            var classId = $('#classSelect').val();
            var section = $('#sectionInput').val() || 'A';
            
            $.ajax({
    url: '{{ url("/routines/edit") }}',
    type: 'GET',
    data: {
        class_id: classId,
        section: section,
        day: day,
        period: period
    },
    success: function(response) {
        $('#editFormContainer').html(response);
        $('#editPeriodModal').modal('show');
    },
    error: function() {
        alert('পিরিয়ড তথ্য লোড করতে সমস্যা হয়েছে');
    }
});

        // Delete period
        $(document).on('click', '.delete-period', function() {
            if (!confirm('এই পিরিয়ড মুছে ফেলতে চান?')) return;
            
            var period = $(this).data('period');
            var classId = $('#classSelect').val();
            var section = $('#sectionInput').val() || 'A';
            
            $.ajax({
                url: '{{ route("routines.destroy", "") }}/' + period,
                type: 'DELETE',
                data: {
                    _token: '{{ csrf_token() }}',
                    class_id: classId,
                    section: section
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.message);
                        $('#loadRoutine').click();
                    }
                }
            });
        });

        // Print routine
        $('#printRoutine').click(function() {
            var classId = $('#classSelect').val();
            var section = $('#sectionInput').val() || 'A';
            window.open('{{ url("routines/print") }}/' + classId + '/' + section, '_blank');
        });

        // Export PDF
        $('#exportPdf').click(function() {
            var classId = $('#classSelect').val();
            var section = $('#sectionInput').val() || 'A';
            window.open('{{ url("routines/pdf") }}/' + classId + '/' + section, '_blank');
        });
    });
</script>

<style>
.class-cell {
    padding: 5px;
    background-color: #e8f4f8;
    border-radius: 5px;
    margin: 2px;
}

.break-cell {
    padding: 5px;
    background-color: #fff3cd;
    border-radius: 5px;
    margin: 2px;
}

.empty-cell {
    padding: 15px;
}

.edit-period {
    opacity: 0.3;
    transition: opacity 0.3s;
}

td:hover .edit-period {
    opacity: 1;
}
</style>
@endsection
@endsection