@extends('layout')

@section('content')
<div class="container-fluid flex-grow-1 container-p-y">
    <h4 class="font-weight-bold py-3 mb-0">Create IPD Bill</h4>

    <form method="POST" action="/{{projectUrl()}}updateIpdTempBill">

        <input type="hidden" name="actionvalue" value="Save">
        <input type="hidden" name="saveid" value="{{$data->BillNo}}">
        @csrf


        <div class="card mb-12 mb-4">
            <div class="card-body">
                <div class="form-row align-items-center" style="overflow-x:auto;">
                    <div class="table-responsive">

                        <table class="table table-bordered table-striped mb-0">
                            <thead>

                                <tr>
                                    <th align="center" valign="top">Bill NO </th>
                                    <th align="left" valign="top"><input name="BillNo" id="Bill_No" type="text"
                                            class="form-control" placeholder="" value="{{$data->BillNo}}" readonly />
                                    </th>
                                    <th align="center" valign="top">Bill Type </th>
                                    <th align="left" valign="top">
                                        <select class="form-control" name="BillType" id="BillType">
                                            <option value="General" <?php if($data->BillType == 'General'){?> selected
                                                <?php } ?>>General</option>
                                            <option value="Reimbursement"
                                                <?php if($data->BillType == 'Reimbursement'){?> selected <?php } ?>>
                                                Reimbursement</option>
                                        </select>
                                    </th>

                                    <input type="hidden" id="BillId">

                                    <th width="20" align="center" valign="top">Mrd.No </th>
                                    <th width="150" align="center" valign="top"><input type="text" class="form-control"
                                            placeholder="" id="MrdNo" name="MrdNo" value="{{$data->MrdNo}}" readonly>
                                        <div class="clearfix"></div>
                                    </th>
                                    <!-- <th width="20" align="center" valign="top">IPD.No </th>
                                    <th width="50" align="center" valign="top"><input type="text" class="form-control"
                                            placeholder="" id="IpdNo" name="IpdNo" readonly>
                                        <div class="clearfix"></div>
                                    </th> -->
                                    <th width="30" align="center" valign="top">Patient Name </th>
                                    <th width="180" align="center" valign="top"><input type="text" class="form-control"
                                            placeholder="" name="PatientName" id="PatientName"
                                            value="{{$data->PatientName}}" readonly>
                                        <div class="clearfix"></div>
                                    </th>
                                </tr>

                                <tr>
                                    <th width="50" align="center" valign="top">Age/Gender </th>
                                    <th width="100" align="center" valign="top"><input type="text" class="form-control"
                                            placeholder="" id="AgeGender" name="AgeGender" value="{{$data->AgeGender}}"
                                            readonly>

                                        <div class="clearfix"></div>
                                    </th>
                                    <th width="20" align="center" valign="top">Bill Date </th>
                                    <th width="20" align="center" valign="top"><input type="date" name="BillDate"
                                            id="BillDate" class="form-control" value="{{$data->BillDate}}"></th>
                                            <th width="20" align="center" valign="top">Admission Date </th>
                            <th width="20" align="center" valign="top"><input type="date" name="AdmissionDate"
                                    id="AdmissionDate" class="form-control" value="{{$data->AdmissionDate}}" required></th>
                                    <th width="50" align="center" valign="top">Operation Date</th>
                                    <th width="50" align="center" valign="top"><input type="date" name="OperationDate"
                                            class="form-control" id="OperationDate" value="{{$data->OperationDate}}">
                                    </th>
                                    
                                    </tr>
                        <tr>
                        <th width="30" align="center" valign="top">Discharge Date </th>

<th width="30" align="center" valign="top"><input type="date" id="DischargeDate"
        name="DischargeDate" class="form-control" value="{{$data->DischargeDate}}">
</th>
                                    <th  width="30" align="center" valign="top">Consultant Name </th>

                                    <th colspan="2" width="30" align="center" valign="top"><select class="form-control"
                                            name="Consultant" id="ConsultantId" required>
                                            <option>Search Consultant</option>
                                            @foreach($consultantList as $result)
                                            <option value="{{$result->id}}"
                                                <?php if($data->Consultant == $result->id){?> selected <?php } ?>>
                                                {{$result->Name}}</option>
                                            @endforeach
                                        </select></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>


                        <table class="table table-bordered table-striped mb-0">
                    <thead>
                    <input type="hidden" name="chargesaction" id="action" value="Save">
                                    <input type="hidden" name="id" id="id" />
                                    <tr>
                            <th>Package Name </th>
                            <th><input class="form-control" type="text" list="emails2" style="overflow-x:auto;"
                                    name="PackageName" id="PackageName" required
                                    onchange="getPackageDetails(this.value)" value="{{$data->PackageName}}">
                                <datalist id="emails2">
                                    <option value="GENERAL">
                                </datalist>
                            </th>
                            <th>Package Amount </th>
                            <th><input type="text" class="form-control" id="PackageAmt" placeholder="" name="PackageAmt"
                                    onKeyPress="return isNumberKey(event)" required="" value="{{$data->PackageAmt}}"></th>

                            <th>
                                Balance Amount</th>
                            <th><input type="text" class="form-control" id="BalanceAmt" name="BalanceAmt" placeholder=""
                                    onKeyPress="return isNumberKey(event)" value="{{$data->BalanceAmt}}">
                            </th>
                        </tr>

                        <tr>
                            <th width="13%">Charges Name <span class="text-danger">*</span></th>
                            <th width="25%"><input class="form-control" type="text" list="Charges"
                                    style="overflow-x:auto;" name="ChargesName" id="ChargesName"
                                    onchange="getChargesDetails(this.value)">
                                <datalist id="Charges">

                                </datalist>
                            </th>

                            <th width="13%">Days / Unit <span class="text-danger">*</span></th>
                            <th width="25%"><input type="text" class="form-control" name="Days" id="Days" placeholder=""
                                    onKeyPress="return isNumberKey(event)"
                                    oninput="getAmount(document.getElementById('Days').value,document.getElementById('Rate').value)">
                            </th>
                            <th colspan="2">
                            
                            <button class="btn btn-success btn-sm mb-3 btn-round" type="button"
                                    id="submit" onclick="saveBills()"><i class="feather icon-plus"></i> Add</button>
                                    <!-- <button class="btn btn-info btn-sm mb-3 btn-round" type="button"
                                    id="calulate" onclick="calculateBills()"><i class="feather icon-plus"></i> Calculate</button> -->
                            </th>


                        </tr>

                        <tr>
                            <th>Rate <span class="text-danger">*</span></th>
                            <th><input type="text" class="form-control" name="Rate" id="Rate" placeholder=""
                                    onKeyPress="return isNumberKey(event)"
                                    oninput="getAmount(document.getElementById('Days').value,document.getElementById('Rate').value)">
                            </th>

                            <th>Amount <span class="text-danger">*</span></th>
                            <th><input type="text" class="form-control" name="Amount" id="Amount" placeholder=""
                                    onKeyPress="return isNumberKey(event)" readonly></th>
                            <th colspan="2">
                                <a href="/vyawahare_hosp/bill.php" class="btn btn-danger btn-sm mb-3 btn-round"><i
                                        class="feather icon-reload"></i> Refresh</a>
                            </th>

                        </tr>
                        <tr>
                            <th colspan="6">
                                <div class="table-responsive" id="custresult">

                                </div>
                            </th>
                        </tr>


                    </thead>

                </table>      
                
                <table width="100%" border="0" cellspacing="3" cellpadding="2"
                    class="table table-bordered table-striped mb-0">
                    <thead>
                        <tr>

                            <th>Sub Total</th>
                            <th><input type="text" class="form-control" placeholder="" id="SubTotal" name="SubTotal"
                                    readonly value="{{$data->SubTotal}}">
                            </th>
                            <th>Discount</th>
                            <th><input type="text" class="form-control" placeholder="" id="Discount" name="Discount"
                                    onKeyPress="return isNumberKey(event)" required value="{{$data->Discount}}"
                                    oninput="netAmount(document.getElementById('SubTotal').value,document.getElementById('Discount').value,document.getElementById('GrossAmt').value,document.getElementById('PaidAmt').value)">
                            </th>
                            <th>Gross Amount</th>
                            <th><input type="text" class="form-control" placeholder="" value="{{$data->GrossAmt}}" id="GrossAmt" name="GrossAmt"
                                    readonly>
                            </th>
                            <th>Paid Amount</th>
                            <th><input type="text" class="form-control" placeholder="" id="PaidAmt" name="PaidAmt"
                                    onKeyPress="return isNumberKey(event)" required value="{{$data->PaidAmt}}"
                                    oninput="netAmount(document.getElementById('SubTotal').value,document.getElementById('Discount').value,document.getElementById('GrossAmt').value,document.getElementById('PaidAmt').value)">
                            </th>
                        </tr>
                        <tr>
                            <td>Balance Amount</td>
                            <td><input type="text" class="form-control" placeholder="" id="BalAmt" name="BalAmt"
                                    readonly value="{{$data->BalAmt}}">
                            </td>
                            <td>Payment Mode </td>
                            <td>
                            <select class="form-control" style="width: 100%"
                                                        data-allow-clear="true" name="PayMode" id="PayMode">

                                                        <option value="Cash" <?php if($data->PayMode == 'Cash'){?>
                                                            selected <?php } ?>>Cash</option>
                                                            <option value="Card" <?php if($data->PayMode == 'Card'){?>
                                                            selected <?php } ?>>Card</option>
                                                        <option value="Mobile" <?php if($data->PayMode == 'Mobile'){?>
                                                            selected <?php } ?>Mobile</option>
                                                        <option value="Cheque" <?php if($data->PayMode == 'Cheque'){?>
                                                            selected <?php } ?>Cheque</option>

                                                    </select>
                            </td>
                            <td>Narration </td>
                            <td colspan="5"><input type="text" class="form-control" id="Narration" name="Narration"
                                    placeholder="" value="{{$data->Narration}}"></td>


                        </tr>

                    </thead>

                </table>

                <div class="col-sm-12">
                    <span style="color:red;display: none;" id="error_msg">Package Amount Not Matched
                        With Sub Total</span><br>
                    <button class="btn btn-primary" type="submit" disabled id="submit_save">Submit</button>
                    <!-- <button class="btn btn-success" type="button" onclick="print()">Print</button> -->
                    <a href="/{{projectUrl()}}tempBill" class="btn btn-danger"
                                            type="button">Refresh</a>
                </div>
                    </div>

                   



                </div>

            </div>
        </div>



        
    </form>


</div>

@endsection
@section('scriptcontent')
<script>
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 Charges Added Successfully!',
        location: isRtl ? 'tl' : 'tr'
    });
}

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

function updateBill() {
    var BillId = $('#BillId').val();
    var SubTotal = $('#SubTotal').val();
    var Discount = $('#Discount').val();
    var GrossAmt = $('#GrossAmt').val();
    var PaidAmt = $('#PaidAmt').val();
    var BalAmt = $('#BalAmt').val();
    var PayMode = $('#PayMode').val();
    var Narration = $('#Narration').val();
    $.ajax({
        url: "{{ url('updateIpdBill') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            BillId: BillId,
            SubTotal: SubTotal,
            Discount: Discount,
            GrossAmt: GrossAmt,
            PaidAmt: PaidAmt,
            BalAmt: BalAmt,
            PayMode: PayMode,
            Narration: Narration,
        },
        success: function(data) {
            setTimeout(function() {
                window.open(
                    '/{{projectUrl()}}ipdBillPrint/' + BillId, '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 getAmount(days, rate) {
    var Amount = Number(days) * Number(rate);
    $('#Amount').val(Amount);
}

function getPackageDetails(val) {
    $.ajax({
        url: "{{ url('getBillPackageDetails') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            PackageName: val
        },
        dataType: "json",
        success: function(data) {
            console.log(data);
            $('#PackageAmt').val(data.PackageAmt);
            //$('#BalanceAmt').val(data.BalanceAmt);
            procedure_lists(val);
            calBalanceAmt(val);
            totSumBills();
        }
    });
}

function calBalanceAmt(PackageName) {
    var PackageAmt = $('#PackageAmt').val();
    $.ajax({
        url: "{{ url('calBillBalanceAmt') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            PackageName: PackageName,
            PackageAmt: PackageAmt
        },
        success: function(data) {
            //console.log(data);
            $('#BalanceAmt').val(data);
            if (data == 0) {
                $('#submit_save').attr('disabled', false);
                $('#error_msg').hide();
            } else {
                $('#submit_save').attr('disabled', true);
                $('#error_msg').show();
            }
        }
    });
}

function totSumBills() {
    var Discount = $('#Discount').val();
    var GrossAmt = $('#GrossAmt').val();
    var PaidAmt = $('#PaidAmt').val();
    var BillNo = $('#Bill_No').val();
    var PackageAmt = $('#PackageAmt').val();
    $.ajax({
        url: "{{ url('totSumBills3') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            BillNo: BillNo
        },
        success: function(data) {
            $('#SubTotal').val(data);
            netAmount(data, Discount, GrossAmt, PaidAmt);
            //balBillAmt();
            if (PackageAmt == data) {
                $('#submit_save').attr('disabled', false);
                $('#error_msg').hide();
            } else {
                $('#submit_save').attr('disabled', true);
                $('#error_msg').show();
            }
        }
    });
}

function netAmount(SubTotal, Discount, GrossAmt, PaidAmt) {
    var GrossAmt = Number(SubTotal) - Number(Discount);
    $('#GrossAmt').val(GrossAmt);
    var BalAmt = Number(GrossAmt) - Number(PaidAmt);
    $('#BalAmt').val(BalAmt);
    //balBillAmt();

}

function procedure_lists(PackageName) {
    $.ajax({
        url: "{{ url('billChargesView') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            PackageName: PackageName
        },
        success: function(data) {
            //console.log(data);
            $('#custresult').html(data);
        }
    });
}

function saveBills() {
    var action = $('#action').val();
    var id = $('#id').val();
    var PackageName = $('#PackageName').val();
    var PackageAmt = $('#PackageAmt').val();
    var BalanceAmt = $('#BalanceAmt').val();
    var ChargesName = $('#ChargesName').val();
    var Amount = $('#Amount').val();
    var Days = $('#Days').val();
    var Rate = $('#Rate').val();
    var BillNo = $('#Bill_No').val();
    $.ajax({
        url: "{{ url('updateBillCharges2') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            action: action,
            id: id,
            PackageName: PackageName,
            PackageAmt: PackageAmt,
            BalanceAmt: BalanceAmt,
            ChargesName: ChargesName,
            Amount: Amount,
            Days: Days,
            Rate: Rate,
            BillNo: BillNo
        },
        beforeSend: function() {
            $('#submit').attr('disabled', 'disabled');
            $('#submit').text('Please Wait...');
        },
        success: function(data) {
            //console.log(data);exit();
            if (data == 1) {
                //$('#modal-report').modal('hide');
                success_toast();
                getBillCharges(BillNo);
                totSumBills();
                $('#ChargesName').val('');
                $('#Amount').val('');
                $('#Days').val('');
                $('#Rate').val('');
                $('#action').val('Save');

                $('#id').val('');
                $('#submit').text("Add");
            } else {
                error_toast();
                //$('#modal-report').modal('show');
            }
            $('#submit').attr('disabled', false);
            $('#submit').text('Add');
        }
    });
}

function print() {
    var BillId = $('#BillId').val();
    setTimeout(function() {
        window.open(
            '/{{projectUrl()}}ipdBillPrint/' + BillId, '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 getBillCharges(billno) {
    $.ajax({
        url: "{{ url('getBillCharges2') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            billno: billno
        },
        success: function(data) {
            console.log(data);
            $('#custresult').html(data);
            totSumBills();
        }
    });
}
$(document).ready(function() {
    var Bill_No = $('#Bill_No').val();
    getBillCharges(Bill_No);

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

        $.ajax({
            url: "{{ url('getBillDetails') }}",
            method: "POST",
            data: {
                _token: '{{csrf_token()}}',
                id: val
            },
            dataType: "json",
            success: function(data) {
                console.log(data);
                $('#BillId').val(data.id);
                $('#Bill_No').val(data.BillNo);
                $('#MrdNo').val(data.MrdNo);
                $('#BillType').val(data.BillType).attr("selected", true);
                $('#PatientName').val(data.PatientName);
                $('#AgeGender').val(data.AgeGender);
                $('#BillDate').val(data.BillDate);
                $('#AdmissionDate').val(data.AdmissionDate);
                $('#DischargeDate').val(data.DischargeDate);
                $('#ConsultantId').val(data.Consultant).attr("selected", true);
                $('#PackageName').val(data.PackageName);
                $('#PackageAmt').val(data.PackageAmt);
                $('#SubTotal').val(data.SubTotal);
                $('#Discount').val(data.Discount);
                $('#GrossAmt').val(data.GrossAmt);
                $('#PaidAmt').val(data.PaidAmt);
                $('#BalAmt').val(data.BalAmt);
                $('#PayMode').val(data.PayMode).attr("selected", true);
                $('#Narration').val(data.Narration);
                getBillCharges(data.BillNo);
            }
        });
    });
    $(document).on("change", "#PatientId", function(event) {
        var val = this.value;
        $.ajax({
            url: "{{ url('getIpdPatientDetails') }}",
            method: "POST",
            data: {
                _token: '{{csrf_token()}}',
                id: val
            },
            dataType: "json",
            success: function(data) {
                //console.log(data);
                var AgeGender = data.Age + "/" + data.Gender;
                $('#IpdNo').val(data.IpdNo);
                $('#MrdNo').val(data.MrdNo);
                $('#PatientName').val(data.PatientName);
                $('#AgeGender').val(data.AgeGender);
                $('#AdmissionDate').val(data.AdmissionDate);
                $('#DischargeDate').val(data.DischargeDate);
                $('#ConsultantId').val(data.Consultant).attr("selected", true);
                $('#Diagnosis').val(data.Diagnosis);
            }
        });

    });

    $(document).on("click", ".update", function(event) {
        event.preventDefault();
        event.stopPropagation();
        var id = $(this).attr("data-id");
        var action = "fetch_record";

        $.ajax({
            url: "{{ url('fetchBillChargesRecord3') }}",
            method: "POST",
            data: {
                _token: '{{csrf_token()}}',
                id: id
            },
            dataType: "json",
            success: function(data) {
                console.log(data);
                $('#ChargesName').val(data.Name);
                $('#Days').val(data.Days);
                $('#Rate').val(data.Rate);
                $('#Amount').val(data.Amount);
                $('#action').val('Edit');

                $('#id').val(id);
                $('#submit').text("Update");
                $('#modal-report').modal('show');
                $('.modal-title').html(
                    "Update <span class='font-weight-light'>Charges</span>");

            }
        });
    });



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

                    success: function(data) {
                        swal("Deleted!", "Charges has been deleted.", "success");

                        procedure_lists(PackageName);
                        calBalanceAmt(PackageName);
                        totSumBills();

                    }
                });

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

});
</script>

@endsection