@extends('layouts.app')
@section('title','Payment Vouchers')
@section('pages')
<style type="text/css">
    .clear {
        clear: both;
        margin-top: 20px;
    }

    .autocomplete {
        position: relative;
    }

    .autocomplete .searchResult {
        list-style: none;
        padding: 0px;
        width: 78%;
        position: absolute;
        margin: 0;
        margin-top: 40px;
        background: white;
        z-index: 5;
    }

    .autocomplete .searchResult li {
        background: #F2F3F4;
        padding: 10px;
        margin-bottom: 1px;
        white-space: break-spaces;
    }

    .autocomplete .searchResult li:nth-child(even) {
        background: #E5E7E9;
        color: black;
    }

    .autocomplete .searchResult li:hover {
        cursor: pointer;
        background: #CACFD2;
    }

    #add_reference i {
        height: 20px;
        width: 20px;
        background: #0d6efd25;
        color: #0d6efd;
        text-align: center;
        border-radius: 50px;
        line-height: 20px;
    }

    .add_btn {
        height: 40px;
        width: 40px;
        font-size: 16px;
        border-radius: 0 3.5px 3.5px 0;
        padding: 0;
    }

    .custom_grid {
        padding-left: 1rem;
        padding-right: 1rem;
    }

    .custom_grid .input-group {
        position: relative;
    }

    .custom_grid .input-group .form-label {
        position: absolute;
        top: -10px;
        left: 5px;
        font-size: 12px;
        padding: 0px 8px;
        background-color: #f7f8fa;
        z-index: 5;
    }

    .custom_grid .input-group .form-control.br-0 {
        border-radius: 0;
    }

    .custom_grid .btn {
        font-size: 22px;
        padding: 0.15rem 0.75rem;
        border-top-left-radius: 0px;
        border-bottom-left-radius: 0px;
    }

    .select2-container--bootstrap4 .select2-selection {
        border-top-right-radius: 0px;
        border-bottom-right-radius: 0px;
    }
</style>
<link rel="stylesheet/less" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css')}}" rel="stylesheet" />

<!--breadcrumb-->
<div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
    <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Payment Vouchers</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">
                <li class="breadcrumb-item pe-3" aria-current="page"><a class="page_head"><b>
                            {{ 'PURCHASE' }}

                            ({!! $purchase_invoice->voucher_type_invoice_no??'' !!})
                            @if(isset($purchase_invoice->invoice_date))
                            ({!! $purchase_invoice->invoice_date?formatedDateTime($purchase_invoice->invoice_date):'' !!})
                            @endif
                        </b></a></li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
    @php
        $redirect = request()->redirect??'' ;
        $page  = request()->page??1;
    @endphp
        <div class="btn-group">
            <a href="{!! url($redirect) !!}?page={{$page}}" class="btn btn-info"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
        </div>
    </div>
</div>
<!--end breadcrumb-->

<div class="row auto">
    <div class="col-xl-12 mx-auto">
        <div class="cart_products">
            <div class="card style_table shadow-none" style="margin-bottom:0.8rem;">
                <div class="card-body pb-0">
                    <div class="table-responsive">
                        <table id="example" class="table table-bordered align-middle" style="width:100%">
                            <thead class="table-light">
                                <tr>
                                    <th class="thbutton">Serial No</th>
                                    <th>Payment Date</th>
                                    <th>Payment No</th>
                                    <th>Payment From</th>
                                    <th>Voucher Type</th>
                                    <th>Ref. Voucher No.</th>
                                    <th>Narration</th>
                                    <th style="text-align: right;">Amount</th>
                                    <th class="thbutton">Print</th>
                                    @if(in_array('payment-voucher-edit', $authRolePermissions))
                                    <th class="thbutton">Edit</th>
                                    @endif
                                    @if(in_array('receipt-voucher-delete', $authRolePermissions))
                                    <th class="thbutton">Delete</th>
                                    @endif
                                </tr>
                            </thead>
                            <tbody>
                                @php $i=1;@endphp
                                @if(count($data)>0)
                                @foreach($data as $key=> $list)
                                <tr>
                                    <td class="text-center">{{$i}}</td>
                                    <td>
                                        {{ formatedDate($list->receipt_date) }}<br>
                                        {{ formatedTime($list->receipt_time) }}
                                    </td>
                                    <td><a href="{{route('receipt-voucher.show',$list->id)}}"><strong>{{$list->receipt_no}}</strong>
                                            <br>
                                            @if($list->advance_received=='Yes' && $list->settlement_status=='Yes')
                                            <span class="badge bg-success"><b>
                                                    {{ 'Advance Adjusted' }}
                                                </b>
                                            </span>
                                            @elseif($list->advance_received=='Yes')
                                            <span class="badge btn-secondary"><b>
                                                    {{ $list->advance_received=='Yes'?'Advance Receipt':'' }}
                                                </b>
                                            </span>
                                            @endif

                                        </a>
                                    </td>
                                    <td>{{ $list->paymentVoucherDetail->account->account_title->name ?? '' }} {{ $list->paymentVoucherDetail->account->name ?? '' }}
                                        <br>
                                        @if(isset($list->user->prepared_by))
                                        <div style="color:#aaa">By: {!! $list->user->prepared_by??'' !!}</div>
                                        @endif
                                    </td>
                                    <td>{{ $list->paymentVoucherDetail->voucherType->name ?? '' }}</td>
                                    <td>
                                            <b>
                                                @if(isset($list->paymentVoucherDetail->voucherType->name) && $list->paymentVoucherDetail->voucherType->name=="OPD Booking")
                                                {{ $list->opdBooking->booking_no ?? '' }}
                                                @else
                                                {!! $list->salesVoucher->voucher_type_invoice_no??'' !!}
                                                @endif
                                            </b>
                                    </td>
                                    <td style="white-space: break-spaces;">{{ $list->paymentVoucherDetail->details_narration ?? '' }}</td>
                                    <td style="text-align: right;">{{ isset($list->paymentVoucherDetail->amount) ? convertDecimelPoint($list->paymentVoucherDetail->amount) : '' }}</td>
                                    <td style="text-align: center;">
                                        <a href="{{route('print-payment-voucher',$list->id)}}?redirect=purchase/collection-list/{{$purchase_invoice->id}}/{{$voucherType->code}}" class="btn btn-success" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Print">
                                            <i class="bi bi-printer text-white"></i>
                                        </a>
                                    </td>
                                    @if(in_array('payment-voucher-edit', $authRolePermissions))
                                    <td style="text-align: center;">
                                        <a href="{{route('payment-voucher.edit',$list->id)}}" class="btn btn-warning edit" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                                            <i class="bi bi-pencil-square text-white"></i>
                                        </a>
                                    </td>
                                    @endif
                                    @if(in_array('payment-voucher-delete', $authRolePermissions))
                                    <td style="text-align: center;"><a data-url="{{route('payment-voucher-delete')}}" data-id="{{$list->id}}" class="btn btn-danger deleteDataCustom" href="#" class="text-danger" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete"><i class="bi bi-trash text-white"></i></a></td>
                                    @endif
                                </tr>
                                @php $i++; @endphp
                                @endforeach
                                @else
                                <tr>
                                    <td colspan="9">No Data Found</td>
                                </tr>
                                @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!--end row-->

@endsection

@section('js')
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>

<script>
    $(function() {
        $('.datepickers').datepicker();
    });
    $(document).on('click', '.save_button', function(e) {
        e.preventDefault();

        //$('.error_voucher_no').hide();
        $('.error_receipt_date').hide();
        $('.error_account_id').hide();
        $('.error_due_amount').hide();
        //$('.error_description').hide();
        /*$('.error_details_narration').hide();*/
        $('.error_duplicate_voucher_no').hide();
        var error = 0;


        if ($('[name="receipt_date"]').val().trim() == '' || $('[name="receipt_date"]').val() == undefined) {
            $('.error_receipt_date').show();
            error = 1;
        }

        if ($('[name="account_id"]').val() == '' || $('[name="account_id"]').val() == undefined) {
            $('.error_account_id').show();
            error = 1;
        }

        @if(isset($redirect) && $redirect == 'lab-billings')
        if ($('[name="due_amount"]').val() < 0) {
            $('.error_due_amount').show();
            error = 1;
            toastr.error("Due Amount can not be negative!", 'Error!');
        }
        if ($('[name="received_amount"]').val() == '') {
            error = 1;
            toastr.error("Received Amount can not be empty!", 'Error!');
        }
        @endif

        /*if ($('#remarks').val() == '' || $('#remarks').val() == undefined) {
          $('.error_description').show();
          error = 1;
        }*/
        var totalAmount = 0;
        $('.amount').each(function() {
            totalAmount += parseFloat($(this).val()) || 0;
        });

        if (totalAmount == '' || totalAmount == 0) {
            toastr.error('Transaction amount can not be 0!', 'Error!');
            error = 1;
        }

        if (error == 0) {
            $('.create_billing').submit()
        }
    });

    $(document).on('change input', '.amount', function(e) {
        var totalAmount = 0;
        var received_amount = $('#purchase_invoice_received_amount').val();

        $('.amount').each(function() {
            totalAmount += parseFloat($(this).val()) || 0;
        });

        @if(isset($redirect) && $redirect == 'lab-billings')
        $('.due_amount').val($('.collection_amount').val() - totalAmount - received_amount);
        @endif
        var total = parseInt(totalAmount) + parseInt(received_amount);
        $('[name="total_amount"]').val(total);
        $('[name="received_amount"]').val(total);
    });

    $(document).on('click', '.add_to_cart', function(e) {
        e.preventDefault();

        //$('.error_voucher_no').hide();
        $('.error_transaction_date').hide();
        $('.error_account_id').hide();
        //$('.error_description').hide();
        /*$('.error_details_narration').hide();*/
        $('.error_duplicate_voucher_no').hide();
        var error = 0;
        /*
        if ($('input[name="voucher_no"]').val().trim() == '') {
          $('.error_voucher_no').show();
          error = 1;
        }
        */
        if ($('[name="transaction_date"]').val().trim() == '' || $('[name="transaction_date"]').val() == undefined) {
            $('.error_transaction_date').show();
            error = 1;
        }
        if ($('[name="account_id"]').val() == '' || $('[name="account_id"]').val() == undefined) {
            $('.error_account_id').show();
            error = 1;
        }

        if ($('#remarks').val() == '' || $('#remarks').val() == undefined) {
            $('.error_description').show();
            error = 1;
        }

        /*if ($('[name="details_narration"]').val() == '' || $('[name="details_narration"]').val() == undefined) {
          $('.error_details_narration').show();
          error = 1;
        }*/
        /*var productIds = $('.cart-products').map(function() {
            return $(this).data('voucher_no').toString();
        }).get();
        */
        if (error == 0) {
            let formdata = new FormData($('.create_billing')[0]);

            $.ajax({
                    url: $('.create_billing').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            fetch_cart();

                            $('#details_narration').val('');
                            $('#account_id').val('');
                            $('[name="debit"]').val('');
                            $('[name="credit"]').val('');
                            $('[name="account_id"]').val('');

                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
        }

        error = 1;
    })

    $(document).on('keyup', '.amount', function(e) {
        e.preventDefault();
        if (e.target.name == 'debit') {
            $('[name="debit"]').val($.trim(this.value));
            $('[name="credit"]').val();
        } else {
            $('[name="credit"]').val($.trim(this.value));
            $('[name="debit"]').val();
        }
    });

    $(document).ready(function() {

        $('.accounts-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="account_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('journal-voucher-search-accounts') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'get_accounts_for_journal_voucher',
                        search_text: request.term
                    },
                    success: function(json) {
                        ;
                        if (json.error) {
                            $('[name="account_id"]').val('');
                            return false;
                        };
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                ;
                event.preventDefault();
                $(this).val(ui.item.name + "");
                $('[name="account_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            ;
            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };
    });

    const patientSelect = document.querySelector(".accounts-select");
    const querySelector = document.querySelector(".searchResult");

    document.addEventListener("click", (event) => {
        if (event.target !== patientSelect && event.target !== querySelector) {
            $(".searchResult").empty();
        }
    });

    $(document).on('click', '#create_patient', function() {
        $('#commonModalLabel').text('Add New Patient');
        $('.save_button_span').text('Save Patient');
        $.ajax({
            url: "{!! route('patient-account-create') !!}",
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
                reinitializeTelInput();
                $('[name="date_of_birth"]').datepicker('destroy');

                $('[name="date_of_birth"]').datepicker({
                        "dateFormat": "dd-mm-yy",
                        "maxDate": '0',
                        "changeMonth": true,
                        "changeYear": true
                    }).datepicker("setDate", 'now')
                    .on('changeDate', function(ev) {
                        $(this).datepicker('hide');
                    })
                    .on('focusout', function(ev) {
                        $(this).datepicker('hide');
                    });
            }
        })
    })

    $(document).on('click', '#create_doctor', function() {
        $('#commonModalLabel').text('Add New Doctor');
        $('.save_button_span').text('Save Doctor');
        $.ajax({
            url: "{!! route('doctor-account-create') !!}",
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
                reinitializeTelInput();
                $('[name="date_of_birth"]').datepicker('destroy');

                $('[name="date_of_birth"]').datepicker({
                        "dateFormat": "dd-mm-yy",
                        "maxDate": '0',
                        "changeMonth": true,
                        "changeYear": true
                    }).datepicker("setDate", 'now')
                    .on('changeDate', function(ev) {
                        $(this).datepicker('hide');
                    })
                    .on('focusout', function(ev) {
                        $(this).datepicker('hide');
                    });
            }
        })
    })

    $(document).on('click change', '#account_id', function() {
        $('[name="search_product"]').val('');
        $('.create_billing [name="product_price"]').val('');
        $('#search_product').val('');
    })

    $(document).on('focusout', '[name="product_details"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('voucher_no'),
                "product_details": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    $(document).on('focusout', '[name="vial_code"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('voucher_no'),
                "vial_code": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    $(document).on('focusout', '.cart_products [name="product_price"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('voucher_no'),
                "product_price": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    $(document).on('focusout', '.cart_products [name="per_discount"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('voucher_no'),
                "per_discount": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    $(document).on('focusout', '.cart_products [name="flat_discount"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('voucher_no'),
                "flat_discount": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    $(document).on('focusout', '.cart_products [name="per_discount"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('voucher_no'),
                "per_discount": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    /*********delete data**********/
    $("body").on("click", '.deleteDataCustom', function(event) {
        dataString = {
            "id": $(this).data('id')
        };
        var UrlValue = $(this).data('url');
        var btn = $(this);

        Swal.fire({
            title: 'Are you sure you want to delete this?',
            icon: 'warning',
            showDenyButton: true,
            showCancelButton: false,
            confirmButtonText: 'Yes',
            denyButtonText: 'No',
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    url: UrlValue,
                    method: 'post',
                    data: {
                        "_token": $('meta[name="csrf-token"]').attr('content'),
                        "id": $(this).data('id')
                    },
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    beforeSend: function(xhr) {
                        // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },
                    success: function(response) {
                        ;
                        if (response.success) {
                            toastr.success(response.message, 'Success.');
                            fetch_cart();;
                        } else {
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('error', ErroMsg);
                        }
                    },
                    error: function(data) {
                        console.log("error ", data);
                    }
                });
            }
        });
    });

    function getAge(birthdate) {
        if (birthdate != '' && birthdate != null && birthdate != undefined) {
            var birthdateObj = new Date(birthdate);
            var now = new Date();
            var age = now.getFullYear() - birthdateObj.getFullYear();

            // Adjust age if birthday hasn't occurred this year yet
            if (now.getMonth() < birthdateObj.getMonth() || (now.getMonth() === birthdateObj.getMonth() && now.getDate() < birthdateObj.getDate())) {
                age--;
            }
            return age;
        }
    };
</script>
@endsection