@include('header')
@php
$UserId = Session::get('UserId');
@endphp
<style>
    a{
        color:black;
    }
    /* .table-bordered th, .table-bordered td {
    border: 1px solid rgb(24 28 33);
} */
.style2 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 18px;
	color: #FFFFFF;
	font-weight: bold;
}

.autocomplete-list2 {
          border: 1px solid #ccc;
          max-height: 150px;
          overflow-y: auto;
          position: absolute;
          background-color: white;
          z-index: 1000;
          width: 100%;
          margin-top: 35px;
        }

.autocomplete-list {
          border: 1px solid #ccc;
          max-height: 150px;
          overflow-y: auto;
          position: absolute;
          background-color: white;
          z-index: 1000;
          width: 100%;
        }
    
        .autocomplete-item {
          padding: 8px;
          cursor: pointer;
        }
    
        .autocomplete-item:hover,
        .autocomplete-item.active {
          background-color: #98e6ed;
        }
        
        .form-group,
.col-md-1,
.col-md-2,
.col-md-3,
.col-md-4,
.col-md-5,
.col-md-6,
.col-md-7,
.col-md-8,
.col-md-9,
.col-md-10,
.col-md-11,
.col-md-12{
    margin-bottom: 12px; /* gap between rows */
}

    </style>
    
<input type="hidden" id="NewMrdNo" value="{{$NewMrdNo}}">
<div class="container-fluid flex-grow-1 container-p-y">
    <div class="row">
        <!-- customar project  start -->
        <div class="col-xl-12">
            <div class="card">
                <div class="card-body">

                    
                        <div class="form-row">


                        <table width="100%" border="0" cellspacing="2" cellpadding="2">
  <tr>
    <td width="10%" height="55" rowspan="2" align="center" valign="top" onclick="refreshQueue()" style="cursor: pointer;"><img src="innerlogo.jpg" width="75" height="86" /></td>
    <td align="left" valign="top"><table width="100%" height="10%" border="0" cellspacing="8" cellpadding="2">
      <tr>
        <td width="10%"> <div class="input-group">
                                <input type="text" oninput="getPatientVal()" id="TopMrdNo" class="form-control" placeholder="Mrd No">
                               
                            </div></td>

                            <td width="50%"> <div class="input-group">
                                <input type="text" id="TopPatientName" class="form-control" placeholder="Patient Name">
                                <div id="autocomplete-list2" class="autocomplete-list2" style="display: none; position: absolute;"></div>
                            </div></td>

        <td width="10%" align="center" valign="top" bgcolor="#4FAFB8" style="padding-top: 5px;"><a class="style2" data-toggle="modal"
                                            data-target="#modal-report" id="add_button" style="color:white;cursor: pointer;"> <i
                                                class="feather icon-plus"></i>New Patient </a></td>
                                                <td></td>
        <td width="10%" align="center" valign="top" bgcolor="#416E6E" style="padding-top: 5px;cursor: pointer;" onclick="todayPatientLists(1)"><span class="style2" id="totalPatient">Total : &nbsp; {{$totalPatient}}</span></td>
        <td></td>
        <td width="10%" align="center" valign="top" bgcolor="#416E6E" style="padding-top: 5px;cursor: pointer;" onclick="todayPatientLists(2)"><span class="style2" id="totalChecked">Check : &nbsp; {{$totalCheckPatient}}</span></td>
        <td></td>
        <td width="10%" align="center" valign="top" bgcolor="#416E6E" style="padding-top: 5px;cursor: pointer;" onclick="todayPatientLists(3)"><span class="style2" id="totalUnchecked">Uncheck : &nbsp;{{$totalUncheckPatient}}</span></td>
      </tr>
    </table></td>
  </tr>
  <tr>
    <td align="left" valign="top">&nbsp;</td>
  </tr>
</table>
                        

                            <!-- <div class="form-group">
                           
                                            <div class="input-group">
                                                <input type="text" id="TopMrdNo" oninput="getPatientVal()" class="form-control" placeholder="Mrd No">
                                                <span class="input-group-append">
                                                    <button class="btn btn-secondary" type="button" data-toggle="modal"
                                            data-target="#modal-ptlist">List</button>
                                                </span>
                                            </div>
                                        </div>

                            <div class="form-group col-md-6">
                                <div class="row" style="padding-left: 50px;">
                                    <div class="col-sm-5 text-left">
                                        <button class="btn btn-success btn-sm mb-3 btn-round" data-toggle="modal"
                                            data-target="#modal-report" id="add_button"><i
                                                class="feather icon-plus"></i> New
                                            Patient</button>

                                            <button class="btn btn-info btn-sm mb-3 btn-round" onclick="refreshQueue()"><i
                                                class="feather icon-refresh-cw"></i> Refresh</button>
                                    </div>


                                    <div class="col-sm-7 text-right">
                                        <a href="javascript:void(0)" class="badge badge-pill badge-danger"
                                            style="font-size:20px;" id="totalPatient">Tot :
                                            {{$totalPatient}}</a>
                                        <a href="javascript:void(0)" class="badge badge-pill badge-success"
                                            style="font-size:20px;" id="totalChecked">Chk : {{$totalCheckPatient}}</a>
                                        <a href="javascript:void(0)" class="badge badge-pill badge-info"
                                            style="font-size:20px;" id="totalUnchecked">Un
                                            Chk : {{$totalUncheckPatient}}</a>
                                    </div>
                                </div>

                            </div> -->
                        </div>
                        <form id="validation-form2" novalidate="novalidate" method="POST" enctype="multipart/form-data"
                        autocomplete="off" action="" name="myForm" onsubmit="return validation(this);">
                        <input type="hidden" name="action" value="SaveOldQueue">

                        @csrf
                        <div class="form-row">
                            <div class="form-group col-md-1 showoldfields" style="display:none;">
                                <label class="floating-label" for="Name">Mrd No <span
                                        class="text-danger">*</span></label>
                                <input type="text" id="MRD_NO" name="MRD_NO" class="form-control" value="" readonly="">
                                <div class="clearfix"></div>
                            </div>

                            <div class="form-group col-md-2 showoldfields" style="display:none;">
                                <label class="floating-label" for="Name">Patient Name <span
                                        class="text-danger">*</span></label>
                                <input type="text" id="PatientName" name="PatientName" class="form-control"
                                    placeholder="" readonly="">
                                <div class="clearfix"></div>
                            </div>
                          
                            <div class="form-group col-md-1 showoldfields" style="display:none;">
                                <label class="floating-label" for="Name">Age <span class="text-danger">*</span></label>
                                <input type="text" id="PatientAge" name="PatientAge" class="form-control" placeholder=""
                                    required>
                                <div class="clearfix"></div>
                            </div>

                            <div class="form-group col-md-1 showoldfields" style="display:none;">
                                <label class="floating-label" for="gender">Gender <span
                                        class="text-danger">*</span></label>
                                <select class="form-control" id="PatGender" name="PatGender" required>
                                    <option value="" disabled="" selected="">Select Gender</option>
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                </select>
                            </div>

                            <div class="form-group col-md-3 showoldfields" style="display:none;">
                                <label class="floating-label" for="Name">Address <span
                                        class="text-danger">*</span></label>
                                <input type="text" id="PatientAddress" name="PatientAddress" class="form-control"
                                    placeholder="">
                                <div class="clearfix"></div>
                            </div>

                            <div class="form-group col-md-1 showoldfields" style="display:none;">
                                <label class="floating-label" for="gender">Type</label>
                                <select class="form-control" id="OpdType" name="OpdType">
                                   
                                    <option value="1" selected="">OPD</option>
                                    <option value="2">Appointment</option>
                                   
                                </select>
                            </div> 


                            

                            

                            <div class="form-group col-md-2 showoldfields" style="display:none;">
                                <label class="floating-label" for="gender">Consultant Name <span
                                    class="text-danger">*</span></label>
                                <select class="form-control" id="PatConsultant" name="Consultant" required>
                                    <option value="" selected>...</option>
                                   @foreach($consultantList as $consultant)
                                    <option value="{{$consultant->id}}">{{$consultant->Name}}</option>
                                    @endforeach
                                   
                                   
                                </select>
                            </div> 



                            <div class="form-group col-md-1 showoldfields" style="display:none;">
                                <label class="floating-label" for="Name">Fees <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Rs.</span>
                                    </div>
                                    <input type="text" list="Feeslist" class="form-control" name="Fees" id="ConsFees"
                                        onKeyPress="return isNumberKey(event)" value="" required @if($UserId != 58) readonly @endif>
                                    <datalist id="Feeslist">

                                        <option value="400">
                                        <option value="100">
                                        <option value="600">
                                        <option value="0">

                                    </datalist>

                                    <div class="clearfix"></div>
                                </div>
                            </div>

                            <input type="hidden" id="PayMode" name="PayMode" value="Cash">

                            <!-- <div class="form-group col-md-1 showoldfields" style="display:none;">
                                <label class="floating-label" for="gender">Pay Mode</label>
                                <select class="form-control" id="PayMode" name="PayMode">
                                    <option value="" disabled="" selected="">Select Payment Mode</option> 
                                    <option value="Cash" selected="">Cash</option>
                                    <option value="Coupon">Coupon</option>
                                    <option value="Mobile Payment">Mobile Payment</option> 
                                </select>
                            </div> -->

                           
                            
                            <div class="form-group col-md-2 showoldfields" style="display:none;">
                                <label class="floating-label" for="gender">Previous Visit Date <span
                                    class="text-danger">*</span></label>
                               <input type="date" id="PrevVisitDate" class="form-control" placeholder=""
                                    readonly>
                                <div class="clearfix"></div>
                            </div> 

                            <div class="form-group col-md-1 showoldfields" style="display:none;">
                                <label class="floating-label" for="gender">Total Days <span
                                    class="text-danger">*</span></label>
                                <input type="text" id="TotDays" class="form-control" placeholder=""
                                    readonly>
                            </div> 

                             <div class="form-group col-md-1 showoldfields" style="display:none;">
            <label class="floating-label">Weight (kg)</label>
            <input type="text" id="Weight" name="Weight" class="form-control"
                   onkeypress="return isNumberKey(event)">
        </div>

        <div class="form-group col-md-1 showoldfields" style="display:none;">
            <label class="floating-label">Height (cm)</label>
            <input type="text" id="Height" name="Height" class="form-control"
                   onkeypress="return isNumberKey(event)">
        </div>

        <div class="form-group col-md-1 showoldfields" style="display:none;">
            <label class="floating-label">Temp (°C)</label>
            <input type="text" id="Temp" name="Temp" class="form-control"
                   onkeypress="return isNumberKey(event)">
        </div>

                            <div class="form-group col-md-4 showoldfields" style="display:none;padding-top:20px;">
                                <button type="submit" id="submit2" class="btn btn-primary btn-finish">Add In
                                    Queue</button>
                                <button type="button" id="prevsumbtn" class="btn btn-success btn-finish"
                                    onclick="viewOpdDetails()">View Prev Summary</button>
                            </div>
                        </div>
                        <input type="hidden" id="visitno">
                    </form>
                    <hr>


                    <input type="hidden" id="CurrDate" value="{{date('Y-m-d')}}">
                    <button type="button" class="btn btn-secondary" id="please_wait" disabled style="text-align: center;display:none;"><span class="spinner-border spinner-border-sm" role="status"></span> &nbsp;Please Wait</button>
                    <div class="table-responsive" id="custresult">



                    </div>
                </div>
            </div>
        </div>
        <!-- customar project  end -->
    </div>
</div>

@include('opd/incnewpatient')
@include('opd/incqueuepatient')
@include('opd/incoldpatientlistmodal')
@include('footerscript')
<script type="text/javascript">

let currentFocus = -1;

    $(document).ready(function () {
        $("#RefBy").on("input", function () {
            let RefBy = $(this).val();

            if (RefBy.length === 0) {
                $("#autocomplete-list").hide();
                return;
            }

            $.ajax({
                url: "{{ url('getRefList') }}",
                method: "POST",
                data: {
                    _token: '{{ csrf_token() }}',
                    RefBy: RefBy
                },
                success: function (data) {
                    $("#autocomplete-list").empty().show();
                    currentFocus = -1;

                    if (data.length === 0) {
                        $("#autocomplete-list").hide();
                        return;
                    }

                    data.forEach(function (item) {
                        $("#autocomplete-list").append(`<div class="autocomplete-item">${item}</div>`);
                    });

                    $(".autocomplete-item").on("click", function () {
                        $("#RefBy").val($(this).text());
                        $("#autocomplete-list").hide();
                    });
                }
            });
        });

        $("#RefBy").on("keydown", function (e) {
            let items = $(".autocomplete-item");

            if (e.key === "ArrowDown") {
                currentFocus++;
                if (currentFocus >= items.length) currentFocus = 0;
                setActive(items);
                e.preventDefault();
            } else if (e.key === "ArrowUp") {
                currentFocus--;
                if (currentFocus < 0) currentFocus = items.length - 1;
                setActive(items);
                e.preventDefault();
            } else if (e.key === "Enter") {
                e.preventDefault();
                if (currentFocus > -1 && items[currentFocus]) {
                    items.eq(currentFocus).click();
                }
            }
        });

        function setActive(items) {
            items.removeClass("active");
            if (currentFocus >= 0 && currentFocus < items.length) {
                items.eq(currentFocus).addClass("active");
                items.eq(currentFocus)[0].scrollIntoView({ block: "nearest" });
            }
        }

        $(document).click(function (e) {
            if (!$(e.target).closest("#RefBy, #autocomplete-list").length) {
                $("#autocomplete-list").hide();
            }
        });
   


    let currentFocus2 = -1;

        $("#TopPatientName").on("input", function () {
            let TopPatientName = $(this).val();

            if (TopPatientName.length === 0) {
                $("#autocomplete-list2").hide();
                return;
            }

            $.ajax({
                url: "{{ url('getSearchPatientList') }}",
                method: "POST",
                data: {
                    _token: '{{ csrf_token() }}',
                    TopPatientName: TopPatientName
                },
                success: function (data) {
                    $("#autocomplete-list2").empty().show();
                    currentFocus2 = -1;

                    if (data.length === 0) {
                        $("#autocomplete-list2").hide();
                        return;
                    }

                    data.forEach(function (item) {
                        $("#autocomplete-list2").append(`<div class="autocomplete-item" onclick="getPatientVal2('${item.MrdNo}')">${item.PatientNameFull}</div>`);
                    });

                    $(".autocomplete-item").on("click", function () {
                        $("#TopPatientName").val($(this).text());
                        $("#autocomplete-list2").hide();
                    });
                }
            });
        });

        $("#TopPatientName").on("keydown", function (e) {
            let items = $(".autocomplete-item");

            if (e.key === "ArrowDown") {
                currentFocus2++;
                if (currentFocus2 >= items.length) currentFocus2 = 0;
                setActive(items);
                e.preventDefault();
            } else if (e.key === "ArrowUp") {
                currentFocus2--;
                if (currentFocus2 < 0) currentFocus2 = items.length - 1;
                setActive(items);
                e.preventDefault();
            } else if (e.key === "Enter") {
                e.preventDefault();
                if (currentFocus2 > -1 && items[currentFocus2]) {
                    items.eq(currentFocus2).click();
                }
            }
        });

        function setActive(items) {
            items.removeClass("active");
            if (currentFocus2 >= 0 && currentFocus2 < items.length) {
                items.eq(currentFocus2).addClass("active");
                items.eq(currentFocus2)[0].scrollIntoView({ block: "nearest" });
            }
        }

        $(document).click(function (e) {
            if (!$(e.target).closest("#TopPatientName, #autocomplete-list2").length) {
                $("#autocomplete-list2").hide();
            }
        });
    });

    function getGender(val){
    if(val == 'Mr.' || val == 'Master'){
        $('#Gender').val('Male').attr("selected",true);
    }
    else{
        $('#Gender').val('Female').attr("selected",true);
    }
}
    function stickerPrint(MrdNo) {
        setTimeout(function() {
        window.open(
            '/{{projectUrl()}}stickerPrint/' + MrdNo, 'stickerPrint',
            'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=800, height=800'
        );
    }, 1);
    }
function goWhatsApp(Phone) {
    setTimeout(function() {
        window.open(
            'https://api.whatsapp.com/send?phone=+91' + Phone + '&text=Hi', 'whatsapp',
            'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=1500, height=1000'
        );
    }, 1);
}

function viewOpdDetails() {
    var mrdno = $('#MRD_NO').val();
    var visitno = $('#visitno').val();
    setTimeout(function() {
        window.open(
            '/{{projectUrl()}}opdSummary/' + mrdno, 'popUpWindow3',
            'height=1000,width=1000,left=0,top=0,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no'
        );
    }, 1);
}

function getPatientList() {
    var Patient_Name = $('#Patient_Name').val();
    $.ajax({
        url: "{{ url('getPatientList') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            Patient_Name: Patient_Name
        },
        success: function(data) {
            console.log(data);
            $('#patientlist').html(data);
        }
    });
}

function getLastVisit(mrdno) {
    $.ajax({
        url: "{{ url('getLastVisit') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            mrdno: mrdno
        },
        success: function(data) {
            $('#visitno').val(data);
        }
    });
}
$('body').click(function(e) {
    if (!$(e.target).closest('#showpatient').length) {
        $('#showpatient').html('');
    }
});

function dailyReport() {
    //$('#modal-daily-report').modal('show');
    var FromDate = $('#FromDate').val();
    var CurrDate = $('#CurrDate').val();
    if (FromDate == '') {
        var SearchDate = CurrDate;
    } else {
        var SearchDate = FromDate;
    }
    setTimeout(function() {
        window.open(
            '/{{projectUrl()}}dailyReport/' + SearchDate, 'name',
            'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=1500, height=1000'
        );
    }, 1);
}

function showOptoForm(mrdno, qid, indate) {
    //alert(indate);exit();
    //var visitdate = $('#CurrDate').val();
    var visitdate = indate;
    $.ajax({
        url: "{{ url('getMaxVisitNo') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            mrdno: mrdno,
            visitdate: visitdate,
            qid: qid
        },
        success: function(data) {
            //alert(data);exit();
            setTimeout(function() {
                window.open(
                    '/{{projectUrl()}}optoform/' + mrdno + '/' + visitdate + '/' + data +
                    '?page=tab1', 'name',
                    'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=1500, height=1000'
                );
            }, 1);
        }
    });

}

function patientOut(id, mrdno, indate, ptname) {
    swal({
        title: "" + ptname + " - " + mrdno,
        text: "Are you sure you want to out this patient?",
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Patient Out",
        cancelButtonText: "No, cancel",
        closeOnConfirm: false,
        closeOnCancel: false
    }, function(isConfirm) {
        if (isConfirm) {
            $.ajax({
                url: "{{ url('patientOut') }}",
                method: "POST",
                data: {
                    _token: '{{csrf_token()}}',
                    id: id,
                    mrdno: mrdno,
                    indate: indate
                },
                beforeSend: function() {
                    $('.confirm').attr('disabled', 'disabled');
                    $('.confirm').text('Please Wait...');
                },
                success: function(data) {
                    var res = JSON.parse(data);
                    var Status = res.Status;
                    var totalPatient = res.totalPatient;
                    var totalCheckPatient = res.totalCheckPatient;
                    var totalUncheckPatient = res.totalUncheckPatient;

                    $('#totalPatient').html('Total :' + totalPatient);
                    $('#totalChecked').html('Checked :' + totalCheckPatient);
                    $('#totalUnchecked').html('Un Checked :' + totalUncheckPatient);
                    queueList();
                    swal("Patient Out!", "Successfully", "success");
                }
            });
        } else {
            swal("Cancelled", "Record is safe :)", "error");
        }
    });
}

function newPatientList() {
    $.ajax({
        url: "{{ url('newPatientDataList') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}'
        },
        success: function(data) {
            //console.log(data);
            $('#PatientId').html(data);
        }
    });
}

function getAge(val) {
    var dob = new Date(val);
    //calculate month difference from current date in time  
    var month_diff = Date.now() - dob.getTime();

    //convert the calculated difference in date format  
    var age_dt = new Date(month_diff);

    //extract year from date      
    var year = age_dt.getUTCFullYear();

    //now calculate the age of the user  
    var age = Math.abs(year - 1970);

    $('#Age').val(age);
    //alert(age);
}

 function todayPatientLists(val){
    setTimeout(function() {
        window.open(
            '/{{projectUrl()}}todayPatientList/' + val, 'todayPatientList',
            'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=1500, height=800'
        );
    }, 1);
}

function findCurrAge(mrdno) {
    $.ajax({
        url: "{{ url('findCurrAge') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            mrdno: mrdno
        },
        success: function(data) {
            console.log(data);
            $('#PatientAge').val(data);
        }
    });
}

function getPatientVal() {
    var val = $('#TopMrdNo').val();
    $('#showpatient').html('');
    if (val == '') {
        $('.showoldfields').hide();
    } else {
        $('.showoldfields').show();
    }

    $.ajax({
        url: "{{ url('getPatientDetails2') }}",
        method: "POST",
        data: {
            _token: '{{ csrf_token() }}',
            id: val
        },
        dataType: "json",
        success: function(data) {
            console.log(data);
            // Accessing patient object and amount
            let patient = data.patient;
            let amount = data.amount_to_pay_today;
            let lastvisitdate = data.lastvisitdate;
            let totdays = data.totdays;
           
            if (patient) {
                $('#MRD_NO').val(patient.MrdNo);
                $('#PatientName').val(patient.PatientName);
                $('#PatientAge').val(patient.Age);
                $('#PatGender').val(patient.Gender).attr("selected", "selected");
                $('#PatientAddress').val(patient.Address);
                $('#PatientCity').val(patient.City);
                $('#PrevVisitDate').val(lastvisitdate);
                $('#TotDays').val(totdays);
               
                getLastVisit(patient.MrdNo);
            }

            // Show the calculated amount somewhere (optional)
            $('#ConsFees').val(amount); // Make sure you have <input id="AmountToPay">
        }
    });
}

function getPatientVal2(val) {
    //$('#SearchPatientName').val(val);
   // var val = $('#TopMrdNo').val();
    $('#showpatient').html('');
    //var val = this.value;
    if (val == '') {
        $('.showoldfields').hide();
    } else {
        $('.showoldfields').show();
    }
    $.ajax({
        url: "{{ url('getPatientDetails2') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            id: val
        },
        dataType: "json",
        success: function(data) {
            // Accessing patient object and amount
            let patient = data.patient;
            let amount = data.amount_to_pay_today;
            let lastvisitdate = data.lastvisitdate;
            let totdays = data.totdays;
            let last400Date = data.last400Date;
            let daysSince = data.daysSince;
            if (patient) {
                $('#MRD_NO').val(patient.MrdNo);
                $('#PatientName').val(patient.PatientName);
                $('#PatientAge').val(patient.Age);
                $('#PatGender').val(patient.Gender).attr("selected", "selected");
                $('#PatientAddress').val(patient.Address);
                $('#PatientCity').val(patient.City);
                $('#PrevVisitDate').val(lastvisitdate);
                $('#TotDays').val(totdays);
                $('#400VisitDate').val(last400Date);
                $('#400TotDays').val(daysSince);
                getLastVisit(patient.MrdNo);
            }

            // Show the calculated amount somewhere (optional)
            $('#ConsFees').val(amount); // Make sure you have <input id="AmountToPay">
            $('#modal-ptlist').modal("hide");
            $('#TopMrdNo').val('');
            //$('#PartStateId').html(data);
            //findCurrAge(data.MrdNo);
        }
    });
}

$(document).ready(function() {
    $('#example').DataTable({
        responsive: true
    });

    $(document).on("keyup", "#SearchPatientName", function(event) {
        var val = this.value;
        if (val == '') {
            $('#showpatient').html('');
            $('.showoldfields').hide();
        } else {
            $.ajax({
                url: "{{ url('patientList') }}",
                method: "POST",
                data: {
                    _token: '{{csrf_token()}}',
                    val: val
                },
                success: function(data) {
                    //console.log(data);
                    if (data == 0) {
                        $('#showpatient').html('');
                    } else {
                        $('#showpatient').html(data);
                    }

                }
            });
        }
    });

    $(document).on("change", "#ConsultantId", function(event) {
        var val = this.value;
        $.ajax({
            url: "{{ url('consultantDetails') }}",
            method: "POST",
            data: {
                _token: '{{csrf_token()}}',
                val: val
            },
            dataType: "json",
            success: function(data) {
                //console.log(data);
                $('#ConsFees').val(data.Fees);
            }
        });

    });

    $(document).on("change", "#Consultant", function(event) {
        var val = this.value;
        $.ajax({
            url: "{{ url('consultantDetails') }}",
            method: "POST",
            data: {
                _token: '{{csrf_token()}}',
                val: val
            },
            dataType: "json",
            success: function(data) {
                //console.log(data);
                $('#Fees').val(data.Fees);
            }
        });

    });

    $(document).on("click", ".update2", function(event) {
        event.preventDefault();
        event.stopPropagation();
        var id = $(this).attr("data-id");
        $.ajax({
            url: "{{ url('fetchQueuePatientDetails') }}",
            method: "POST",
            data: {
                _token: '{{csrf_token()}}',
                id: id
            },
            dataType: "json",
            success: function(data) {
                console.log(data);
                $('#id2').val(data.id);
                $('#Mrd_No2').val(data.MrdNo);
                $('#PatientName2').val(data.PatientName);
                $('#Gender2').val(data.Gender).attr("selected", true);

                $('#Age2').val(data.Age);

                $('#Consultant2').val(data.Consultant).attr("selected", true);
                $('#Fees2').val(data.Amount);
                $('#PayMode2').val(data.PayMode).attr("selected", true);
                $('#Createdby2').val(data.CreatedBy).attr("selected", true);
                $('#Consultant2').val(data.Consultant).attr("selected", true);


                $('#action2').val('UpdateQueue');
                $('#submit4').text("Update");
                $('.insert_frm4').modal('show');
                $('.modal-title4').html(
                    "Update <span class='font-weight-light'>Patient</span>");

            }
        });
    });


    $(document).on("click", ".update", function(event) {
        event.preventDefault();
        event.stopPropagation();
        var id = $(this).attr("data-id");
        $.ajax({
            url: "{{ url('fetchPatientDetails') }}",
            method: "POST",
            data: {
                _token: '{{csrf_token()}}',
                id: id
            },
            dataType: "json",
            success: function(data) {
                console.log(data);
                $('#id').val(data.id);
                $('#MrdNo').val(data.MrdNo);
                $('#Suffix').val(data.Suffix).attr("selected", true);
                $('#Fname').val(data.Fname);
                $('#Mname').val(data.Mname);
                $('#Lname').val(data.Lname);
                $('#Gender').val(data.Gender).attr("selected", true);
                $('#Dob').val(data.Dob);
                $('#Age').val(data.Age);
                $('#AgeMonth').val(data.AgeMonth);
                $('#AgeDay').val(data.AgeDay);
                $('#Phone').val(data.Phone);
                $('#Phone2').val(data.Phone2);
                $('#Address').val(data.Address);
                $('#City').val(data.City).attr("selected", true);
                $('#State').val(data.State).attr("selected", true);
                $('#Consultant').val(data.Consultant).attr("selected", true).attr("disabled", true);
                $('#Fees').val(data.Amount).attr("disabled", true);
                $('#PayMode').val(data.PayMode).attr("selected", true);
                $('#RefBy').val(data.RefBy);

                $('#action').val('EditQueue');
                $('#submit').text("Update");
                $('.insert_frm').modal('show');
                $('.modal-title').html(
                    "Update <span class='font-weight-light'>Patient</span> <span style='padding-left: 10px;'><button class='btn btn-success btn-sm mb-3 btn-round' onclick='viewOpdQueue()'>view OPD Queue</button></span>"
                    );

            }
        });
    });

    $(document).on("click", ".delete", function(event) {
        event.preventDefault();
        var id = $(this).attr("data-id");
        var action = "delete";
        //alert(id);
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this Queue Record!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes, delete",
            cancelButtonText: "No, cancel",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function(isConfirm) {
            if (isConfirm) {
                $.ajax({
                    url: "{{ url('deletqueue') }}",
                    method: "POST",
                    data: {
                        _token: '{{csrf_token()}}',
                        id: id
                    },
                    beforeSend: function() {
                        $('.confirm').attr('disabled', 'disabled');
                        $('.confirm').text('Please Wait...');
                    },

                    success: function(data) {
                        var res = JSON.parse(data);
                        var Status = res.Status;
                        var totalPatient = res.totalPatient;
                        var totalCheckPatient = res.totalCheckPatient;
                        var totalUncheckPatient = res.totalUncheckPatient;
                        $('#totalPatient').html('Tot :' + totalPatient);
                        $('#totalChecked').html('Chk :' + totalCheckPatient);
                        $('#totalUnchecked').html('Un Chk :' +
                            totalUncheckPatient);
                        swal("Deleted!", "Record has been deleted.", "success");
                        //window.location.href = "/queuemanagement";
                        queueList();



                    }
                });

            } else {
                swal("Cancelled", "Record is safe :)", "error");
            }
        });


    });

    $(document).on("change", "#PatientId", function(event) {
        var val = this.value;
        getPatientVal(val);

    });

});

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

function success_toast() {
    var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
    $.growl.notice({
        title: 'Success',
        message: 'New User Added Successfully!',
        location: isRtl ? 'tl' : 'tr'
    });
}

function error_toast() {
    var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
    $.growl.error({
        title: 'Error',
        message: 'Patient Name Already Exists',
        location: isRtl ? 'tl' : 'tr'
    });
}
</script>

<script type="text/javascript">
$(document).ready(function() {

    //load_data();
    queueList();

    function load_data(FromDate = '', ToDate = '') {
        $('.yajra-datatable').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: "{{ route('queue.listing') }}",
                data: {
                    FromDate: FromDate,
                    ToDate: ToDate
                }
            },
            columns: [

                {
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex'
                },

                {
                    data: 'MrdNo',
                    name: 'MrdNo'
                },
                {
                    data: 'PatientName',
                    name: 'PatientName'
                },
                {
                    data: 'Gender',
                    name: 'Gender'
                },
                {
                    data: 'PatientType',
                    name: 'PatientType'
                },
                {
                    data: 'Consultant_Name',
                    name: 'Consultant'
                },
                {
                    data: 'InTime',
                    name: 'InTime'
                },
                {
                    data: 'Age',
                    name: 'Age'
                },
                {
                    data: 'Amount',
                    name: 'Amount'
                },
                {
                    data: 'DT_RowIndex',
                    name: 'Rwno'
                },
                {
                    data: 'action',
                    name: 'action',
                    orderable: true,
                    searchable: true
                },
            ]
        });
    }

    $('#filter').click(function() {
        var FromDate = $('#FromDate').val();
        var ToDate = $('#ToDate').val();
        if (FromDate != '') {
            //$('.yajra-datatable').DataTable().destroy();
            //load_data(FromDate, ToDate);
            queueList(FromDate, ToDate);
        } else {
            alert('Date is required');
        }
    });

    $('#refresh').click(function() {
        $('#FromDate').val('');
        $('#ToDate').val('');
        //$('.yajra-datatable').DataTable().destroy();
        //load_data();
        queueList();
    });


    $('#validation-form2').on('submit', function(e) {
        e.preventDefault();
        if ($('#validation-form2').valid()) {
            $.ajax({
                url: "{{ url('saveOldQueue') }}",
                method: "POST",
                data: new FormData(this),
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $('#submit2').attr('disabled', 'disabled');
                    $('#submit2').text('Please Wait...');
                },
                success: function(data) {
                    console.log(data);
                    var res = JSON.parse(data);
                    var Status = res.Status;
                    var totalPatient = res.totalPatient;
                    var totalCheckPatient = res.totalCheckPatient;
                    var totalUncheckPatient = res.totalUncheckPatient;
                    var NewMrdNo = res.NewMrdNo;

                    if (Status == 0) {
                        alert('Patient already in queue list. Please out patient first!');
                    } else {
                        $('#NewMrdNo').val(NewMrdNo);
                        $('#totalPatient').html('Tot :' + totalPatient);
                        $('#totalChecked').html('Chk :' + totalCheckPatient);
                        $('#totalUnchecked').html('Un Chk :' + totalUncheckPatient);
                        $('#PatientId').val('');
                        $('#PatGender').val('');
                        $('#showpatient').html('');
                        $('.showoldfields').hide();
                        //$('.yajra-datatable').DataTable().destroy();
                        //load_data();
                        queueList();
                    }
                    $('#submit2').attr('disabled', false);
                    $('#submit2').text('Add In Queue');
                }
            });
        }
    });

    $('#validation-form').on('submit', function(e) {
        e.preventDefault();
        var action = $('#action').val();
        if (action == 'SaveQueue') {
            var url = "{{ url('saveQueue') }}";
        } else {
            var url = "{{ url('EditQueue') }}";
        }

        if ($('#validation-form').valid()) {
            $.ajax({
                url: url,
                method: "POST",
                data: new FormData(this),
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $('#submit').attr('disabled', 'disabled');
                    $('#submit').text('Please Wait...');
                },
                success: function(data) {
                    //console.log(data);exit()
                    var res = JSON.parse(data);
                    var Status = res.Status;
                    var MrdNo = res.MrdNo;
                    if (Status == 1) {
                        var totalPatient = res.totalPatient;
                        var totalCheckPatient = res.totalCheckPatient;
                        var totalUncheckPatient = res.totalUncheckPatient;
                        var NewMrdNo = res.NewMrdNo;
                        $('#NewMrdNo').val(NewMrdNo);
                        $('#totalPatient').html('Tot :' + totalPatient);
                        $('#totalChecked').html('Chk :' + totalCheckPatient);
                        $('#totalUnchecked').html('Un Chk :' + totalUncheckPatient);
                        $('#PatientId').val('');
                        $('#PatGender').val('');
                        $('#showpatient').html('');
                        $('.showoldfields').hide();
                        $('#MrdNo').val('');
                        $('#id').val('');
                        $('#PageVal').val('');
                        $('#Suffix').val('').attr("selected", true);
                        $('#Fname').val('');
                        $('#Mname').val('');
                        $('#Lname').val('');
                        $('#Gender').val('').attr("selected", true);
                        $('#Dob').val('');
                        $('#Age').val('');
                        $('#Phone').val('');
                        $('#Phone2').val('');
                        $('#City').val('');
                        $('#State').val('');
                        $('#Address').val('');
                        $('#Consultant').val(19).attr("selected", true);
                        $('#Fees').val('');
                        $('#PayMode').val('Cash').attr("selected", true);
                        $('#RefBy').val('');
                        $('#action').val('SaveQueue');

                        //$('.yajra-datatable').DataTable().destroy();
                        //load_data();
                        $('#modal-report').modal('hide');
                        queueList();
                        newPatientList();
                        if (action == 'SaveQueue') {
                        setTimeout(function() {
        window.open(
            '/{{projectUrl()}}stickerPrint/' + MrdNo, 'stickerPrint',
            'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=800, height=800'
        );
    }, 1);
}
                    } else {
                        error_toast();
                    }
                    $('#submit').attr('disabled', false);
                    $('#submit').text('Add');
                }
            });
        }
    });


    $('#add_button').click(function() {
        var NewMrdNo = $('#NewMrdNo').val();
        //$('.modal-title').html("Add <span class='font-weight-light'>Patient</span><button class='btn btn-success btn-sm mb-3 btn-round'>view OPD Queue</button>");
        $('#id').val('');
        $('#submit').text('Submit');
        $('#PatientId').val('');
        $('#PatGender').val('');
        $('#showpatient').html('');
        $('.showoldfields').hide();
        $('#MrdNo').val(NewMrdNo);
        $('#id').val('');
        $('#PageVal').val('');
        $('#Suffix').val('').attr("selected", true);
        $('#Fname').val('');
        $('#Mname').val('');
        $('#Lname').val('');
        $('#Gender').val('').attr("selected", true);
        $('#Dob').val('');
        $('#Age').val('');
        $('#Phone').val('');
        $('#Phone2').val('');
        $('#City').val('');
        $('#State').val('');
        $('#Address').val('');
        $('#Consultant').val(19).attr("selected", true).attr("disabled", false);
        $('#Fees').val('').attr("disabled", false);
        $('#PayMode').val('Cash').attr("selected", true);
        $('#RefBy').val('');
        $('#action').val('SaveQueue');


    })

    $('#validation-form4').on('submit', function(e) {
        e.preventDefault();
        if ($('#validation-form4').valid()) {
            $.ajax({
                url: "{{ url('updateQueueDetails') }}",
                method: "POST",
                data: new FormData(this),
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $('#submit4').attr('disabled', 'disabled');
                    $('#submit4').text('Please Wait...');
                },
                success: function(data) {
                    //console.log(data);
                    var res = JSON.parse(data);
                    var Status = res.Status;
                    var totalPatient = res.totalPatient;
                    var totalCheckPatient = res.totalCheckPatient;
                    var totalUncheckPatient = res.totalUncheckPatient;

                    $('#totalPatient').html('Tot :' + totalPatient);
                    $('#totalChecked').html('Chk :' + totalCheckPatient);
                    $('#totalUnchecked').html('Un Chk :' + totalUncheckPatient);
                    $('#id2').val('');
                    $('#MrdNo2').val('');
                    $('#PatientName2').val('');
                    $('#Gender2').val('').attr("selected", true);

                    $('#Age2').val('');

                    $('#Consultant2').val('').attr("selected", true);
                    $('#Fees2').val('');
                    $('#PayMode2').val('Cash').attr("selected", true);
                    $('#modal-report4').modal('hide');
                    queueList();

                    $('#submit4').attr('disabled', false);
                    $('#submit4').text('Update');
                }
            });
        }
    });

});

function queueList(FromDate = '', ToDate = '') {
    $.ajax({
        url: "{{ url('viewQueueList') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            FromDate: FromDate,
            ToDate: ToDate
        },
        beforeSend:function(){
     $('#please_wait').show();
    },
        success: function(data) {
            //console.log(data);
            $('#custresult').html(data);
            $('#please_wait').hide();
            //refreshQueue();
        }
    });
}

function refreshQueue() {
    $.ajax({
        url: "{{ url('refreshQueue') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}'
        },
        success: function(data) {
            queueList();
            var res = JSON.parse(data);
            var Status = res.Status;
            var totalPatient = res.totalPatient;
            var totalCheckPatient = res.totalCheckPatient;
            var totalUncheckPatient = res.totalUncheckPatient;
            var NewMrdNo = res.NewMrdNo;
            $('#NewMrdNo').val(NewMrdNo);
            $('#totalPatient').html('Total : ' + totalPatient);
            $('#totalChecked').html('Check : ' + totalCheckPatient);
            $('#totalUnchecked').html('Un Check : ' + totalUncheckPatient);
        }
    });
}

function viewOpdQueue() {
    setTimeout(function() {
        window.open(
            '/{{projectUrl()}}viewOpdQueue', 'opdqueue',
            'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=1500, height=1000'
        );
    }, 1);

}

function clearBlankRecord(){
    $.ajax({
        url: "{{ url('clearBlankRecord') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}'
        },
       beforeSend: function() {
                    $('#clearblank').attr('disabled', 'disabled');
                    $('#clearblank').text('Please Wait...');
                },
        success: function(data) {
            window.location.href='/{{projectUrl()}}queuemanagement';
        }
    });
}
</script>