<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    @include('layout.header')
</head>
<body>
<div class="row" id="x" style="display: none;">
    <div class="col-12">
      <span class="d-flex align-items-center purchase-popup">
        <i class="typcn typcn-delete-outline" id="bannerClose"></i>
      </span>
    </div>
</div>
<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">
                            <div class="card-body">
                                <h4 class="card-title"><i class="mdi mdi-dots-vertical menu-icon"></i> {{__('sidebar.appointment')}}</h4>
                                <div class="row">
                                    <div class="col-sm-12">

                                        <form method="get" action="{{url('appointment/search')}}">
                                            <div class="row">
                                                <div class="col-sm-7">
                                                    <div class="form-group">
                                                        <div class="input-group">
                                                            <input type="date" value="{{isset($_GET['appointment_date']) ? $_GET['appointment_date']  : ''}}" class="form-control rounded-top-left-25 rounded-bottom-left-25 rounded-right-0" name="appointment_date">
                                                            <div class="input-group-append">
                                                                <button class="btn btn-sm btn-inverse-secondary px-3 rounded-top-right-25 rounded-bottom-right-25" type="submit"><i class="fa fa-search"></i> {{__('general.btn_search')}}</button>
                                                                @if(\App\Http\Controllers\Helper\GlobalController::user_can(Auth::user()->role_id, ['create_appointment']))
                                                                    <button class="btn btn-sm btn-inverse-success rounded-25 waves-effect px-3 ml-3" type="button" data-action="new" data-toggle="modal" data-target="#modal-appointment" data-backdrop="static"><i class="typcn typcn-plus"></i> {{__('general.btn_add_new')}}</button>
                                                                @endif
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </form>
                                        <hr class="my-3 d-none">

                                        <div class="col-sm-12 p-0 mb-1 mt-3">
                                            <div class="table-responsive">
                                                <table class="table table-bordered table-striped table-hover" id="quantity_dt">
                                                    <thead>
                                                    <tr class="bg-gradient-light">
                                                        <th class="py-2" width="50px">{{__('comment.table_no')}}</th>
                                                        <th class="py-2 text-center" width="100px">{{__('comment.table_action')}}</th>
                                                        <th class="py-2">{{__('appointment.patient')}}</th>
                                                        <th class="py-2">{{__('appointment.date')}}</th>
                                                        <th class="py-2">{{__('appointment.type')}}</th>
                                                        <th class="py-2">{{__('appointment.doctor')}}</th>
                                                        <th class="py-2">{{__('appointment.description')}}</th>
                                                    </tr>
                                                    </thead>
                                                    <tbody>
                                                    @foreach($appointments as $k=>$appointment)
                                                        <tr>
                                                            <td class="py-2 text-center">{{($k+1) + (($_GET['page'] ?? 1) * 20) - 20}}</td>
                                                            <td class="py-1 text-center">
                                                                <div class="btn-group" role="group" aria-label="Basic example" >
                                                                    @if(\App\Http\Controllers\Helper\GlobalController::user_can(Auth::user()->role_id, ['create_sample']))
                                                                        <a href="{{url('sample/patient/'.$appointment->patient->id)}}/new" class="btn btn-sm btn-inverse-success mr-2 pt-1" title="{{__('sample.form_btn_new_sample')}}"><i class="mdi mdi-test-tube"></i> <i class="mdi mdi-plus" style="margin-left: -10px;"></i></a>
                                                                    @endif
                                                                    @if(\App\Http\Controllers\Helper\GlobalController::user_can(Auth::user()->role_id, ['update_appointment']))
                                                                        <button type="button" class="btn btn-sm btn-inverse-info mr-2" title="{{__('general.btn_edit')}}" data-action="edit" data-uid="{{$appointment->id}}" data-toggle="modal" data-target="#modal-appointment" data-backdrop="static">
                                                                            <i class="typcn typcn-edit"></i>
                                                                        </button>
                                                                    @endif
                                                                    @if(\App\Http\Controllers\Helper\GlobalController::user_can(Auth::user()->role_id, ['delete_appointment']))
                                                                        <button type="button" class="btn btn-sm btn-inverse-danger " title="{{__('general.btn_delete')}}" onclick="delete_data({{$appointment->id}})"><i class="mdi mdi-close-circle"></i></button>
                                                                    @endif
                                                                </div>
                                                            </td>
                                                            <td class="py-2">{{$appointment->patient->name_en . ' - ' .$appointment->patient->phone_number}}</td>
                                                            <td class="py-2">{{date('d-M-Y h:i A', strtotime($appointment->appointment_date))}}</td>
                                                            <td class="py-1">{{$appointment->appointment_type}}</td>
                                                            <td class="py-1">{{$appointment->doctor->name_en ?? ''}}</td>
                                                            <td class="py-1">{{$appointment->description}}</td>
                                                        </tr>
                                                    @endforeach
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>

                                        <div class="float-right mt-3">
                                            {!! $appointments->appends($_GET)->links('pagination.custom') !!}
                                        </div>

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

                </div>
            </div>

            @include('modal.appointment')

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

<script>

    let base_url = "{{url('appointment')}}";

    $('#patient-id').select2({
        tags: false,
        allowClear: true,
        ajax: {
            url: '{{url('patient/live-search')}}',
            dataType: 'json',
            delay: 10
        }
    });

    $("#btnSaveAppointment").on('click',function(e){
        e.preventDefault();
        data_id = $('#data-id').val();
        let url = base_url.toString() + (data_id < 1 ? '/save' : '/update').toString();
        $.ajax({
            url: url,
            type:"POST",
            data :{
                "_token": csrf_token,
                uid : data_id,
                patient_id: $('#patient-id').val(),
                appointment_type: $('#appointment_type').val(),
                appointment_date: $('#appointment_date').val(),
                doctor_id: $('#doctor_id').val(),
                description : $('#description').val()
            },
            success:function(res){
                handleMessage(res.success, res.message)
                if(res.success) setTimeout(function () {location.reload()}, messageDuration)
            }
        });
    });

    function delete_data(uid){
        Swal.fire({
            text: confirm_delete_record,
            icon: 'question',
            showCancelButton: true,
            cancelButtonClass:'danger',
            confirmButtonText: confirm_ok_delete,
            cancelButtonText: confirm_cancel
        }).then((result) => {
            if (result.value) {
                $.ajax({
                    url: base_url.toString() + '/delete',
                    method:'POST',
                    data:{
                        "_token": csrf_token,
                        uid : uid,
                    },
                    success:function(res){
                        handleMessage(res.success, res.message)
                        if(res.success) setTimeout(function () {location.reload()}, messageDuration)
                    }
                })

            }
        });
    }

    $('#modal-appointment').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget) // Button that triggered the modal
        var action = button.data('action') // Extract info from data-* attributes
        var modal = $(this);
        $('#comment-desc').val("");
        if(action === "new"){
            // Clear inputs
            modal.find('.modal-body input[name="uid"]').val(0);
            modal.find('.modal-body select[name="patient_id"]').val('').trigger('change')
            modal.find('.modal-body select[name="appointment_type"]').val('').trigger('change')
            modal.find('.modal-body select[name="doctor_id"]').val('').trigger('change')
            $('#description').val('')
        }else if(action === "edit"){
            uid = button.data('uid');
            modal.find('.modal-body input[name="uid"]').val(uid);
            $.ajax({
                url: base_url.toString() + '/get',
                type:"POST",
                data:{
                    "_token": csrf_token,
                    uid: uid,
                },
                success:function(res){
                    let data = res.data;
                    modal.find('.modal-body select[name="patient_id"]').val(data.patient_id).trigger('change');
                    modal.find('.modal-body select[name="appointment_type"]').val(data.appointment_type).trigger('change');
                    modal.find('.modal-body select[name="doctor_id"]').val(data.doctor_id).trigger('change');
                    modal.find('.modal-body input[name="appointment_date"]').val(data.appointment_date);
                    $('#description').val(data.description)
                    if(!res.success) handleMessage(res.success, res.message)
                }
            });
        }
    })


    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>

</body>

</html>

