@include('header')
@php
$UserId = Session::get('UserId');
$UserType = Session::get('UserType');
@endphp
<div class="container-fluid flex-grow-1 container-p-y">
    <h4 class="font-weight-bold py-3 mb-0">TUBING RECEIPT</h4>
    <div class="card mb-4">
        <div class="card-body">

            <div class="row align-items-center m-l-0">

                <div class="col-sm-1 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> Add
                        </button>
                </div>
                <div class="col-sm-2">
                    <div class="form-group">
                        <label class="floating-label" for="gender">Payment Mode </label>
                        <select class="form-control" id="SrchPayMode" name="SrchPayMode">
                            <option value="">All</option>
                            <option value="Cash">Cash</option>
                            <option value="Mobile Payment">Mobile Payment</option>
                        </select>
                    </div>
                </div>
                <div class="form-group col-md-2">
                    <label class="form-label">From Date </label>
                    <input type="date" id="FromDate" class="form-control" value="{{date('Y-m-d')}}" autocomplete="off" required>
                </div>
                <div class="form-group col-md-2">
                    <label class="form-label">To Date</label>
                    <input type="date" id="ToDate" class="form-control" value="{{date('Y-m-d')}}" autocomplete="off" required>
                </div>
                <input type="hidden" name="Search" value="Search">
                <div class="form-group col-md-1" style="padding-top:20px;">
                    <button type="button" class="btn btn-primary btn-finish"
                    id="filter">Search</button>
                </div>

                <div class="col-sm-2 text-right">
                    <a href="javascript:void(0)" class="badge badge-pill badge-danger" id="today">Today's Receipt :
                        {{$today}}</a>
                    <a href="javascript:void(0)" class="badge badge-pill badge-success"
                        id="total">Total Receipt : {{$total}}</a>
                </div>

            </div>
            <hr>
            <div class="table-responsive" id="custresult">

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

<div class="modal fade" id="modal-report" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" style="max-width: 70rem; ">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title">Add Tubing Receipt</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="validation-form" method="POST">
                    @csrf
                    <input type="hidden" name="action" id="action" value="Save">
                    <input type="hidden" name="id" id="id" />
                    <input type="hidden" name="ConsultantId" id="ConsultantId" />
                    <input type="hidden" name="Consultant" id="Consultant" />
                    <div class="row">
                        
                        <div class="col-sm-2">
                            <div class="form-group">
                                <label>Receipt No.</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" name="ReceiptNo" id="ReceiptNo" placeholder="" readonly>
                                    <div class="input-group-append">
                                        <button class="btn btn-secondary" type="button" id="listReceiptNo" title="List">
                                            List
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-2">
                            <div class="form-group">
                                <label>Receipt No.</label>
                                <input type="text" class="form-control" name="ReceiptNo2" id="ReceiptNo2" placeholder="" readonly>
                            </div>
                        </div>

                        <div class="col-sm-2">
                            <div class="form-group">
                                <label>Date <span class="text-danger">*</span></label>
                                <input type="date" value="{{date('Y-m-d')}}" class="form-control" id="Date" name="Date" placeholder="" required>
                            </div>
                        </div>

                        <div class="col-sm-3">
                            <div class="form-group">
                                <label class="floating-label" for="Name">Select MRD/IPD <span
                                        class="text-danger">*</span></label>
                                <select class="form-control" id="SelectMrdIpd" name="SelectMrdIpd" required>
                                    <option value="">Select...</option>
                                    <option value="MRD">MRD</option>
                                    <option value="IPD">IPD</option>
                                </select>
                            </div>
                        </div>

                        <div class="col-sm-3">
                            <div class="form-group">
                                <label class="floating-label" for="Name">UHID NO./IPD No. <span
                                        class="text-danger">*</span></label>
                                <div class="input-group">
                                    <input type="text" class="form-control" name="UhidNo" id="UhidNo" placeholder="" required>
                                    <div class="input-group-append">
                                        <button class="btn btn-secondary" type="button" id="browseUhid" title="Browse">
                                            ...
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-sm-4">
                            <div class="form-group">
                                <label class="floating-label" for="Name">Patient Name</label>
                                <input type="text" class="form-control" name="PatientName" id="PatientName" placeholder="" readonly>
                            </div>
                        </div>

                        <div class="col-sm-4">
                            <div class="form-group">
                                <label class="floating-label" for="gender">Procedure <span
                                        class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="Procedure" id="Procedure" value="TUBING" readonly required>
                            </div>
                        </div>

                        <div class="col-sm-2">
                            <div class="form-group">
                                <label class="floating-label" for="Phone">Total No ( TUBING)</label>
                                <input type="text" class="form-control" id="TotalNo" Name="TotalNo" placeholder="">
                            </div>
                        </div>

                        <div class="col-sm-4">
                            <div class="form-group">
                                <label class="floating-label" for="gender">Consultant <span
                                        class="text-danger">*</span></label>
                                <select class="form-control" id="ConsultantSelect" name="ConsultantSelect" required>
                                    <option value="">-Select Consultant-</option>
                                    @foreach($consultants as $consultant)
                                    <option value="{{$consultant->id}}">{{$consultant->Name}}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="col-sm-2">
                            <div class="form-group">
                                <label class="floating-label" for="Phone">Amount <span
                                        class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="Amount" Name="Amount" placeholder="" required>
                            </div>
                        </div>

                        <div class="col-sm-2">
                            <div class="form-group">
                                <label class="floating-label" for="gender">Pay Mode <span
                                        class="text-danger">*</span></label>
                                <select class="form-control" id="PayMode" name="PayMode" required>
                                    <option value="Cash" selected>Cash</option>
                                    <option value="Mobile Payment">Mobile Payment</option>
                                </select>
                            </div>
                        </div>

                        <div class="col-sm-12">
                            <button class="btn btn-primary" type="submit" name="submit" id="submit" onclick="btnaction2('submit')">Save</button>
                            <button class="btn btn-info" type="button" onclick="refreshForm()">Refresh</button>
                            <button class="btn btn-success" type="submit" name="print" id="print" onclick="btnaction2('print')">Print</button>
                            <button class="btn btn-danger" type="button" id="deletebtn" onclick="deleteReceipt()" disabled>Delete</button>
                            <button class="btn btn-secondary" type="button" onclick="window.close()">Exit</button>
                        </div>

                        <input type="hidden" id="CurrDate" value="{{date('Y-m-d')}}">
                        <input type="hidden" id="btnaction" value="submit">
                        <input type="hidden" name="MrdNo" id="MrdNo" />
                        <input type="hidden" name="IpdNo" id="IpdNo" />
                        
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@include('footerscript')
@include('excelscript')
<script type="text/javascript">
    function btnaction2(val){
        $('#btnaction').val(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() {
    if (typeof $.growl !== 'undefined' && typeof $.growl.notice !== 'undefined') {
        var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
        $.growl.notice({
            title: 'Success',
            message: 'Tubing Receipt Saved Successfully!',
            location: isRtl ? 'tl' : 'tr'
        });
    } else {
        alert('Success: Tubing Receipt Saved Successfully!');
    }
}

function error_toast() {
    if (typeof $.growl !== 'undefined' && typeof $.growl.error !== 'undefined') {
        var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
        $.growl.error({
            title: 'Error',
            message: 'Failed to save receipt',
            location: isRtl ? 'tl' : 'tr'
        });
    } else {
        alert('Error: Failed to save receipt');
    }
}

function printCard(id){
    setTimeout(function () {
        window.open(
            '/{{projectUrl()}}tubingReceiptPrint/'+id, 'name', 'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=900, height=1000'
        );
    }, 1);
}

function refreshForm() {
    $('#validation-form')[0].reset();
    $('#action').val('Save');
    $('#id').val('');
    $('#ReceiptNo').val('');
    $('#ReceiptNo2').val('');
    var CurrDate = $('#CurrDate').val();
    $('#Date').val(CurrDate);
    $('#Procedure').val('TUBING');
    $('#PayMode').val('Cash');
    $('#submit').text('Save');
    $('#deletebtn').attr('disabled', true);
}

function deleteReceipt() {
    var id = $('#id').val();
    if(!id) {
        error_toast();
        return;
    }

    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this receipt!",
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Yes, delete",
        cancelButtonText: "No, cancel",
        closeOnConfirm: false,
        closeOnCancel: false
    }, function(isConfirm) {
        if (isConfirm) {
            $.ajax({
                url: "{{ url('deleteTubingReceipt') }}",
                method: "POST",
                data: {
                    _token: '{{csrf_token()}}',
                    id: id
                },
                success: function(data) {
                    var res = JSON.parse(data);
                    var status = res.status;
                    var today = res.today;
                    var total = res.total;
                    queueList();
                    $('#today').html('Today\'s Receipt : '+today);
                    $('#total').html('Total Receipt : '+total);
                    swal("Deleted!", "Receipt has been deleted.", "success");
                    $('#modal-report').modal('hide');
                    refreshForm();
                }
            });
        } else {
            swal("Cancelled", "Receipt is safe :)", "error");
        }
    });
}

$('#filter').click(function(){
    var FromDate = $('#FromDate').val();
    var ToDate = $('#ToDate').val();
    var SrchPayMode = $('#SrchPayMode').val();
    if(FromDate != '' && ToDate != '') {
        queueList(FromDate, ToDate, SrchPayMode);
    } else {
        alert('Both Date is required');
    }
});

function queueList(FromDate = '', ToDate = '', SrchPayMode = '') {
    $.ajax({
        url: "{{ url('viewTubingReceipts') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}',
            FromDate: FromDate,
            ToDate: ToDate,
            SrchPayMode: SrchPayMode
        },
        success: function(data) {
            $('#custresult').html(data);
        }
    });
}

$(document).ready(function() {
    queueList();

    // Generate Receipt No on add
    $('#add_button').click(function() {
        var CurrDate = $('#CurrDate').val();
        $('.modal-title').html("Add <span class='font-weight-light'>Tubing Receipt</span>");
        $('#action').val("Save");
        $('#id').val('');
        $('#MrdNo').val('');
        $('#IpdNo').val('');
        $('#UhidNo').val('');
        $('#PatientName').val('');
        $('#Procedure').val('TUBING');
        $('#TotalNo').val('');
        $('#ConsultantSelect').val('').attr("selected", true);
        $('#ConsultantId').val('');
        $('#Consultant').val('');
        $('#Amount').val('');
        $('#Date').val(CurrDate);
        $('#PayMode').val('Cash');
        $('#submit').text('Save');
        $('#deletebtn').attr('disabled', true);
        
        // Generate Receipt No
        $.ajax({
            url: "{{ url('getTubingReceiptNo') }}",
            method: "POST",
            data: {
                _token: '{{csrf_token()}}'
            },
            success: function(data) {
                if(data.receipt_no) {
                    $('#ReceiptNo').val(data.receipt_no);
                    $('#ReceiptNo2').val(data.receipt_no);
                }
            }
        });
    });

    // Handle UHID/IPD No input
    $(document).on("input", "#UhidNo", function(event) {
        var val = this.value.trim();
        var selectType = $('#SelectMrdIpd').val();
        
        if(!val || !selectType) return;
        
        clearTimeout(window.uhidTimer);
        window.uhidTimer = setTimeout(function() {
            $.ajax({
                url: "{{ url('getPatientDetails') }}",
                method: "POST",
                data: {
                    _token: '{{csrf_token()}}',
                    id: val
                },
                dataType: "json",
                success: function(data) {
                    if(data) {
                        $('#MrdNo').val(data.MrdNo);
                        $('#PatientName').val(data.PatientName);
                        if(selectType == 'IPD') {
                            $('#IpdNo').val(data.IpdNo || val);
                        }
                        if(data.Consultant) {
                            $('#ConsultantId').val(data.Consultant);
                            $('#ConsultantSelect').val(data.Consultant).attr("selected", true);
                        }
                        if(data.ConsultantName) {
                            $('#Consultant').val(data.ConsultantName);
                        }
                    }
                }
            });
        }, 400);
    });

    // Handle Consultant Select
    $('#ConsultantSelect').on('change', function() {
        var consultantId = $(this).val();
        var consultantName = $(this).find('option:selected').text();
        $('#ConsultantId').val(consultantId);
        $('#Consultant').val(consultantName);
    });

    // Handle form submission
    $('#validation-form').on('submit', function(e) {
        e.preventDefault();
        var btnaction = $('#btnaction').val();
        var form = document.getElementById('validation-form');
        if(form.checkValidity()) {
            $.ajax({
                url: "{{ url('saveTubingReceipt') }}",
                method: "POST",
                data: new FormData(this),
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $('#'+btnaction).attr('disabled', 'disabled');
                    $('#'+btnaction).text('Please Wait...');
                },
                success: function(data) {
                    var res = JSON.parse(data);
                    var status = res.status;
                    var today = res.today;
                    var total = res.total;
                    var id = res.id;
                    if (status == 1) {
                        $('#modal-report').modal('hide');
                        success_toast();
                        queueList();
                        $('#today').html('Today\'s Receipt : '+today);
                        $('#total').html('Total Receipt : '+total);
                        if(btnaction == 'print'){
                            setTimeout(function () {
                                window.open(
                                    '/{{projectUrl()}}tubingReceiptPrint/'+id, 'name', 'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=900, height=1000'
                                );
                            }, 1);
                        }
                        refreshForm();
                    } else {
                        error_toast();
                        $('#modal-report').modal('show');
                    }
                    $('#'+btnaction).attr('disabled', false);
                    $('#'+btnaction).text('Submit');
                },
                error: function(xhr, status, error) {
                    error_toast();
                    $('#'+btnaction).attr('disabled', false);
                    $('#'+btnaction).text('Submit');
                }
            });
        } else {
            form.reportValidity();
        }
    });

    // Handle edit from list
    $(document).on("click", ".update", function(event) {
        event.preventDefault();
        event.stopPropagation();
        var id = $(this).attr("data-id");
        $.ajax({
            url: "{{ url('fetchTubingReceiptRecord') }}",
            method: "POST",
            data: {
                _token: '{{csrf_token()}}',
                id: id
            },
            dataType: "json",
            success: function(data) {
                $('#ReceiptNo').val(data.ReceiptNo);
                $('#ReceiptNo2').val(data.ReceiptNo);
                $('#Date').val(data.Date);
                $('#MrdNo').val(data.MrdNo);
                $('#IpdNo').val(data.IpdNo);
                $('#UhidNo').val(data.UhidNo || data.MrdNo);
                $('#PatientName').val(data.PatientName);
                $('#Procedure').val(data.Procedure);
                $('#TotalNo').val(data.TotalNo);
                $('#ConsultantId').val(data.ConsultantId);
                $('#ConsultantSelect').val(data.ConsultantId).attr("selected", true);
                $('#Consultant').val(data.Consultant);
                $('#Amount').val(data.Amount);
                $('#PayMode').val(data.PayMode).attr("selected", true);
                $('#action').val('Edit');
                $('#id').val(id);
                $('#submit').text("Update");
                $('#deletebtn').attr('disabled', false);
                $('#modal-report').modal('show');
                $('.modal-title').html("Update <span class='font-weight-light'>Tubing Receipt</span>");
            }
        });
    });

    // Handle delete from list
    $(document).on("click", ".delete", function(event) {
        event.preventDefault();
        var id = $(this).attr("data-id");
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this receipt!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes, delete",
            cancelButtonText: "No, cancel",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function(isConfirm) {
            if (isConfirm) {
                $.ajax({
                    url: "{{ url('deleteTubingReceipt') }}",
                    method: "POST",
                    data: {
                        _token: '{{csrf_token()}}',
                        id: id
                    },
                    success: function(data) {
                        var res = JSON.parse(data);
                        var status = res.status;
                        var today = res.today;
                        var total = res.total;
                        queueList();
                        $('#today').html('Today\'s Receipt : '+today);
                        $('#total').html('Total Receipt : '+total);
                        swal("Deleted!", "Receipt has been deleted.", "success");
                    }
                });
            } else {
                swal("Cancelled", "Receipt is safe :)", "error");
            }
        });
    });

});
</script>
