<form class="row g-3 auto-width create_birth_register" id="create_birth_register_form" enctype='multipart/form-data' action="{{route('birth-registers-account-store' , $ipd_admission_id) }}">
    @csrf
    @method('POST')
    <div class="col-md-6">
        <div>
            <label for="child_name" class="form-label"> Child Name <span class="text-danger"><b>*</b></span></label>
                <input type="text" class="form-control" id="child_name" name="child_name" placeholder=" Child Name ">
                <input type="hidden" class="form-control" id="birth_registers_id" name="birth_registers_id" value="{{$birth_registers_id}}">
        </div>
    </div>
     <div class="col-md-6">
        <label for="gender_id" class="form-label"> Gender </label>
        <select class="form-control" name="gender_id" id="gender_id" required>
            <option value="">Select Gender</option>
            @foreach($genders as $gender)
                <option value="{{ $gender->id }}">{{ $gender->name }}</option>
            @endforeach
        </select>
    </div>
    <div class="col-md-6">
        <div>
            <label for="birth_date" class="form-label"> Birth Date </label>
            <input type="date" class="form-control" id="birth_date" name="birth_date" placeholder="Birth Date">
        </div>
    </div>
     <div class="col-md-6">
        <div>
            <label for="birth_time" class="form-label"> Birth Time </label>
            <input type="time" class="form-control" id="birth_time" name="birth_time" placeholder="Birth Date">
        </div>
    </div>
    <div class="col-md-6">
        <div>
            <label for="mother_name" class="form-label"> Mother Name </label>
            <input type="text" class="form-control" id="mother_name" name="mother_name" placeholder="Mother Name">
        </div>
    </div>
    <div class="col-md-6">
        <div>
            <label for="father_name" class="form-label"> Father Name </label>
            <input type="text" class="form-control" id="father_name" name="father_name" placeholder="Father Name">
        </div>
    </div>
    <div class="col-md-6">
        <div>
            <label for="birth_report" class="form-label"> Report </label>
            <input type="text" class="form-control" id="birth_report" name="birth_report" placeholder="Report">
        </div>
    </div>
</form>


<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js') }}"></script>
<script src="{!! asset('admin/js/accounts.js') !!}"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<script>
    $(document).ready(function(){
        $('#admission_date').flatpickr({
            enableTime: true,
            dateFormat: "Y-m-d H:i",
            defaultDate: "now",
            clickOpens: true,
            onReady: function (selectedDates, dateStr, instance) {
                instance.setDate(new Date(), true);
            },
            onClose: function (selectedDates, dateStr, instance) {
                instance.close();
            }
        });

        $('.patient-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="patient_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('billings-search-patients') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'get_patients_for_billing',
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="patient_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                                code: item.code,
                                gender: item.gender ,
                                phone_no: item.phone_no,
                                date_of_birth: item.date_of_birth,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();
                var age      = ui.item.date_of_birth != null ? ', ' + getAge(ui.item.date_of_birth) + ' Years' : '';
                var gender   = ui.item.gender != null ? ', ' + ui.item.gender : '';
                var phone_no = ui.item.phone_no != null ? ', ' + ui.item.phone_no : '';

                $(this).val(ui.item.name + ' - (' + ui.item.code + ')' + gender + age + phone_no + "");
                $('[name="patient_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var age      = item.date_of_birth != null ? ', ' + getAge(item.date_of_birth) + ' Years' : '';
            var gender   = item.gender != null ? ', ' + item.gender : '';
            var phone_no = item.phone_no != null ? ', ' + item.phone_no : '';

            return $("<li>")
                .append("<a>" + item.name + ' - (' + item.code + ')' + gender + age + phone_no + "</a>")
                .appendTo(ul);
        };
    });

    var patientSelect = document.querySelector(".patient-select");
    var querySelector = document.querySelector(".searchResult");

    /**************** create patient ********************/
    $(document).on('click', '#create_patient', function(){
        $('#commonModalLabel').text('Add New Patient');
        $('.save_button_span').text('Save Patient');
        $.ajax({
          url:"{!! route('patient-account-create') !!}?redirect_back=ipd_admission",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $( function() {
                $('#date_of_birth').datepicker();
            });
            reinitializeTelInput();
          }
        })
    })

    /**************** edit patient ********************/
    $(document).on('click', '#edit_patient', function() {
        var customerName = $('[name="patient_id"]').val();

        if (customerName === "") {
            $('.error_patient_id').show();
        } else {
            $('.error_patient_id').hide();

            $('#commonModalLabel').text('Edit Patient');
            $('.save_button_span').text('Update Patient');
            var id = $('[name="patient_id"]').val();

            var url = `{!! route('patient-account-edit', ':id') !!}`.replace(':id', id);

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                    $('[name="date_of_birth"]').datepicker('destroy');

                    $('[name="date_of_birth"]').datepicker({
                        "dateFormat" : "yy-mm-dd",
                        "maxDate": '0',
                        "changeMonth": true,
                        "changeYear": true
                    }).datepicker("setDate",'now')
                    .on('changeDate', function (ev) {
                         $(this).datepicker('hide');
                    })
                    .on('focusout', function (ev) {
                         $(this).datepicker('hide');
                    });
                    reinitializeTelInput();
                }
            });
        }
    });

    function CitySelected(id) {
        if ($('[name="city_id"]').length > 0) {
            $('[name="city_id"]').val(id);
        } else {
            setTimeout(function() {
                CitySelected(id);
            }, 1000);
        }
    }

    /**************** Create City ********************/
    $(document).on('click', '#create_city', function() {
        $('#commonModalLabel').text('Add New City');
        $('.save_button_span').text('Save City');
        $.ajax({
            url: "{!! route('cities.create') !!}",
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
            }
        })
    })

    function getAge(birthdate) {
        if (birthdate != '' && birthdate != null && birthdate != undefined) {
            var birthdateObj = new Date(birthdate);
            var now = new Date();
            var age = now.getFullYear() - birthdateObj.getFullYear();

            // Adjust age if birthday hasn't occurred this year yet
            if (now.getMonth() < birthdateObj.getMonth() || (now.getMonth() === birthdateObj.getMonth() && now.getDate() < birthdateObj.getDate())) {
                age--;
            }
            return age;
        }
    };

    /******* Disabling & Enabling edit button of patient ************/
    $(document).ready(function() {
        function toggleEditButton() {
            var patientId = $('[name="patient_id"]').val();
            $('#edit_patient').prop('disabled', patientId === "");
        }

        toggleEditButton();

        $('#patient_id').on('input', function() {
            toggleEditButton();
        });

        $('#patient_id').on('change', function() {
            toggleEditButton();
        });

        $('#edit_patient').on('click', function() {
            var patientName = $('#patient_id').val();

            if (patientName === "") {
                $('.error_patient_id').show();
            } else {
                $('.error_patient_id').hide();

                $('#commonModalLabel').text('Edit Customer');
                $('.save_button_span').text('Update Customer');
                var id = $('[name="patient_id"]').val();
                var url = `{!! route('patient-account-edit', ':id') !!}`.replace(':id', id);

                $.ajax({
                    url: url,
                    success: function(data) {
                        $('#commonModal').find('.modal-body').html('');
                        $('#commonModal').find('.modal-body').html(data);
                    }
                });
            }
        });

        function enableEditButton() {
            $('#edit_patient').prop('disabled', false);
        }

        function addValueToPatientId(newValue) {
            $('[name="patient_id"]').val(newValue);
            enableEditButton();
        }
    });


    function allNumeric(inputtxt) {
        onlyNumbers = inputtxt.replace(/[^0-9]/g, '');
        if (onlyNumbers.length > 16) {
            onlyNumbers = onlyNumbers.substring(0, 16);
        }
        return onlyNumbers;
    }
    $("#ipd_file_no").on('input', function() {
        const onlyNumbers = allNumeric($(this).val());
        $("#ipd_file_no").val(onlyNumbers);
    });


    $(document).on('click','.save_button', function(e) {
        e.preventDefault();
        if ($('#commonModal').find('form').hasClass('create_patient')) {
            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').hide();
            $('.error_date_of_birth').hide();
            var error = 0;
            if ($('#phone_no').val() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }
            if ($('#relation_phone').val() != '') {
                var dailcode_title = $('.relation_phone_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="relation_phone"]').val("+" + dailcode_array[1] + $('#relation_phone').val());
            }
            $('#year').trigger("change")

            const yearInput = $('#age_years').val();
            const monthInput = $('#month').val();
            const dayInput = $('#day').val();
            const hourInput = $('#hour').val();

            if (yearInput == '' & monthInput == '' &  dayInput == '' & hourInput == '' ) {
                // toastr.error('Date field is required!', 'Error');
                $('.error_date_of_birth').show();
                error = 1;
                setTimeout(function () {
                    $('.error_date_of_birth').hide();
                }, 3000);
            }
            if ($('#age_years').val() == '') {
                $('.error_date_of_birth').show();
                error = 1;
                setTimeout(function () {
                    $('.error_date_of_birth').hide();
                }, 3000);
            }
            if ($('#whatsapp_no').val() != '') {
                var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
            }


            if ($('input[name="name"]').val() == '') {
              $('.error_name').show();
              error = 1;
              setTimeout(function () {
                $('.error_name').hide();
                }, 3000);
            }
            if ($('[name="country_id"]').val() == '') {
              $('.error_country_id').show();
              error = 1;
            }
            if ($('input[name="phone_no"]').val() == '') {
              $('.error_phone').show();
              error = 1;
              setTimeout(function () {
                    $('.error_phone').hide();
                }, 3000);
            }
            if ($('input[name="date_of_birth"]').val() == '' &&
                $('input[name="year"]').val() == '' &&
                $('input[name="month"]').val() == '' &&
                $('input[name="day"]').val() == ''
            ) {
            //   $('.error_date_of_birth').show();
            //   error = 1;
            }
            if ($('input[name="relation_phone"]').val() == '') {
              $('.error_relation_phone').show();
              error = 1;
              setTimeout(function () {
                    $('.error_relation_phone').hide();
                }, 3000);
            }

            if ($('input[name="relation_type"]').val() == '') {
              $('.error_address_type_id').show();
              error = 1;
              setTimeout(function () {
                    $('.error_address_type_id').hide();
                }, 3000);
            }

            if ($('input[name="relation_name"]').val() == '') {
              $('.error_relation_name').show();
              error = 1;
              setTimeout(function () {
                    $('.error_relation_name').hide();
                }, 3000);
            }

            if (error == 0) {
                let formdata = new FormData($('#create_patient_form')[0]);

                $.ajax({
                    url: $('#create_patient_form').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="patient_id"]').val(response.data.id);
                            $('#patient_id').val(response.data.name);
                            $('#edit_patient').prop('disabled', false);
                            // 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!');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('update_patient')) {
            console.log('as');
            if ($('#phone_no').val() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }
            $('#year').trigger("change")

            const yearInput  = $('#year').val();
            const monthInput = $('#month').val();
            const dayInput   = $('#day').val();
            const hourInput  = $('#hour').val();

            if (yearInput == '' & monthInput == '' &  dayInput == '' & hourInput == '' ) {
                // toastr.error('Date field is required!', 'Error');
                $('.error_date_of_birth').show();
                error = 1;
                setTimeout(function () {
                    $('.error_date_of_birth').hide();
                }, 3000);
            }

            if ($('#whatsapp_no').val() != '') {
                var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
            }

            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').hide();
            $('.error_date_of_birth').hide();
            var error = 0;

            if ($('input[name="name"]').val() == '' || $('[name="account_title_id"]').val() == '') {
              $('.error_name').show();
              error = 1;
              setTimeout(function () {
                $('.error_name').hide();
                }, 3000);

            }

            if ($('[name="country_id"]').val() == '') {
              $('.error_country_id').show();
              error = 1;
              setTimeout(function () {
                $('.error_country_id').hide();
                }, 3000);

            }

            if ($('input[name="phone_no"]').val() == '') {
              $('.error_phone').show();
              error = 1;
              setTimeout(function () {
                $('.error_phone').hide();
                }, 3000);

            }
            if ($('#age_years').val() == '') {
                $('.error_date_of_birth').show();
                error = 1;
                setTimeout(function () {
                    $('.error_date_of_birth').hide();
                }, 3000);
            }

            if ($('input[name="date_of_birth"]').val() == '' &&
                $('input[name="year"]').val() == '' &&
                $('input[name="month"]').val() == '' &&
                $('input[name="day"]').val() == ''
            ) {
              $('.error_date_of_birth').show();
              error = 1;
              setTimeout(function () {
                $('.error_date_of_birth').hide();
                }, 3000);

            }

            if (error == 0) {
                let formdata = new FormData($('#update_patient_form')[0]);

                $.ajax({
                    url: $('#update_patient_form').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="patient_id"]').val(response.data.id);
                            $('#patient_id').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!');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('create_cities')) {
            console.log('tset');
            event.preventDefault();
            $('.error_name').hide();
            var error = 0;
            setTimeout(function() {
                $('.error_name').hide();
            }, 3000);


            if ($('#commonModal').find('form').find('input[name="name"]').val() == '') {
                $('.error_name').show();
                error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('#commonModal').find('form')[0]);

                $.ajax({
                    url: $('#commonModal').find('form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');

                            // hide modal
                            $('#commonModal').removeClass('create_cities');
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            setTimeout(function() {
                                $('#create_patient').trigger('click');
                                CitySelected(response.data.id);
                            }, 1000);

                    } 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!');

                // hide modal
                $('#commonModal').modal('hide');
                $('#commonModal').find('.modal-body').html('');
            });
            }
            error = 1;
        }
        else {
            $('.error_patient_id').hide();
            $('.error_admission_date').hide();
            $('.error_ipd_file_no').hide();

            var error = 0;

            if ($('input[name="patient_id"]').val() == '') {
              $('.error_patient_id').show();
              error = 1;
              setTimeout(function () {
                $('.error_patient_id').hide();
                }, 3000);

            }
            if ($('[name="admission_date_time"]').val() == '') {
              $('.error_admission_date').show();
              error = 1;
            }

            if (error == 0) {
                $('.ipd-admission-form').submit();
            }
        }

        error = 1;
    })

</script>

