@extends('layouts.master')

@section('content')
    <style>
        .image-uploader {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative; /* Add position relative */
        }

        .image-uploader__label {
            display: flex;
            flex-direction: column;
            align-items: center;
            cursor: pointer;
            position: relative; /* Add position relative */
        }

        .image-uploader__icon-overlay {
            position: absolute;
            top: 50%; /* Align vertically centered */
            left: 50%; /* Align horizontally centered */
            transform: translate(-50%, -50%); /* Center the icon */
            width: 100%;
            height: calc(100%); /* Height equal to parent minus icon height */
            background-color: rgba(0, 0, 0, 0.2); /* Transparent black background */
            border-radius: 50%; /* Rounded border */
            display: flex;
            justify-content: center;
            align-items: center;
            opacity: 0.4;
        }

        .image-uploader__icon-overlay i {
            color: #ffffff; /* Icon color */
            font-size: 24px; /* Icon size */
        }

        /* Your existing styles */
        .image-uploader__preview {
            overflow: hidden;
        }

        .image-uploader__input {
            display: none;
        }


    </style>
    <div class="card std__form">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between border-bottom">
            <h6 class="m-0 table__top__txt">Edit Student Profile</h6>
            <div class="m-0 float-right">
                <a class="btn btn-sm btn-light-blue" href="{{ route('student_info.index') }}">View All</a>
            </div>
        </div>
        <div class="card-body m-3">
            <form action="{{ route('student_info.update',$studentInfo->id) }}" method="POST"
                  enctype="multipart/form-data">
                @csrf
                @method('Put')
                <div class="row py-2 mb-0 form__head">
                    Personal information
                </div>
                <div class="row p-2 form__body">
                    <div class="col-md-9">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="student_id_no">
                                        Student ID
                                        <i class="fas fa-info-circle text-info"
                                           data-container="body"
                                           data-toggle="popover"
                                           data-placement="right"
                                           data-html="true"
                                           data-content="Student ID is automatically generated based on the 'Student Id Year' settings. You can change it from <a href='{{route('setting.index')}}' target='_blank'><strong>Settings</strong></a> by looking 'Student Id Year'">
                                        </i>
                                    </label>
                                    <input type="text" class="form-control" name="student_id_no" id="student_id_no"
                                           value="{{$studentInfo->student_id_no}}" readonly required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="first_name">First name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="first_name" id="first_name"
                                           value="{{$studentInfo->first_name}}" placeholder="First Name" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="last_name">Last name </label>
                                    <input type="text" class="form-control" name="last_name"
                                           value="{{$studentInfo->last_name}}">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="gender">Gender <span class="text-danger">*</span></label>
                                    {{ generateDropdown($genderOptions, 'class="form-control" name="gender" required', $studentInfo->gender, 'Select Option') }}
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="blood_group">Blood group </label>
                                    {{ generateDropdown($bloodGroupOptions, 'class="form-control" name="blood_group"', $studentInfo->blood_group, 'Select Option') }}
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="religion">Religion <span class="text-danger">*</span></label>
                                    {{ generateDropdown($religionOptions, 'class="form-control" name="religion" required', $studentInfo->religion, 'Select Option') }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="image-uploader">
                            <label for="first_name">Profile image </label>
                            <label for="imageFile" class="image-uploader__label">
                                <!-- Icon overlay with transparent background -->
                                <div class="image-uploader__icon-overlay">
                                    <i class="fas fa-cloud-upload-alt"></i>
                                    <!-- Assuming you're using Font Awesome for icons -->
                                </div>
                                <!-- Preview image -->
                                @php
                                    $student_image = $studentInfo->profile_image ? $studentInfo->profile_image : 'graduated_student.png';
                                @endphp
                                <img src="{{ asset("uploads/student/$student_image") }}" alt="Preview image"
                                     class="image-uploader__preview-image img-thumbnail rounded-circle p-1"
                                     style="width: 140px; height: 140px;">
                                <!-- File input -->
                                <input type="file" name="profile_image" class="image-uploader__input" id="imageFile"
                                       name="imageFile">
                            </label>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="date_of_birth">Date of birth <span class="text-danger">*</span> </label>
                            <input type="text" class="form-control date360" name="date_of_birth"
                                   value="{{$studentInfo->date_of_birth}}" placeholder="Date of Birth" required>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="birth_certi_no">Birth certificate no </label>
                            <input type="text" class="form-control" name="birth_certi_no"
                                   value="{{$studentInfo->birth_certi_no}}" placeholder="Birth Certificate No">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="mobile_no"><b>Mobile number (For SMS)</b> <span class="text-danger">*</span> </label>
                            <input type="text" class="form-control" name="mobile_no" value="{{$studentInfo->mobile_no}}"
                                   placeholder="Mobile Number" required>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="email">Email </label>
                            <input type="text" class="form-control" name="email" value="{{$studentInfo->email}}"
                                   placeholder="Email">
                        </div>
                    </div>
                </div>

                <div class="row py-2 mb-0 form__head">
                    Academic information
                </div>
                <div class="form__body">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="branch_id">Branch <span class="text-danger">*</span> </label>
                                {{ generateDropdown($branches, 'class="form-control branch_id" id="branch_id" name="branch_id" required disabled', $studentInfo->branch_id, 'Select Option') }}
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="shift_id">Shift <span class="text-danger">*</span> </label>
                                {{ generateDropdown($shifts, 'class="form-control shift_id" id="shift_id" name="shift_id" required',$studentInfo->shift_id, 'Select Option') }}
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="student_class_id">Class <span class="text-danger">*</span> </label>
                                {{ generateDropdown($studentClasses, 'class="form-control select2 student_class" id="student_class" name="student_class_id" required', $studentInfo->student_class_id, 'Select Option') }}
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="section_id">Section </label>
                                {{ generateDropdown([], 'class="form-control section_id" id="section_id" name="section_id" ', $studentInfo->section_id, 'Select Option') }}

                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="group_id">Group </label>
                                {{ generateDropdown($groups, 'class="form-control group_id" id="group_id" name="group_id"', $studentInfo->group_id, 'Select Option') }}
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="admission_roll">Admission Roll </label>
                                <input type="text" class="form-control" name="admission_roll"
                                    value="{{$studentInfo->admission_roll}}">
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="class_roll">Class Roll <span class="text-danger">*</span> </label>
                                <input type="text" class="form-control" name="class_roll"
                                    value="{{$studentInfo->class_roll}}" placeholder="Class Roll" required>
                            </div>
                        </div>
                    </div>

                    {{-- //hsc subjects --}}

                    <div class="row hsc-subjects">
                        <div class="col-md-4">
                            <div class="form-group">
                                <h5>Main/Compulsory Subjects</h5>
                                <div class="controls">
                                    @if (!empty($compulsory_subjects))
                                        @foreach ($compulsory_subjects as $key=>$compulsorySubject)
                                            <fieldset>
                                                <input type="checkbox" id="checkbox_{{$key}}" value="{{ $compulsorySubject->subject_id ?? '' }}" name="{{ $compulsorySubject->subject->subject_name ?? '' }}" checked="" disabled="">
                                                <label for="checkbox_{{$key}}">{{ $compulsorySubject->subject->subject_name ?? '' }}</label>
                                            </fieldset>
                                        @endforeach
                                    @endif
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <h5>Group Compulsory Subjects</h5>
                                @if (!empty($subjects))
                                    {{-- <select name="elective_subjects[]" multiple class="form-control select2" >
                                        <option value="">-Select-</option>
                                        @foreach ($subjects as $key => $subject)
                                            <option value="{{ $subject->subject_id }}">{{ $subject->subject->subject_name }}</option>
                                        @endforeach
                                        </select> --}}

                                    <select name="elective_subjects[]" multiple class="form-control select2">
                                        <option value="">-Select-</option>
                                        @foreach ($subjects as $key => $subject)
                                            <option value="{{ $subject->subject_id }}"
                                                {{ in_array($subject->subject_id, $studentElectiveSubjects ?? []) ? 'selected' : '' }}>
                                                {{ $subject->subject->subject_name }}
                                            </option>
                                        @endforeach
                                    </select>
                                @endif
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <h5>Additional/4th Subjects</h5>

                                <div class="controls" id="optional-section">
                                    @if (!empty($subjects))
                                    <select name="optional_subject" class="form-control select2">
                                        <option value="">-Select-</option>
                                        @foreach ($subjects as $key => $subject)
                                            <option value="{{ $subject->subject_id }}"
                                                {{ isset($optionalSubject) && $optionalSubject->subject_id == $subject->subject_id ? 'selected' : '' }}>
                                                {{ $subject->subject->subject_name }}
                                            </option>
                                        @endforeach
                                    </select>

                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
                <div class="row py-2 mb-0 form__head">
                    Parent information
                </div>
                <div class="row p-2 form__body">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="father_name">Father's name <span class="text-danger">*</span> </label>
                            <input type="text" class="form-control" name="father_name"
                                   value="{{$studentInfo->father_name}}" placeholder="Father Name" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="father_occupation">Father's occupation</label>
                            {{ generateDropdown($occupations, 'class="form-control select2 father_occupation" id="father_occupation" name="father_occupation" ', $studentInfo->father_occupation, 'Select Option') }}
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="father_mobile">Father's mobile </label>
                            <input type="tel" class="form-control" name="father_mobile"
                                   value="{{$studentInfo->father_mobile}}" placeholder="Father Mobile No">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="mother_name">Mother's name</label>
                            <input type="text" class="form-control" name="mother_name"
                                   value="{{$studentInfo->mother_name}}" placeholder="Mother Name">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="mother_occupation">Mother's occupation</label>
                            {{ generateDropdown($occupations, 'class="form-control select2 mother_occupation" id="mother_occupation" name="mother_occupation" ', $studentInfo->mother_occupation, 'Select Option') }}
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="mother_mobile">Mother's mobile </label>
                            <input type="tel" class="form-control" name="mother_mobile"
                                   value="{{$studentInfo->mother_mobile}}" placeholder="Mother Mobile No">
                        </div>
                    </div>
                </div>
                <div class="row py-2 mb-0 form__head">
                    Address
                </div>
                <div class="row p-2 form__body">
                    {{-- Present Address Start --}}
                    <label class="ml-2" for="present_address">Present address</label> 
                    <div class="row col-md-12 mt-2">
                        <x-location-dropdown
                            :selected-division="$studentInfo->present_division_id"
                            :selected-district="$studentInfo->present_district_id"
                            :selected-upazila="$studentInfo->present_upazila_id"
                            :selected-union="$studentInfo->present_union_id"
                            container-class=""
                            group-class="form-group col-md-3"
                            label-class="form-label"
                            select-class="form-control select2"
                            prefix="present"
                        />

                        <div class="col-md-12">
                            <div class="form-group">
                                <textarea class="form-control" name="present_address" id="present_address"
                                placeholder="Present Address">{{$studentInfo->present_address}}</textarea>
                            </div>
                        </div>
                    </div>
                    {{-- Present Address End --}}

                    {{-- Permanent Address Start --}}
                    <label class="ml-2 mt-4" for="permanent_address">Permanent address</label>
                    <div class="mx-2 mt-4">
                        (<input class="mx-2" type="checkbox" id="copyAddress" />
                        <label for="copyAddress"> Same as Present Address</label>)
                    </div>
                    <div class="row col-md-12 mt-2">
                        <x-location-dropdown
                            :selected-division="$studentInfo->permanent_division_id"
                            :selected-district="$studentInfo->permanent_district_id"
                            :selected-upazila="$studentInfo->permanent_upazila_id"
                            :selected-union="$studentInfo->permanent_union_id"
                            container-class=""
                            group-class="form-group col-md-3"
                            label-class="form-label"
                            select-class="form-control select2"
                            prefix="permanent"
                        />

                        <div class="col-md-12">
                            <div class="form-group">
                                <textarea class="form-control" name="permanent_address" id="permanent_address"
                                placeholder="Permanent Address">{{$studentInfo->permanent_address}}</textarea>
                            </div>
                        </div>
                    </div>
                    {{-- Permanent Address End --}}
                </div>

                <div class="row py-2 mb-0 form__head">
                    Hostel information
                </div>
                <div class="row p-2 form__body">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="hostel">Hostel </label>
                            {{ generateDropdown($hostels, 'class="form-control hostel" id="hostel" name="hostel"', $studentInfo?->studentHostel?->hostel_id,'Select Option') }}
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="hostel">Floor </label>
                            {{ generateDropdown([], 'class="form-control select2 hostel_floor_id" id="hostel_floor_id" name="hostel_floor_id"', $studentInfo?->studentHostel?->hostel_floor_id, 'Select Option') }}
                        </div>
                    </div>

                    <div class="col-md-5">
                        <div class="form-group">
                            <label for="hostel">Room </label>
                            {{ generateDropdown([], 'class="form-control select2 room_number" id="room_number" name="room_number"', old('room_number'), 'Select Option') }}
                        </div>
                    </div>
                </div>

                <div class="row py-2 mb-0 form__head">
                    Transport information
                </div>
                <div class="row p-2 form__body">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="code">Routes</label>
                            {{ generateDropdown($transport_routes, 'class="form-control select2 route_id" id="route_id" name="route_id"', $studentInfo?->studentTransport?->route_id, "Select Route") }}
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="code">Stoppage</label>
                            {{ generateDropdown([], 'class="form-control select2 stoppage_id" id="stoppage_id" name="stoppage_id"', '', "Select Stopage") }}
                        </div>
                    </div>
                </div>

                <div class="row py-2 mb-0 form__head">
                    Sibling information
                </div>
                <div class="row p-2 form__body">
                    <div class="col-md-4">
                        <div id="sibling-container">
                            <div class="sibling-entry mb-2 d-flex align-items-center">
                                <div class="form-group flex-grow-1">
                                    <label for="student-search">Sibling Info</label>
                                    <input type="text" id="student-search"
                                           class="form-control student-search"
                                           placeholder="Search by Student ID">
                                    {{-- <input type="hidden" class="student-search-value" name="student_id_no" value="{{ $student_id_no ?? '' }}"> --}}
                                </div>
                                <button type="button" class="btn btn-info ml-2 mt-3 add-sibling">Add</button>
                            </div>
                        </div>
                        <div id="siblings-list">
                            @forelse ($studentInfo->siblings as $sibling)
                                <div
                                    class="sibling-item mb-1 p-1 bg-light d-flex justify-content-between align-items-center">
                                    <span>{{$sibling->name}} ({{$sibling->student_id_no}})</span>
                                    <input type="hidden" name="sibling_id_no[]" value="{{$sibling->student_id_no}}">
                                    <button type="button" class="btn btn-danger btn-sm remove-sibling"><i
                                            class="fas fa-minus-circle"></i></button>
                                </div>
                            @empty

                            @endforelse

                        </div>
                    </div>
                </div>

                <div class="row py-2 mb-0 form__head">
                    Guardian information
                </div>

                <div class="row p-2 form__body">
                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="guardian_name">Guardian name </label>
                            <input type="text" class="form-control" name="guardian_name"
                                   value="{{$studentInfo->guardian_name}}" placeholder="Guardian Name">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="guardian_occupation">Guardian occupation </label>
                            {{ generateDropdown($occupations, 'class="form-control select2 guardian_occupation" id="guardian_occupation" name="guardian_occupation" ', $studentInfo->guardian_occupation, 'Select Option') }}
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="guardian_mobile">Guardian mobile </label>
                            <input type="tel" class="form-control" name="guardian_mobile"
                                   value="{{$studentInfo->guardian_mobile}}" placeholder="Guardian Mobile No">
                        </div>
                    </div>

                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="guardian_relationship">Relation with guardian </label>
                            {{ generateDropdown($guardian_relations, 'class="form-control select2" name="guardian_relationship"', $studentInfo->guardian_relationship, 'Select Option') }}
                        </div>
                    </div>
                    <div class="col-md-4">

                        <label for="guardian_address">Guardian address </label>
                        <input type="text" class="form-control" name="guardian_address"
                               value="{{$studentInfo->guardian_address}}" placeholder="Gurdian Address">
                    </div>
                </div>

                <div class="row py-2 mb-0 form__head">
                    Status
                </div>
                <div class="row p-2 form__body">
                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="status">Status</label>
                            {{ generateDropdown(Status::STUDENT_STATUS(), 'class="form-control status" id="status" name="status"', $studentInfo->status, "") }}
                        </div>
                    </div>
                    <div class="col-md-4 inactive-reason" style="display: none">
                        <div class="form-group">
                            <label for="inactive_reason">Inactive Reason</label>
                            <input type="text" class="form-control" name="inactive_reason"
                                value="{{ $studentInfo->inactive_reason }}" placeholder="Inactive Reason">
                        </div>
                    </div>
                </div>


                {{-- <div class="row p-2 form__body">
                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="guardian_name">Status </label>
                            {{ generateDropdown(Status::STUDENT_STATUS(), 'class="form-control status" id="status" name="status"', $studentInfo->status, "") }}
                        </div>
                    </div>
                    <div class="col-md-4" style="display: none">
                        <div class="form-group">
                            <label for="inactive_reason">Inactive Reason </label>
                            <input type="text" class="form-control" name="inactive_reason"
                               value="{{$studentInfo->inactive_reason}}" placeholder="Inactive Reason">
                        </div>
                    </div>
                </div> --}}

                <div class="row mt-3">
                    <a href="{{ route('student_info.index') }}" type="button" class="btn btn-default mr-2">Discard</a>
                    <button class="btn btn-submit">Update</button>
                </div>
            </form>
        </div>
    </div>
    <script>
        const input = document.querySelector('.image-uploader__input');
        const previewImage = document.querySelector('.image-uploader__preview-image');

        input.addEventListener('change', () => {
            const file = input.files[0];
            const reader = new FileReader();

            reader.onload = (event) => {
                previewImage.src = event.target.result;
            };

            reader.readAsDataURL(file);
        });
    </script>
@endsection

@section('scripts')


<script>
    $(document).ready(function () {

        function toggleInactiveReason() {
            if ($('#status').val() === 'inactive') { // use the exact value from your dropdown
                $('.inactive-reason').show();
            } else {
                $('.inactive-reason').hide();
            }
        }

        // Initial check on page load
        toggleInactiveReason();

        // On status change
        $('#status').change(function() {
            toggleInactiveReason();
        });
        

        const $studentClass = $('.student_class');

        $studentClass.on('change', function () {
            const student_class_id = $(this).val();
            getSubjects(student_class_id);
        });

        function toggleHscSubjects() {
            const selectedClassId = parseInt($('#student_class').val());

            // Assuming class 11 has ID = 11 and class 12 has ID = 12
            if (selectedClassId === 13 || selectedClassId === 14) {
                $('.hsc-subjects').show();
            } else {
                $('.hsc-subjects').hide();
            }
        }

        // Initial check on page load
        toggleHscSubjects();

        // When the class dropdown changes
        $('#student_class').on('change', function () {
            toggleHscSubjects();
        });


        function getSubjects(student_class_id) {
            let subject_id = "{{ isset($subject_id) ? addslashes($subject_id) : '' }}";
            if (student_class_id) {
                $.get('{{ route('subjects.list_by_class') }}', {student_class_id: student_class_id})
                    .done(function (response) {
                        let option = '<option value="">Subject</option>';
                        response.forEach(function (item) {
                            if (item.student_class_id == student_class_id) {
                                const selected = subject_id == item.subject_id ? ' selected' : '';
                                option += `<option value="${item.subject_id}"${selected}>${item.subject.subject_name}</option>`;
                            }
                        });
                        $subjectSelect.empty().append(option);
                    })
                    .fail(function (jqXHR, textStatus) {
                        console.error('Subjects load failed:', textStatus);
                    });
            }
        }


    });
</script>


    <script>
        $('.student_class').on('change', function () {
            let student_class_id = $(this).val();
            getSection(student_class_id)
        });

        let selected_class_id = "{{ $studentInfo->student_class_id }}";
        let selected_section_id = "{{ $studentInfo->section_id }}";

        if (selected_class_id) {
            getSection(selected_class_id)
        }

        function getSection(student_class_id) {
            if (student_class_id) {
                $.get('{{ route('sections.list_by_class') }}', {student_class_id: student_class_id}, function (response) {
                    let sections = response;

                    let option = '<option value="">--Select Section--</option>';
                    for (let i = 0; i < sections.length; i++) {

                        if (selected_section_id == sections[i].id) {
                            option += '<option value=' + sections[i].id + ' selected>' + sections[i].section_name + '</option>';
                        } else {
                            option += '<option value=' + sections[i].id + ' >' + sections[i].section_name + '</option>';
                        }
                    }
                    $('select.section_id').empty().append(option);
                });
            }
        }

        $('.route_id').on('change', function () {
            let route_id = $(this).val();
            let stoppage_id = '';
            getStoppage(route_id, stoppage_id);
        });

        let selected_route_id = "{{$studentInfo->studentTransport->route_id ?? ""}}";
        let selected_stoppage_id = "{{$studentInfo->studentTransport->stoppage_id ?? ""}}";

        if (selected_route_id && selected_stoppage_id) {
            getStoppage(selected_route_id, selected_stoppage_id)
        }

        function getStoppage(route_id, stoppage_id) {

            if (route_id) {
                $.get('{{ route('stoppage-list-by-route') }}', {route_id: route_id}, function (response) {
                    let stoppages = response;

                    let option = '<option value="">--Select Stopages--</option>';
                    for (let i = 0; i < stoppages.length; i++) {

                        if (stoppage_id == stoppages[i].id) {
                            option += '<option value=' + stoppages[i].id + ' selected>' + stoppages[i].name + ' -> ( Tk. ' + stoppages[i].monthly_cost + ')</option>';
                        } else {
                            option += '<option value=' + stoppages[i].id + ' >' + stoppages[i].name + ' -> ( Tk. ' + stoppages[i].monthly_cost + ')</option>';
                        }

                    }
                    $('select.stoppage_id').empty().append(option);
                });
            }
        }

        let selected_hostel_id = "{{$studentInfo->studentHostel->hostel_id ?? ""}}";
        let selected_hostel_floor_id = "{{$studentInfo->studentHostel->hostel_floor_id ?? ""}}";
        let selected_hostel_room_id = "{{$studentInfo->studentHostel->hostel_room_id ?? ""}}";

        $('.hostel').on('change', function () {
            let hostel_id = $(this).val();
            getHostelFloor(hostel_id)
        });

        if (selected_hostel_id) {
            getHostelFloor(selected_hostel_id)
        }

        function getHostelFloor(hostel_id) {
            if (hostel_id) {
                $.get('{{ route('hostel.floors') }}', {hostel_id: hostel_id}, function (response) {
                    let hostel_floors = response;

                    let option = '<option value="">--Select Section--</option>';
                    for (let i = 0; i < hostel_floors.length; i++) {
                        if (selected_hostel_floor_id == hostel_floors[i].id) {
                            option += '<option value=' + hostel_floors[i].id + ' selected>' + hostel_floors[i].name + '</option>';
                        } else {
                            option += '<option value=' + hostel_floors[i].id + ' >' + hostel_floors[i].name + '</option>';
                        }
                    }
                    $('#hostel_floor_id').empty().append(option);

                });

            }
        }

        $('#hostel_floor_id').on('change', function () {
            let hostel_floor_id = $(this).val();
            getHostelRoom(hostel_floor_id)
        });

        if (selected_hostel_floor_id) {
            getHostelRoom(selected_hostel_floor_id)
        }

        function getHostelRoom(hostel_floor_id) {
            if (hostel_floor_id) {
                $.get('{{ route('hostel-room-by-floor') }}', {hostel_floor_id: hostel_floor_id}, function (response) {
                    let hostel_rooms = response;

                    let option = '<option value="">--Select Section--</option>';
                    for (let i = 0; i < hostel_rooms.length; i++) {

                        const disabled = hostel_rooms[i].empty_beds === 0 ? 'disabled' : '';
                        const selected = selected_hostel_room_id == hostel_rooms[i].id ? 'selected' : '';
                        option += `<option value="${hostel_rooms[i].id}" ${selected} ${disabled}>
                                        ${hostel_rooms[i].room_name} => ${hostel_rooms[i].room_type.name}
                                        => (Tk.${Math.floor(hostel_rooms[i].room_type.cost_per_bed)})
                                        => ${hostel_rooms[i].no_of_bed}/${hostel_rooms[i].empty_beds}
                                    </option>`;
                    }

                    $('#room_number').empty().append(option);

                });
            }
        }

        $(".student-search").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "{{ route('students.search') }}",
                    data: {
                        query: request.term
                    },
                    success: function (data) {
                        response($.map(data, function (student) {
                            if (/^0/.test(request.term)) { // Check if mobile number starts with 0
                                return {
                                    label: `${student.first_name} ${student.last_name} (${student.guardian_mobile})`,
                                    value: student.student_id_no
                                };
                            } else { // Otherwise, assume it's an ID starting with 1-9
                                return {
                                    label: `${student.first_name} ${student.last_name} (${student.student_id_no})`,
                                    value: student.student_id_no
                                };
                            }
                        }));
                    }
                });
            },
            minLength: 3, // Trigger autocomplete after 3 characters
            select: function (event, ui) {
                // Set the selected sibling name and ID to the input
                $(this).val(ui.item.label); // Set the label (full name with ID/Mobile)
                $(this).siblings('.student-search-value').val(ui.item.value); // Optionally, store student ID in hidden field
                return false;
            },
            focus: function (event, ui) {
                $(this).val(ui.item.label); // Optionally, show full label when focused
                return false;
            }
        });

        // Handle the "Add" button click to add a sibling entry to the list below
        $(document).on('click', '.add-sibling', function () {
            var $parent = $(this).closest('.sibling-entry'); // Get the current sibling entry
            var siblingName = $parent.find('.student-search').val(); // Get the full name (label) from input field
            var studentId = $parent.find('.student-search-value').val(); // Get the student ID from the hidden input
            console.log(siblingName + '' + studentId);
            // Check if the input is not empty (a sibling has been selected)
            if (siblingName && studentId) {
                // Append the sibling data as a list item in the #siblings-list
                $('#siblings-list').append(`
                    <div class="sibling-item mb-1 p-1 bg-light d-flex justify-content-between align-items-center">
                        <span>${siblingName}</span>
                        <input type="hidden" name="sibling_id_no[]" value="${studentId}">
                        <button type="button" class="btn btn-danger btn-sm remove-sibling"><i class="fas fa-minus-circle"></i></button>
                    </div>
                `);

                // Clear the search input for the next sibling
                $parent.find('.student-search').val('');
                $parent.find('.student-search-value').val('');
            } else {
                alert('Please select a sibling before adding.');
            }
        });

        // Handle the "Remove" button click to remove a sibling from the list
        $(document).on('click', '.remove-sibling', function () {
            $(this).closest('li').remove();
        });
        $("#student-search").on('input', function () {
            if ($(this).val() === '') {
                $('.student-search-value').val('');
            }
        });

        $('.date360').datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayHighlight: true,
        });

        $('#copyAddress').on('change', function() {
            if ($(this).is(':checked')) {
                // Copy division value and trigger change event
                const divisionId = $('#present_division_id').val();
                $('#permanent_division_id').val(divisionId).trigger('change');

                // Wait for districts to load before copying district
                setTimeout(() => {
                    const districtId = $('#present_district_id').val();
                    $('#permanent_district_id').val(districtId).trigger('change');

                    // Wait for upazilas to load before copying upazila
                    setTimeout(() => {
                        const upazilaId = $('#present_upazila_id').val();
                        $('#permanent_upazila_id').val(upazilaId).trigger('change');

                        // Wait for unions to load before copying union
                        setTimeout(() => {
                            const unionId = $('#present_union_id').val();
                            $('#permanent_union_id').val(unionId);

                            // Copy textarea content
                            const address = $('#present_address').val();
                            $('#permanent_address').val(address);
                        }, 500);
                    }, 500);
                }, 500);
            }
        });

    </script>
@endsection
