@extends('layouts.master')
<style>
    .form-group {
        display: flex;
        align-items: center;
        margin-bottom: 0; /* Remove default bottom margin */
    }
    .form-group > * {
        flex: 1;
    }

    .row.g-3 {
        gap: 0; /* Remove gap between columns */
    }

    .col-auto {
        flex-grow: 0; /* Prevent button column from growing */
        flex-shrink: 0; /* Prevent button column from shrinking */
        width: auto; /* Allow button column to take minimal width */
    }

    .select2-results__option {
        display: flex;
        align-items: center;
        cursor: pointer;
    }
    .select2-results__option input[type="checkbox"] {
        margin-right: 10px;
        pointer-events: none; /* Prevent checkbox from handling the click event itself */
    }

    @media (max-width: 768px) {
        .form-group {
            flex: 0 0 50%;
            padding-right: 5px;
        }
        .form-group:last-child {
            padding-right: 0;
        }
    }
    @media (max-width: 576px) {
        .form-group {
            flex: 0 0 100%;
            padding-right: 0;
        }
    }
</style>

@section('content')
    <div class="card mt-3 send__sms">
        <div class="card-body">
            <div class="col-12 mt-2">
                <h5 class="mb-4">Send sms to students:</h5>
                <form method="POST" action="{{ route('student-sms.department-wise-student') }}" class="row g-3 align-items-center">
                    @csrf
                    <div class="form-group col-lg-4 col-xl-3 col-xxl-2 col-md-6 col-6">
                        <select name="student_class_id" id="student_class_id" class="form-control">
                            <option value="all">All Students </option>
                            @foreach ($studentClasses as $item)
                                <option value="{{ $item->id }}"
                                    {{ $student_class_id == $item->id ? 'selected' : '' }}>
                                    {{ $item->class_name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-auto form-group">
                        <button type="submit" class="btn btn-info">Search</button>
                    </div>
                </form>
            </div>


            <form action="{{ route('student-sms-department.send') }}" method="POST">
                @csrf
                <div class="col-12 mt-1">
                    <label>Enter Mobile Numbers <span>(Use Comma for number separation. Don't use space after/before comma.)</span></label>
                    <select name="mobile_number[]" id="mobile_numbers" class="form-control select2" multiple required>
                        @if (!empty($students) && $students->count() > 0)
                            <option value="{{ $all_mobile_no }}">All Students (Total Student : {{ $total_students }})</option>
                        @endif
                        @foreach ($students as $student)
                            <option value="{{ $student->mobile_no }}">
                                {{ $student->first_name . ' ' . $student->last_name }} ({{ $student->mobile_no }})
                            </option>
                        @endforeach
                    </select>
                </div>

                <div class="col-12 mt-3">
                    <label>Select SMS Type</label>
                    <ul class="list-unstyled mb-0">
                        <li class="d-inline-block mr-2">
                            <fieldset>
                                <div class="custom-control custom-radio">
                                    <input type="radio" class="custom-control-input testr" name="gn_sms_type" id="customRadio1" value="text" required="" checked="">
                                    <label class="custom-control-label" for="customRadio1">Text</label>
                                </div>
                            </fieldset>
                        </li>
                        <li class="d-inline-block mr-2">
                            <fieldset>
                                <div class="custom-control custom-radio">
                                    <input type="radio" class="custom-control-input testr" name="gn_sms_type" value="unicode" id="customRadio2" required="">
                                    <label class="custom-control-label" for="customRadio2">Unicode</label>
                                </div>
                            </fieldset>
                        </li>
                    </ul>
                </div>
                <div class="col-12 mt-3 mb-2">
                    <label>Enter SMS Content </label>
                    <fieldset class="form-label-group mb-0">
                        <textarea class="form-control char-textarea" id="message" name="sms_body" rows="3" required
                            placeholder="Write your sms body here..." style="color: rgb(78, 81, 84);"></textarea>
                        <label for="textarea-counter"></label>
                    </fieldset>
                    <small class="sms-count float-left">
                        <span id="length">0 characters</span> |
                        <span id="remaining">1530 Characters Left | </span>
                        <span id="messages" style="color: #f79622;font-weight: bold;"> 1 SMS </span>
                        <span id="smslen" style="color: #f79622;font-weight: bold;"> ( 160 Char./SMS ) </span>
                    </small>
                </div>

                <div class="col-12">
                    <button type="submit"
                        class="btn btn-submit float-right">Send</button>
                </div>
            </form>
        </div>
    </div>

@endsection

@section('scripts')
    <script>
        $(document).ready(function() {

            function formatState(state) {
                if (!state.id) {
                    return state.text;
                }

                var $state = $(
                    '<span><input type="checkbox" class="select2-checkbox" /> ' + state.text + '</span>'
                );

                // Ensure the checkbox is checked if the item is selected
                if ($(state.element).prop('selected')) {
                    $state.find('input').prop('checked', true);
                }

                return $state;
            }

            $('#mobile_numbers').select2({
                placeholder: "Select mobile numbers",
                templateResult: formatState,
                templateSelection: function(selection) {
                    return selection.text;
                },
                closeOnSelect: false
            });

            $('#mobile_numbers').on('select2:select select2:unselect', function(e) {
                // Force the Select2 to redraw its options
                $(this).data('select2').trigger('change');
            });

            $('#mobile_numbers').on('select2:opening select2:closing', function(event) {
                var $searchfield = $(this).parent().find('.select2-search__field');
                $searchfield.prop('disabled', true);
            });

            $('#mobile_numbers').on('change', function() {
                var selectedValues = $(this).val();
                $(this).find('option').each(function() {
                    var optionValue = $(this).val();
                    var $option = $(this);
                    if(optionValue!=0)
                        if (selectedValues.includes(optionValue)) {
                            $option.prop('selected', true);
                        } else {
                            $option.prop('selected', false);
                        }
                });
            });

            // Custom event handler to toggle checkbox when clicking on the item
            $('#mobile_numbers').on('select2:selecting', function(e) {
                var $checkbox = $(e.params.args.data.element).find('input[type="checkbox"]');
                $checkbox.prop('checked', !$checkbox.prop('checked'));
            });

            // Additional event handler for clicks outside of the checkbox
            $(document).on('click', '.select2-results__option', function(e) {
                var $checkbox = $(this).find('input[type="checkbox"]');
                if ($(e.target).is('input[type="checkbox"]')) {
                    return;
                }
                $checkbox.prop('checked', !$checkbox.prop('checked'));
            });

            var $remaining = $('#remaining'),
                $length = $('#length'),
                $smslen = $('#smslen'),
                $messages = $remaining.next();

            $('#message').keyup(function() {
                var str = this.value;
                var msgResponse = isDoubleByte(str);
                var chars = this.value.length;

                if (msgResponse == false) {
                    $("#customRadio1").prop("checked", true);
                    console.log(chars);
                    if (chars <= 160) {
                        messages = Math.ceil(chars / 160),
                        $length.text(chars + ' characters');
                        $remaining.text((1530 - chars) + ' characters left | ');
                        $messages.text(messages + ' SMS');
                        $smslen.text('( 160 Char./SMS )');
                    } else {
                        messages = Math.ceil(chars / 153),
                        $length.text(chars + ' characters');
                        $remaining.text((1530 - chars) + ' characters left | ');
                        $messages.text(messages + ' SMS');
                        $smslen.text(' ( 153 Char./SMS ) ');
                    }
                } else {
                    $("#customRadio2").prop("checked", true);
                    if (chars <= 70) {
                        messages = Math.ceil(chars / 70),
                        $length.text(chars + ' characters');
                        $remaining.text((670 - chars) + ' characters left | ');
                        $messages.text(messages + ' SMS');
                        $smslen.text('( 70 Char./SMS )');
                    } else {
                        messages = Math.ceil(chars / 67),
                        $length.text(chars + ' characters');
                        $remaining.text((670 - chars) + ' characters left | ');
                        $messages.text(messages + ' SMS');
                        $smslen.text('( 67 Char./SMS )');
                    }

                }

            });

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

        let student_class_id = "{{ isset($student_class_id) ? $student_class_id : '' }}";

        if(student_class_id!=''){
            getSection(student_class_id);
        }

        function getSection(student_class_id){

            let section_id = "{{ isset($section_id) ? $section_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="">Section</option>';
                    for(let i=0;i<sections.length;i++){
                        // if(sections[i].student_class_id == student_class_id){
                            if(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);
                });
            }
        }

        });


        function isDoubleByte(str) {
            for (var i = 0, n = str.length; i < n; i++) {
                if (str.charCodeAt(i) > 255 ||
                    str.charCodeAt(i) == 91 ||
                    str.charCodeAt(i) == 92 ||
                    str.charCodeAt(i) == 93 ||
                    str.charCodeAt(i) == 94 ||
                    str.charCodeAt(i) == 123 ||
                    str.charCodeAt(i) == 124 ||
                    str.charCodeAt(i) == 125 ||
                    str.charCodeAt(i) == 126
                ) {
                    return true;
                }
            }
            return false;
        }
    </script>
@endsection
