<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    @include('layout.header')
    <style>
        .form-group label {
            line-height: 0.2rem !important;
        }
    </style>
</head>
<body>

<div class="container-scroller">
@include('layout.navbar')
<!-- partial -->
    @include('layout.breadscrum')
    <div class="container-fluid page-body-wrapper">

    @include('layout.sidebar')

    <!-- partial -->
        <div class="main-panel">
            <div class="content-wrapper">
                <div class="row">
                    <div class="col-md-12 grid-margin stretch-card">
                        <div class="card min-vh-70">
                            <div class="card-body">
                                <h4 class="card-title"><i class="mdi mdi-dots-vertical menu-icon"></i> {{__('vaccination.new_title')}}</h4>
                                <hr>
                                <form method="post" class="p-2" action="{{route('vaccination.save')}}" id="form-test-sample">
                                    @csrf
                                    <div class="row">
                                        <div class="col-lg-12">
                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="form-vertical sample-creation-form">
                                                        <div class="row mb-0">
                                                            <div class="col-sm-12 col-md-6 col-lg-6">
                                                                <div class="form-group mb-1">
                                                                    <label for="lab-name-en">{{__('invoice.form_patient')}} <span class="text-danger">*</span></label>
                                                                    <div class="input-group" id="testItem">
                                                                        <div class="form-group" style="flex: 1 !important;">
                                                                            <select class="form-control select2" name="patient_id" id="patient-id" style=" width: 100% !important;">
                                                                                <option value="1">Walk In Patient</option>
                                                                                @foreach($patients as $patient)
                                                                                    <option value="{{$patient->id}}">{{($patient->patient_uuid . ' - ' . $patient->name_en) . ((!empty($patient->phone_number) ? ' - '.$patient->phone_number: ''))}}</option>
                                                                                @endforeach
                                                                            </select>
                                                                        </div>
                                                                        <div class="input-group-append">
                                                                            <button class="btn btn-sm btn-inverse-secondary px-3" id="searchPatientAddForm"  type="button"><i class="fa fa-search"></i> {{__('general.btn_search')}} </button>
                                                                            @if(\App\Http\Controllers\Helper\GlobalController::user_can(Auth::user()->role_id, ['create_patient']))
                                                                                <button class="btn btn-info waves-effect rounded-0 px-3 ml-2" type="button" data-action="new" data-toggle="modal" data-target="#modal-patient" data-backdrop="static"><i class="typcn typcn-plus"></i>
                                                                                    {{__('patient.form_add_title')}}</button>
                                                                            @endif
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="col-sm-12 col-md-6 col-lg-3">
                                                                <div class="form-group mb-1">
                                                                    <label for="lab-name-en">{{__('vaccination.date')}} <span class="text-danger">*</span></label>
                                                                    <input type="date" value="{{date('Y-m-d')}}" class="form-control rounded-0" name="vaccination_date" id="invoice_date" placeholder="Invoice Date">
                                                                </div>
                                                            </div>
                                                            <div class="col-sm-12 col-md-6 col-lg-3">
                                                                <div class="form-group mb-1">
                                                                    <label for="lab-name-en">{{__('vaccination.next_visit')}} <span class="text-danger">*</span></label>
                                                                    <input type="date" value="{{date('Y-m-d')}}" class="form-control rounded-0" name="next_visit_date" id="invoice_date" placeholder="Invoice Date">
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="row border p-0">
                                                            <div class="col-sm-8 p-0">
                                                                <table class="table table-bordered" >
                                                                    <thead>
                                                                    <tr class="bg-light">
                                                                        <th class="py-2">{{__('vaccination.name')}}</th>
                                                                        <th width="15%" class="py-2 text-center">{{__('vaccination.unit_price')}} ($)</th>
                                                                        <th width="15%" class="py-2 text-center">{{__('vaccination.qty')}}</th>
                                                                        <th width="15%" class="py-2 text-center">{{__('vaccination.subtotal')}}</th>
                                                                        <th width="50px" class="py-2 text-right">
                                                                            <button class="btn btn-info btn-md waves-effect rounded-0" id="btn-add-new-med-item" type="button"><i class="typcn typcn-plus"></i></button>
                                                                        </th>
                                                                    </tr>
                                                                    </thead>
                                                                    <tbody id="vaccination-item">
                                                                    <tr>
                                                                        <td class="py-2">
                                                                            <select name="medicine_item_id[]" class="form-control vaccine-item form-control-xxs select2" style="width: 100%;">
                                                                                <option></option>
                                                                                @foreach($medicineItems as $medicineItem)
                                                                                    <option data-price="{{$medicineItem->sale_price}}" value="{{$medicineItem->id}}"> {{$medicineItem->medicine->name}} </option>
                                                                                @endforeach
                                                                            </select>
                                                                        </td>
                                                                        <td class="py-2">
                                                                            <input type="number" name="unit_price[]" value="0" min="0" step="0" class="form-control unit-price">
                                                                        </td>
                                                                        <td class="py-2">
                                                                            <input type="number" name="quantity[]" value="1" min="1" step="1" class="form-control quantity">
                                                                        </td>
                                                                        <td class="py-2">
                                                                            <input type="hidden" name="sub_total[]" class="form-control sub-total">
                                                                            <input type="number" readonly class="form-control bg-white sub-total-to-display">
                                                                        </td>
                                                                        <td class="py-2">
                                                                            <button class="btn btn-danger btn-remove-vaccine-item btn-md waves-effect rounded-0" type="button"><i class="typcn typcn-trash"></i></button>
                                                                        </td>
                                                                    </tr>
                                                                    </tbody>
                                                                </table>
                                                            </div>
                                                            <div class="col-sm-4 p-4 border-left">
                                                                <div class="row">
                                                                    <div class="col-sm-12">
                                                                        <div class="form-group row">
                                                                            <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.exchange_rate')}} <span class="text-danger">*</span></label>
                                                                            <div class="col-sm-7">
                                                                                <input type="number" required step="any" class="form-control bg-white form-control-xxs rounded-0" value="{{$labSettings->exchange_rate}}" name="exchange_rate" id="exchange_rate">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-sm-12">
                                                                        <div class="form-group row">
                                                                            <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.table_total_cost')}} <span class="text-danger">({{$labSettings->currency==1?'៛':'$'}})</span></label>
                                                                            <div class="col-sm-7">
                                                                                <input type="number" readonly required step="any" class="form-control bg-white form-control-xxs rounded-0" name="total" id="total-amount" placeholder="0.00">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-sm-12">
                                                                        <div class="form-group row">
                                                                            <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.table_discount')}} <span class="text-danger">(%)</span></label>
                                                                            <div class="col-sm-7">
                                                                                <input type="number" required value="0.00" maxlength="2" step="any" class="form-control form-control-xxs rounded-0" name="discount" id="discount-amount" placeholder="0.00">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-sm-12">
                                                                        <div class="form-group row">
                                                                            <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.table_net_cost')}} <span class="text-danger"></span></label>
                                                                            <div class="col-sm-7">
                                                                                <input type="number" required step="any" readonly class="form-control bg-white form-control-xxs rounded-0" name="gross_total" id="net-amount" placeholder="0.00">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-sm-12 bg-light px-0 pt-2">
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.pay_type')}} <span class="text-danger">*</span></label>
                                                                                <div class="col-sm-7">
                                                                                    <select class="form-control form-control-xxs select2_ rounded-0 py-0" name="pay_type" id="pay_type" style=" width: 100% !important;">
                                                                                        <option value="1">{{__('invoice.cash_paid')}}</option>
                                                                                        <option value="2">{{__('invoice.bank_paid')}}</option>
                                                                                        <option value="3">{{__('invoice.cash_paid')}} + {{__('invoice.bank_paid')}}</option>
                                                                                    </select>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.table_paid')}} <small class="text-info">({{__('invoice.cash_paid')}})</small></label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="number" required step="any" value="0.00" class="form-control form-control-xxs rounded-0" name="deposit" id="paid-amount" placeholder="0.00">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.table_paid')}} <small class="text-info">({{__('invoice.bank_paid')}})</small></label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="number" required step="any" value="0.00" class="form-control form-control-xxs rounded-0" name="bank_deposit" id="bank-amount" placeholder="0.00">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.form_paid_date')}} <span class="text-danger">*</span></label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="datetime-local" value="{{date('Y-m-d\TH:i:s')}}" class="form-control form-control-xxs rounded-0" name="first_paid_date" id="paid-date" placeholder="DD-MM-YYYY">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.bank_name')}}</label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="text" value="" class="form-control form-control-xxs rounded-0" name="bank_name" id="bank_name">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.transaction_no')}}</label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="text" value="" class="form-control form-control-xxs rounded-0" name="transaction_ref" id="transaction_ref">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.form_owe_amount')}} <span class="text-danger">*</span></label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="number" readonly step="any" class="form-control bg-white form-control-xxs rounded-0" name="balance" id="owe-amount" placeholder="0.00">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="row">
                                                            <div class="col-lg-12 pt-4 text-right">
                                                                <button class="btn btn-inverse-success mr-2" name="save_print_invoice" type="submit" value="save_preview_invoice"><i class="mdi mdi-printer"></i> {{__('invoice.form_btn_save_preview')}}</button>
                                                                <button class="btn btn-info" type="submit"><i class="mdi mdi-content-save"></i> {{__('vaccination.btn_save')}}</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal Patient -->
            <div class="modal fade modal-primary" id="modal-patient">
                <div class="modal-dialog show modal-semi-xxl">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h6 class="modal-title">{{__('patient.form_add_title')}}</h6>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true" class="mdi mdi-close"></span></button>
                        </div>

                        <div class="modal-body">
                            <form method="post" action="#" id="form" onkeydown="return event.key != 'Enter';">
                                @csrf
                                <input type="hidden" class="form-control" name="uid" id="data-id" value="0" />
                                <div class="form-vertical">

                                    <div class="row">
                                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-6 px-3">

                                            <div class="form-group mb-1">
                                                <label for="patient-code">{{__('patient.form_code')}} <span class="text-danger">*</span></label>
                                                <div class="input-group">
                                                    <input type="text" class="form-control" {{$labSettings->patient_code == 1 ? ' disabled readonly ' : ''}} name="patient_code" id="patient-code" placeholder="{{__('patient.form_code')}}">
                                                    <div class="input-group-append">
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="form-group mb-1">
                                                <label for="lab-name-en">{{__('patient.form_name')}} <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="patient_name" id="patient-name" placeholder="{{__('patient.form_name')}}">
                                            </div>
                                            <div class="form-group mb-1">
                                                <label for="lab-name-kh">{{__('patient.form_dob')}} <span class="text-danger">*</span></label>
                                                <div class="input-group">
                                                    <div class="input-group-append mr-3" style="flex: 5 !important;">
                                                        <input class="form-control datepicker" name="dob" type="text" id="dob" placeholder="{{__('general.date_placeholder')}}" required="" autocomplete="off">
                                                    </div>
                                                    <input class="form-control" name="year" onkeypress="return isNumber(event);" maxlength="2" type="text" id="year" autocomplete="off">
                                                    <div class="input-group-append" style="">
                                                        <button class="btn btn-sm btn-light" disabled type="button">{{__('patient_type.form_input_year')}}</button>
                                                    </div>

                                                    <input class="form-control" name="month" onkeypress="return isNumber(event);" maxlength="2" type="text" id="month" autocomplete="off">
                                                    <div class="input-group-append" style="">
                                                        <button class="btn btn-sm btn-light" disabled type="button">{{__('patient_type.form_input_month')}}</button>
                                                    </div>

                                                    <input class="form-control" name="month" onkeypress="return isNumber(event);" maxlength="2" type="text" id="day" autocomplete="off">
                                                    <div class="input-group-append" style="">
                                                        <button class="btn btn-sm btn-light" disabled type="button">{{__('patient_type.form_input_day')}}</button>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="form-group mb-1">
                                                <label for="lab-name-en">{{__('patient.form_gender')}} <span class="text-danger">*</span></label>
                                                <div class="form-group pl-3">
                                                    <div class="row">
                                                        <div class="form-check col-sm-12 col-md-12 col-lg-3" style="margin-bottom: 6px !important;">
                                                            <label class="form-check-label">
                                                                <input type="radio" class="form-check-input" checked name="gender" data-id="1" value="1">
                                                                {{__('patient.form_sex_male')}}
                                                            </label>
                                                        </div>
                                                        <div class="form-check col-sm-12 col-md-12 col-lg-3" style="margin-bottom: 6px !important;">
                                                            <label class="form-check-label">
                                                                <input type="radio" class="form-check-input" name="gender" data-id="2" value="2"> {{__('patient.form_sex_female')}}
                                                            </label>
                                                        </div>
                                                        <div class="form-check col-sm-12 col-md-12 col-lg-3" style="margin-bottom: 6px !important;">
                                                            <label class="form-check-label">
                                                                <input type="radio" class="form-check-input" name="gender" data-id="3" value="3"> {{__('patient.form_sex_other')}}
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="form-group mb-1">
                                                <label for="lab-name-en">{{__('patient.form_khid')}}</label>
                                                <input type="text" class="form-control" name="khid_number" id="khid-number" placeholder="{{__('patient.form_khid')}}">
                                            </div>
                                            <div class="form-group mb-1">
                                                <label for="lab-name-en">{{__('patient.form_phone')}}</label>
                                                <input type="text" class="form-control" name="phone_number" id="phone-number" placeholder="{{__('patient.form_phone')}}">
                                            </div>

                                        </div>
                                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-6 px-3">
                                            <div class="form-group mb-1">
                                                <label for="lab-name-en">{{__('patient.form_house')}}</label>
                                                <input type="text" class="form-control" name="house_number" id="house-number" placeholder="{{__('patient.form_house')}}">
                                            </div>
                                            <div class="form-group mb-1">
                                                <label for="lab-name-en">{{__('patient.form_street')}}</label>
                                                <input type="text" class="form-control" name="street_number" id="street-number" placeholder="{{__('patient.form_street')}}">
                                            </div>

                                            <div class="form-group mb-1">
                                                <label for="lab-name-en">{{__('patient.form_province')}} </label>
                                                <select class="form-control select2" name="province_id" id="province-id" style="width: 100% !important;">
                                                    <option></option>
                                                    @foreach($provinces as $province)
                                                        <option value="{{$province->id}}">{{$province->name_en}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div class="form-group mb-1">
                                                <label for="lab-name-en">{{__('patient.form_district')}}</label>
                                                <select class="form-control select2" name="district_id" id="district-id" style="width: 100% !important;">
                                                </select>
                                            </div>
                                            <div class="form-group mb-1">
                                                <label for="lab-name-en">{{__('patient.form_commune')}}</label>
                                                <select class="form-control select2" name="commune_id" id="commune-id" style="width: 100% !important;">
                                                </select>
                                            </div>
                                            <div class="form-group mb-1">
                                                <label for="lab-name-en">{{__('patient.form_village')}}</label>
                                                <select class="form-control select2" name="village_id" id="village-id" style="width: 100% !important;">
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-info" id="savePatient"><i class="fa fa-floppy-o"></i>&nbsp;&nbsp;<span class="save">{{__('lang.save')}}</span><span class="update" style="display: none">{{__('lang.update')}}</span></button>
                            <button type="button" class="btn btn-light" data-dismiss='modal'>{{__('lang.cancel')}}</button>
                        </div>
                    </div>
                </div>
            </div>

            @include('layout.footer')
        </div>
    </div>
</div>
@include('layout.common_script')
<script>


    var patient_base_url = "{{url('patient')}}";
    var get_refs_base_url = "{{url('refs')}}";

    $(function(){
        var message = '{!! session('message') !!}';
        if(message=='success')
        {
            alertify.success("@lang('vaccination.create_success')");
        }
        if(message=='error')
        {
            alertify.error("@lang('vaccination.create_fail')");
        }

    });

</script>

<script src="{{url(env("APP_URL").'storage/assets/libs/moment/moment.js')}}"></script>
<script src="{{url(env("APP_URL").'storage/assets/libs/moment/moment-precise-range.js')}}"></script>
<script>

    $(document).on('change','.vaccine-item',  function () {
        let unit_price = $('option:selected', this).attr('data-price');
        let quantity = $(this).closest('tr').find('.quantity').val();
        let total = unit_price * quantity
        $(this).closest('tr').find('.unit-price').val(unit_price);
        $(this).closest('tr').find('.sub-total').val(total);
        calculateVaccineData();
    })

    $(document).on('change','#vaccination-item .unit-price, #vaccination-item .quantity',  function () {
        calculateVaccineData();
    })

    $(document).on('click','.btn-remove-vaccine-item', function () {
        if($('#vaccination-item tr').length>1){
            $(this).closest('tr').remove()
        }
        calculateVaccineData();
    })

    $('#btn-add-new-med-item').click(function () {
        var $tr    = $('#vaccination-item').find('tr:last');
        var $clone = $tr.clone();
        $clone.find('td:eq(0) span').remove()
        $clone.find('.unit-price').val(0);
        $clone.find('.quantity').val(1);
        $clone.find('.vaccine-item').val('');
        $clone.find('.sub-total').val(0);
        $clone.find('.sub-total-to-display').val(0);
        $('#vaccination-item').append($clone)

        $(".select2").select2({
            placeholder: '',
            allowClear: true,
        });
    })

    function calculateVaccineData() {
        let total_amt = 0;
        $('#vaccination-item').find('tr').each(function () {
            let unit_price = $(this).find('.unit-price').val()
            let quantity = $(this).find('.quantity').val()
            let total = unit_price * quantity
            $(this).closest('tr').find('.sub-total').val(total)
            $(this).closest('tr').find('.sub-total-to-display').val(total.toFixed(2))
            total_amt +=total
        })
        $('#total-amount').val(total_amt)
        let discount_amt =$('#discount-amount').val()
        $('#net-amount').val((total_amt * (1-(discount_amt/100))).toFixed(2))
        $('#owe-amount').val((total_amt * (1-(discount_amt/100))).toFixed(2))
    }

    $('#discount-amount').change(function () {
        if($('#discount-amount').val()>100) $('#discount-amount').val(100)
        calculateVaccineData()
    })

    $('#paid-amount, #bank-amount').keyup(function () {
        let own_amount = parseFloat($('#net-amount').val()) - (parseFloat( $('#paid-amount').val()) + parseFloat( $('#bank-amount').val()) )
        $('#owe-amount').val(toFixedNumber(own_amount,2))
    });

    function searchPatientToForm(patientElementId){
        Swal.fire({
            html:"<p style='text-align: left;'>Search the patient with their name, phone, Khmer ID, or patient ID</p>",
            input: "text",
            showCancelButton: !0,
            confirmButtonText: "<i class='fa fa-search mr-2'></i>Search",
            cancelButtonText: "Close",
            position: 'top',
            showLoaderOnConfirm: !1,
            confirmButtonColor: "#4fb51a",
            preConfirm: function (n) {
                return new Promise(function (t) {
                    $.ajax({
                        url: patient_base_url + "/async",
                        method:'get',
                        dataType:'json',
                        data:{kword: n},
                        success:function(response)
                        {
                            if(response.data.length<1 || !response.success){
                                Swal.showValidationMessage('No patient found!')
                                Swal.enableButtons()
                            }
                            else {
                                t(response.data)
                            }
                        }
                    })
                })
            },
            allowOutsideClick:!1,
        }).then(function (t) {
            if(!t.dismiss){
                $('#'+patientElementId).html('');
                t.value.map(item =>{
                    var patientOption = document.createElement('OPTION');
                    patientOption.setAttribute('value',item.id);
                    patientOption.text = item.patient_uuid + ' - ' + item.name_en;
                    $('#'+patientElementId).append(patientOption);
                })
            }
        })
    }

    $("#searchPatientAddForm").click(function () {
        searchPatientToForm('patient-id')
    });

</script>

<script>
    function calculateAge(dob, current_date) {
        dob          = moment(dob);
        current_date = current_date ? moment(current_date) : moment();
        return moment.preciseDiff(dob, current_date, true)
    }

    var $patient_info_form		= $("#modal-patient");
    $patient_info_form.find("#dob").on("change", function() {
        var dob_split = $(this).val().split("-")
        var dob = new Date(dob_split[1]+'-'+dob_split[0]+'-'+dob_split[2]);

        if (dob) {
            current_date =  moment();
            var age = calculateAge(dob);
            $patient_info_form.find("#year").val(age.years);
            $patient_info_form.find("#month").val(age.months);
            var days = age.days === 0 && age.months === 0 && age.years === 0 ? 1 : age.days;
            $patient_info_form.find("#day").val(days);
        }
    });

    $patient_info_form.on("keyup change", "#year, #month, #day", function (evt) {
        var years  = $patient_info_form.find("#year").val() || 0;
        var months = $patient_info_form.find("#month").val() || 0;
        var days   = $patient_info_form.find("#day").val() || 0;
        var dob = moment();
        dob.subtract(days, 'days');
        dob.subtract(months, 'months');
        dob.subtract(years, 'years');
        var dob_split = dob.toDate().toLocaleDateString().split("/")
        var dob = dob_split[1].padStart(2,"0")+'-'+dob_split[0].padStart(2,"0")+'-'+dob_split[2];
        $patient_info_form.find("#dob").val(dob);
    });


    $('#province-id').change(function () {
        getDistrictsByProvinceId('district-id', $(this).val())
    })

    $('#district-id').change(function () {
        getCommunesByDistrictId('commune-id', $(this).val())
    })

    $('#commune-id').change(function () {
        getVillagesByCommuneId('village-id', $(this).val())
    })


    $("#savePatient").on('click',function(e){
        e.preventDefault();
        $.ajax({
            url: patient_base_url.toString()+'.save',
            type:"POST",
            dataType:"JSON",
            data :{
                "_token": csrf_token,
                name_en: $('#patient-name').val(),
                patient_uuid: $('#patient-code').val(),
                dob: $('#dob').val(),
                gender: $("input[name='gender']:checked").attr('data-id'),
                marital_status: $("input[name='marital_status']:checked").attr('data-id'),
                phone_number: $('#phone-number').val(),
                province_id: $('#province-id').val(),
                district_id : $('#district-id').val(),
                commune_id: $('#commune-id').val(),
                village_id: $('#village-id').val(),
                khid_number: $('#khid-number').val(),
                house_number: $('#house-number').val(),
                street_number: $('#street-number').val()
            },
            success:function(res){
                if(res.success){
                    var patient = res.data
                    var patientOption = document.createElement('OPTION');
                    patientOption.setAttribute('value',patient.id);
                    patientOption.setAttribute('selected','selected');
                    patientOption.text = patient.patient_uuid + ' - ' + patient.name_en;
                    $('#patient-id').append(patientOption);

                    $('#modal-patient .close').click();
                    $('#patient-id').trigger('change')

                }else{
                    alertify.error("Can't create patient.")
                }
            }
        });
    });


</script>

</body>

</html>

