@extends('backend.layouts.master')

@section('title')
    {{ $title }}
@endsection
@section('navbar-content')
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0"> QC </h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="{{ route('home') }}">Dashboard</a></li>
                        @if (helper::roleAccess('assets.category.index'))
                            <li class="breadcrumb-item"><a href="{{ route('assets.category.index') }}"> QC </a></li>
                        @endif
                        <li class="breadcrumb-item active"><span> QC list</span></li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
@endsection

@section('admin-content')
    <div class="row">
        <div class="col-md-12">
            <div class="card card-default">
                <div class="card-header">
                    <h3 class="card-title">Create QC</h3>
                    <div class="card-tools">
                        @if (helper::roleAccess('delivery.qc.index'))
                            <a class="btn btn-default" href="{{ route('delivery.qc.index') }}"><i
                                    class="fa fa-list"></i>
                                Create QC</a>
                        @endif
                        <span id="buttons"></span>

                        <a class="btn btn-tool btn-default" data-card-widget="collapse">
                            <i class="fas fa-minus"></i>
                        </a>
                        <a class="btn btn-tool btn-default" data-card-widget="remove">
                            <i class="fas fa-times"></i>
                        </a>
                    </div>
                </div>
                <!-- /.card-header -->
                <div class="card-body">
                    <form class="needs-validation" method="POST" action="{{ route('delivery.qc.store') }}"
                    novalidate>
                    @csrf
                    <div class="col-md-12 d-flex justify-content-between">
                        <div class="col-md-6 ">
                            <div class="form-group">
                                <label for="">Date</label>
                                <input type="date" name="date" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="product">Order List</label>
                                <select class="form-control select2" id="purreq" name="order_voucher">
                                    <option value="">Select Order</option>
                                    @foreach ($orders as $order)
                                        <option value="{{ $order->id }}">
                                            {{ $order->order_code }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>
                    

                    <table class="table table-bordered table-hover" id="show_item">
                        <thead>
                            <tr>
                                <td class="text-center" style="width:10%"><strong>Product</strong></td>
                                <td class="text-center" style="width:10%"><strong>Size</strong></td>
                                <td class="text-center" style="width:10%"><strong>Color</strong></td>
                                <td class="text-center" style="width:10%"><strong>Unit</strong></td>
                                <td class="text-center" style="width:10%"><strong>Order Quantity</strong></td>
                                <td class="text-center" style="width:10%"><strong>Approve</strong></td>
                                <td class="text-center" style="width:10%"><strong>Remaining</strong></td>
                            </tr>
                        </thead>
                        <tbody id="main-table">
           
                        </tbody>

                        <tfoot>
                         
                        </tfoot> 

                    </table>
                    <div class="d-flex justify-content-start mt-2 ">
                        <div class="form-group d-block mr-5">
                            <label for="">Note</label>
                            <textarea name="note" id="" cols="30" rows="5" class="form-control"></textarea>
                        </div>
                    </div>
                    <button class="btn btn-info" type="submit"><i class="fa fa-save"></i> &nbsp;Save</button>

                    </form>

                </div>



            </div>

        </div>
    </div>
    <!-- /.col-->
    </div>


    <script>
        $(document).ready(function() {

            $('#purreq').on('change', function() {
                let id = $(this).val();

                $.ajax({
                    url: "{{ route('delivery.qc.searchgrn') }}",
                    method: 'GET',
                    data: {
                        "_token": "{{ csrf_token() }}",
                        id: id
                    },
                    dataType: 'json',
                    success: function(data) {
                        $('#main-table').html(data.prdetails);
                        $('tfoot').html(data.footer);
                 
                    }
                })
            })


            function durculect() {
                var grandtotal = 0;

                $.each($('.total'), function(index, item) {
                    total = number_format($(item).val());
                    grandtotal += total;
                });
                var advancepayment = $('#advancepayment').val();
                var due = grandtotal - parseInt(advancepayment);
                $('.cart_due').text(due);
                $('.input-checker').val();
            }

            $('.paymentval').on('keyup change', function() {
                var grandtotal = 0;

                $.each($('.total'), function(index, item) {
                    total = number_format($(item).val());
                    grandtotal += total;
                });

                var advancepayment = $('#advancepayment').val();
                var due = grandtotal - parseInt(advancepayment);
                var payment = $(this).val();
                if (payment <= due) {
                    var amount = due - payment;
                } else {
                    // alert('Payment Amount can not greater than ' + due + ' amount');
                    alertMessage.error('Payment Amount can not greater than ' + due + ' amount')
                    $(this).val('');
                    durculect()
                }

                $('.cart_due').text(amount);

            })

            var findqtyamoun = function () {
            var ttlqty = 0;
            var approve = 0;
            var remaining = 0;

            $.each($('.ttlqty'), function () {
                console.log($(this).val());
                qty = number_format($(this).val());
                ttlqty += qty;
            });
            $.each($('.approve'), function () {
                console.log($(this).val());
                qty = number_format($(this).val());
                approve += qty;
            });
            $.each($('.remaining'), function () {
                console.log($(this).val());
                qty = number_format($(this).val());
                remaining += qty;
            });
            $('.ttlqty').text(number_format(ttlqty));
            $('.approvett').text(number_format(approve));
            $('.remainingtt').text(number_format(remaining));

        };

            var findunitamount = function() {
                var ttlunitprice = 0;
                $.each($('.ttlunitprice'), function() {
                    unitprice = number_format($(this).val());
                    ttlunitprice += unitprice;
                });
                $('.ttlunitprice').text(number_format(ttlunitprice));
            };

            var findgrandtottal = function() {
                var grandtotal = 0;

                $.each($('.total'), function(index, item) {
                    total = number_format($(item).val());
                    grandtotal += total;
                });

                // let vatE = $('.vat');
                let discountE = $('.discount');
                let paidAmountE = $('.paid_amount');

                let vat = 0; //number_format(vatE.val());
                let discount = number_format(discountE.val());
                let paidAmount = number_format(paidAmountE.val());
                //calculate discount
                let cal_vat = percentageCalculate(grandtotal, vat);
                let cal_grandtotal = grandTotalCalculate(grandtotal, discount, cal_vat);

                let cart_net_total = $('.cart_net_total');

                $('.grandtotal').text(number_format(grandtotal));
                cart_net_total.text(cal_grandtotal);

            };


            $(document).on('click', '.delete_item', function() {
                // if (confirm("Are you sure?")) {
                //     // $(this).parents('tr').remove();
                //     // findqtyamoun();
                //     // findunitamount();
                //     // findgrandtottal();
                // }

                let deleteitem = () => {
                    $(this).parents('tr').remove();
                    findqtyamoun();
                    findunitamount();
                    findgrandtottal();
                }

                alertMessage.confirm('You want to remove this', deleteitem);
            });

            // check payment type by joy
            $(document).on('change', '.payment_type', function() {
                const self = $(this);
                const val = self.val();

                if (val == '' || val == null || val == 0) {
                    return false;
                }
                checkTypeAndGetAccountInfo(val);

            });

            // get account balance and show by html
            $(document).on('change', '.accounts', function() {
                // settings.transfer.checkBalance
                const self = $(this);
                const val = self.val();

                if (val == '' || val == null || val == 0) {
                    return false;
                }
                getBalance(val);
            });

            // Quantity price calculate
            $(document).on('input', '.qty', function() {
                let self = $(this);
                var requestQty = self.closest('tr').find('.ttlqty').val();
                var approve = self.closest('tr').find('.approve').val();
                var totalval = requestQty - approve;
                var value = self.val();
                if (totalval + 1 <= value) {
                    // alert('Remaining quantity cannot greater than Requested quantity')
                    alertMessage.error('Remaining quantity cannot greater than Requested quantity');
                    self.val(0);
                }
                let parent = self.parents('tr');
                let qty = number_format(self.val());

                if (qty == '' || qty == null) {
                    $(this).val(0);
                    qty = 0;
                }

                let unitPrice = number_format(parent.find('.unitprice').val());

                let total = number_format(unitPrice * qty);

                parent.find('.total').val(number_format(total));
                findqtyamoun();
                findgrandtottal();
                durculect()
            });

            $(document).on('input', '.input-checker', function() {
                var grandtotal = $('.grandtotal').text();
                grandtotal = Number(grandtotal);

                if (isNaN(grandtotal) || grandtotal < 1) {
                    // alert('Please Add some item first.');
                    alertMessage.error('Please Add some item first.');
                    return false;
                }
                findgrandtottal();

            });



            $(document).on('change', '.payment_type', function() {

                let payment_type = $(this).val();
                if (payment_type == '' || payment_type == null) {
                    $('#submit').prop('disabled', true);
                    $('.paid_amount').prop('readonly', true);
                } else {
                    $('.paid_amount').prop('readonly', false);
                }

            });

            $(document).on('keyup', '.paid_amount', function() {
                let paidAmount = number_format($(this).val());
                let balance = number_format($('.balance').val());
                console.log(balance)
                let paymentType = $('.payment_type').val();

                if (paymentType.toLowerCase() == 'cash' && balance < paidAmount) {
                    $('#submit').prop('disabled', true);we

                    $('.payment_amount_error').html(
                        '<span class="error text-red text-bold">Payed amount cannot be greater then balance.</span>'
                    );

                } else {
                    $('#submit').prop('disabled', false);
                    $('.payment_amount_error').html('')
                }
            });

        });
    </script>
@endsection
