@extends('layouts.app')
@section('title', 'Doctor Shifts')
@section('pages')
    <style type="text/css">
        .breadcrumb-title {
            border-right: none;
        }
    </style>

    <!--breadcrumb-->
    <div class="page-breadcrumb row align-items-center justify-content-between mb-3 px-3 px-md-0">
        <div class="breadcrumb-title col-md-6"> Shifts for  <span class="badge bg-info">Dr {{ ucfirst($doctor_shifts->getDoctor->getAccount->name ?? '') }}</span></div>
        <div class="col-md-6">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb justify-content-md-end mb-0">
                    <li class="breadcrumb-item"><i class="bi bi-info-circle-fill text-info show-help-support" data-id="84" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
                </ol>
            </nav>
        </div>
    </div>
    <!--end breadcrumb-->

    <!-- main -->
    <div class="card style_table shadow-none radius-5 min-height">

        <div class="card-header py-3">
            @include('layouts.partials.nav-menu')
            <div class="row gx-5" style="margin-left:0px">

                <div class="parent-checkbox px-3 mt-3 d-sm-flex">
                <div class="col-lg-3 col-md-3">
                    <span class="pe-2 h5">Allow All Shifts</span>
                    <input type="checkbox" class='header-checkbox' class="form-control" id="check-all">
                </div>

                    <div class="col-lg-9 col-md-9">
                        <div class="ms-auto float-md-end">
                            <div class="btn-group">
                            <a href="{!! route('doctor.index') !!}" class="btn btn-outline-secondary me-1"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card-body" id="tables">
            @include('appointment-doctor-shifts.table')
        </div>
        <input type="hidden" name="hidden_page" id="hidden_page" value="1" />
            <input type="hidden" name="hidden_column_name" id="hidden_column_name" value="name" />
            <input type="hidden" name="hidden_sort_type" id="hidden_sort_type" value="asc" />
        <!-- end main -->
    </div>

    @endsection
    @section('js')
        <script>
            $(document).ready(function() {
                 // permission to all 
                 $(document).on('change', '#check-all', function() {
                    //  var parent = $('#tables');
                    var parent = $('.shiftcheck');
                     if ($(this).is(':checked')) {
                         parent.find('input[type="checkbox"]').prop('checked', true);
                         parent.find('.ui-switcher').attr('aria-checked', true);
                         // parent.find('input[type="checkbox"]').trigger('change');
                        } else {
                        console.log('test1');
                        parent.find('input[type="checkbox"]').prop('checked', false);
                        parent.find('.ui-switcher').attr('aria-checked', false);
                        // parent.find('input[type="checkbox"]').trigger('change');
                    }
                    
                    var doctorId = {!! $id !!};
                    // console.log(doctorId,'testing doctor ID variables');
                    
                    var formData = new FormData();
                    formData.append("id", doctorId);
                    formData.append("shift_id", 'all');

                    if ($(this).is(':checked')) {
                        formData.append("status", '1');
                    } else {
                        formData.append("status", '0');
                    }

                    $.ajax({
                        url: "{!! route('appointment-doctor-shifts.doctor-shift-status') !!}",
                        data: formData,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            if (response.success === true) {
                                
                                toastr.success(response.message, 'Success.');                        
                            } else {
                                toastr.error(response.message, 'Error!');
                            }
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
                });
                // permission allows one by one
                $(document).on('change', '.shifts_click', function() {
                    // console.log('test3');
                    
                    var shifts_click = $(this);
                    var shiftId = $(this).data('shift_id');
                    var doctorId = {!! $id !!};
                    var checkStatus = 0;
                    

                    var formData = new FormData();
                    formData.append("id", doctorId);
                    formData.append("shift_id", shiftId);

                    if ($(this).is(':checked')) {
                        formData.append("status", '1');
                        checkStatus =1 ;
                    } else {
                        formData.append("status", '0');
                       checkStatus = 0;
                    }                    

                    $.ajax({
                        url: "{!! route('appointment-doctor-shifts.doctor-shift-status') !!}",
                        data: formData,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            if (response.success === true) {
                                toastr.success(response.message, 'Success.');
                                if(checkStatus == 1) {
                                 shifts_click.parent().parent().find('.fees').prop('disabled', false);
                                 shifts_click.parent().parent().find('#shift button').prop('disabled', false);
                                }else{
                                 shifts_click.parent().parent().find('.fees').prop('disabled', true);
                                 shifts_click.parent().parent().find('#shift button').prop('disabled', true);
                                }

                            } else {
                                toastr.error(response.message, 'Error!');
                            }
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
                });



                // permission allows one by one Web Bookings
                $(document).on('change', '.web_booking_click', function() {
                    // console.log('test3');
                    
                    var shifts_click = $(this);
                    var shiftId = $(this).data('shift_id');
                    var doctorId = {!! $id !!};
                    var checkStatus = 0;
                    

                    var formData = new FormData();
                    formData.append("id", doctorId);
                    formData.append("shift_id", shiftId);

                    if ($(this).is(':checked')) {
                        formData.append("status", '1');
                        checkStatus =1 ;
                    } else {
                        formData.append("status", '0');
                       checkStatus = 0;
                    }                    

                    $.ajax({
                        url: "{!! route('appointment-doctor-shifts.doctor-shift-web-booking-status') !!}",
                        data: formData,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            if (response.success === true) {
                                toastr.success(response.message, 'Success.');
                                // if(checkStatus == 1) {
                                //  shifts_click.parent().parent().find('.fees').prop('disabled', false);
                                //  shifts_click.parent().parent().find('#shift button').prop('disabled', false);
                                // }else{
                                //  shifts_click.parent().parent().find('.fees').prop('disabled', true);
                                //  shifts_click.parent().parent().find('#shift button').prop('disabled', true);
                                // }

                            } else {
                                toastr.error(response.message, 'Error!');
                            }
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
                });


                // permission allows one by one App Bookings
                $(document).on('change', '.app_booking_click', function() {
                    // console.log('test3');
                    
                    var shifts_click = $(this);
                    var shiftId = $(this).data('shift_id');
                    var doctorId = {!! $id !!};
                    var checkStatus = 0;
                    

                    var formData = new FormData();
                    formData.append("id", doctorId);
                    formData.append("shift_id", shiftId);

                    if ($(this).is(':checked')) {
                        formData.append("status", '1');
                        checkStatus =1 ;
                    } else {
                        formData.append("status", '0');
                       checkStatus = 0;
                    }                    

                    $.ajax({
                        url: "{!! route('appointment-doctor-shifts.doctor-shift-app-booking-status') !!}",
                        data: formData,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            if (response.success === true) {
                                toastr.success(response.message, 'Success.');
                                // if(checkStatus == 1) {
                                //  shifts_click.parent().parent().find('.fees').prop('disabled', false);
                                //  shifts_click.parent().parent().find('#shift button').prop('disabled', false);
                                // }else{
                                //  shifts_click.parent().parent().find('.fees').prop('disabled', true);
                                //  shifts_click.parent().parent().find('#shift button').prop('disabled', true);
                                // }

                            } else {
                                toastr.error(response.message, 'Error!');
                            }
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
                });

                
                //  Doctor Shift Days Fee modal
                $(document).on('click', '.fees', function() {
                    var doctor_id = $(this).data('doctor_id');
                    var shift_id = $(this).data('shift_id');
                    var url =
                        "{{ route('appointment-doctor-fees.create', ['doctor_id' => ':doctor_id', 'shift_id' => ':shift_id']) }}";
                    url = url.replace(':doctor_id', doctor_id);
                    url = url.replace(':shift_id', shift_id);

                    $('#commonModalLabel').text('Add New Doctor Fees');
                    $('.save_button_span').text('Save Doctor Fees');
                    $.ajax({
                        url: url,
                        data: {
                            'doctor_id': doctor_id,
                            'shift_id': shift_id,
                        },
                        success: function(data) {
                            $('#commonModal').find('.modal-body').html(data);
                            $('.product-select').autocomplete({
                                autoFocus: true,
                                minLength: 0,
                                source: function(request, response) {
                                    if (request.term.length < 2) {
                                        $('[name="product_id"]').val('');
                                        return false;
                                    }

                                    $.ajax({
                                        url: "{{ route('doctor-fee-search-products') }}",
                                        type: 'POST',
                                        dataType: 'json',
                                        data: {
                                            search_text: request.term
                                        },
                                        success: function(json) {
                                            if (json.error) {
                                                $('[name="product_id"]')
                                                    .val('');
                                                return false;
                                            }
                                            response($.map(json.result,
                                                function(item) {
                                                    return {
                                                        id: item.id,
                                                        name: item
                                                            .name,
                                                    };
                                                }));
                                        }
                                    });
                                },
                                select: function(event, ui) {
                                    event.preventDefault();
                                    $(this).val(ui.item.name);
                                    $('[name="product_id"]').val(ui.item.id);
                                    return false;
                                }
                            }).data("ui-autocomplete")._renderItem = function(ul, item) {
                                return $("<li>").append("<a>" + item.name + "</a>").appendTo(
                                    ul);
                            };
                        }
                    });
                });
                const doctorSelect = document.querySelector(".product-select");
                document.addEventListener("click", (event) => {
                    if (event.target !== doctorSelect) {
                        $(".searchResult").empty();
                    }
                });

                /*********SAVE**********/
                $(document).on('click', '.save_button', function(event) {
                    event.preventDefault();
                    $('.error_product_id').hide();
                    var error = 0;
                    if ($('#commonModal').find('form').find('input[name="product_id"]').val() == '') {
                        $('.error_product_id').show();
                        error = 1;
                    }
                    if (error == 0) {
                        $('#commonModal').find('form').submit();
                        $.ajax({
                                url: $('#fees').attr('action'),
                                data: formdata,
                                processData: false,
                                contentType: false,
                                type: 'POST',
                                success: function(response) {
                                    if (response.success === true) {
                                        toastr.success(response.message, 'Success.');
                                        // append new category to selection
                                        $('[name="doctor_id"]').val(response.data.id);
                                        $('.doctor-select').val(response.data.name);

                                        // hide modal
                                        $('#commonModal').modal('hide');
                                        $('#commonModal').find('.modal-body').html('');
                                    } else {
                                        toastr.error(response.message, 'Error!');
                                    }
                                }
                            })
                            .fail(function(jqXHR, textStatus, errorThrown) {
                                console.log('AJAX request failed:', textStatus, errorThrown);
                                toastr.error('An error occurred during the request.', 'Error!');
                            });
                    }
                    error = 1;
                })


                $(document).on('change', '#check-all', function() {
                    var parent = $('.shiftcheck');
                    if ($(this).is(':checked')) {
                        parent.find('input[type="checkbox"]').prop('checked', true);
                        parent.find('.ui-switcher').attr('aria-checked', true);
                        $('.shift').prop('disabled', false);  
                        $('.fees').prop('disabled', false);      
                    } else {
                        parent.find('input[type="checkbox"]').prop('checked', false);
                        parent.find('.ui-switcher').attr('aria-checked', false);
                        $('.shift').prop('disabled', true);  
                        $('.fees').prop('disabled', true);     
                    }
                });

            
                $(document).on('change', '.body-checkbox', function() {
                    var a = $('.body-checkbox');
                    if (3 == a.filter(":checked").length) {
                        $('.header-checkbox').prop('checked', true);
                        $('.parent-checkbox').find('.ui-switcher').attr('aria-checked', true);
                    } else {
                        $('.header-checkbox').prop('checked', false);
                        $('.parent-checkbox').find('.ui-switcher').attr('aria-checked', false);
                    }
                });

                var a = $('.body-checkbox');
                // console.log(a.filter(":checked"));
                // console.log(a.length);
                // debugger;
                if (3 == a.filter(":checked").length) {
                    $('.header-checkbox').prop('checked', true);
                    $('.parent-checkbox').find('.ui-switcher').attr('aria-checked', true);
                } else {
                    $('.header-checkbox').prop('checked', false);
                    $('.parent-checkbox').find('.ui-switcher').attr('aria-checked', false);
                }

              

            

               
            });

            $(document).on('click', '.edits', function() {
                $('#commonModalLabel').text('Edit Shift');
                $('.save_button_span').text('Update Shift');
                var id = $(this).data('id');
                var url = $(this).data('url');
                $.ajax({
                    url: url,
                    date:{id:id},
                    success: function(data) {
                        $('#commonModal').find('.modal-body').html('');
                        $('#commonModal').find('.modal-body').html(data);
                    }
                })
            });


               

           
        </script>
    @endsection
