<div class="col-md-6 hide">
    <div class="form-group">
        <label>الموظف</label>
        <select class="form-control empList">
            <option value="">بدون</option>
            <?php $__currentLoopData = $employees; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $id => $name): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <option value="<?php echo e($id); ?>"><?php echo e($name); ?>

                </option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </select>
    </div>
</div>
<?php $__env->startPush('js'); ?>
    <script>
        $(".select2").select2();
        $(document).on("change", "#personList", function(e) {
            e.preventDefault();
            if ($(this).val()) {
                $.ajax({
                    url: "<?php echo e(route('person.getDetails')); ?>",
                    type: 'GET',
                    data: {
                        'p_id': $(this).val()
                    },
                    success: function(result) {
                        var obj = JSON.parse(result);
                        var total_due = parseFloat(obj.total_due).toFixed(1);
                        $("#lastBalance").val(total_due);
                        $(".lastBalance").html("( <?php echo e(trans('front.previous balance')); ?>" + total_due +
                            " )");
                        $("#priceType").val(obj.priceType);
                        $("#last_transaction").html(obj.last_transaction);
                        if (obj.points) {
                            $(".userpointSpan").html(obj.points);
                            $(".userpointSpan").removeClass('hide');
                        } else {
                            $(".userpointSpan").addClass('hide');
                        }
                    }
                });
            }
        });
        $(document).on('click', '.saveandPrint', function(e) {
            e.preventDefault();
            if ($("#personList").val()) {
                $('#savePrint').val('print');
                $('form').submit();
            } else {
                swal({
                    title: 'خطأ',
                    text: "يجب استكمال بيانات الفاتورة",
                    type: "error",
                    confirmButtonText: "تمام",
                });
            }
        });
        $(document).on('click', '.addFirstUnit', function(e) {
            e.preventDefault();
            $(this).closest('.posItem').find('.prices a:first').trigger('click');
        });




        $(document).on("click", ".removeItem", function(e) {
            e.preventDefault();
            $(this).closest('.itemRow').remove();
        });
        $(document).on("click", ".itemCard", function(e) {
            e.preventDefault();
            var selectdItem = $(this);
            addRow(selectdItem);
        });
        $(document).on("change", ".unitsPriceList", function(e) {
            var row = $(this).closest('tr');
            var price = row.find(".unitsPriceList option:selected").attr('price');
            var cost = row.find(".unitsPriceList option:selected").attr('cost');
            price = parseFloat(price);
            var itemPrice = row.find(".itemPrice").val(price);
            row.find(".itemCost").val(cost);
            row.find(".itemPrice").trigger("change");
        });

        function addRow(selectdItem) {
            productID = selectdItem.attr('prodid');
            unitPrice = selectdItem.attr('prodprice');
            cost = selectdItem.attr('cost');
            productName = selectdItem.attr('prodname');
            unit_id = selectdItem.attr('unit_id');
            store_id = $('#productStores').val();
            var storeName = $("#productStores option:selected").text();
            var unitName = selectdItem.attr('unitname');

            var productQty = 1;
            var total = unitPrice * productQty;
            total = parseFloat(total).toFixed(2);
            var rowClass = "rowelement" + productID + '_' + store_id + '_' + unit_id;
            var num = $('#invoiceTable tr').length + 1;
            if ($('.' + rowClass).length) {
                num = $('.' + rowClass).find('.rowIndex').val();
            }

            if ($('.' + rowClass).length) {
                productQty += parseInt($('.' + rowClass).find('.itemQty').val());
            }
            if ($('.' + rowClass).length) {
                num = $('.' + rowClass).find('.rowIndex').val();
            }
            var cloneUnitList = '<select name="product[' + num + '][unit_id]" class="unitsPriceList">';
            selectdItem.closest('.posItem').find(".prices a").each(function() {
                var unitname = $(this).attr('unitname');
                var ItemUid = $(this).attr('unit_id');
                var cost = $(this).attr('cost');
                var prodprice = $(this).attr('prodprice');
                if (unit_id == ItemUid) {
                    cloneUnitList += '<option selected cost="' + cost + '" price="' + prodprice + '" value="' +
                        ItemUid + '">' + unitname + '</option>';
                } else {
                    cloneUnitList += '<option cost="' + cost + '" price="' + prodprice + '" value="' + ItemUid +
                        '">' + unitname + '</option>';
                }
            });
            cloneUnitList += '</select>';

            var clonedSelect = $(".empList").clone();
            clonedSelect.attr("name", 'product[' + num + '][employee_id]');
            clonedSelect.prop('required',true);
            clonedSelect.removeClass("empList");
            var employeeSelect = clonedSelect.prop('outerHTML');
            if ($('.' + rowClass).length) {
                var oldqty = $('.' + rowClass).find(".itemQty").val();
                total = unitPrice * productQty;
                total = parseFloat(total).toFixed(2);
                num = $('.' + rowClass).find('.rowIndex').val();
                var completeProcess = false;

                swal({
                        title: " تحذير! الصنف مكرر بكمية " + oldqty,
                        text: "هل تريد الإضافة عليه؟ " + " ستصبح الكمية الجديدة " + productQty,
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD4140",
                        closeOnConfirm: true,
                        showLoaderOnConfirm: false,
                        cancelButtonText: "إلغاء",
                        confirmButtonText: "نعم متأكد",
                    },
                    function() {

                        var data = '<td>' +
                            '<input type="hidden" class="rowIndex" value="' + num + '">' +
                            '<input type="hidden" name="product[' + num + '][product_name]" value="' + productName +
                            '">' +
                            '<input class="itemCost" type="hidden" name="product[' + num + '][cost]" value="' + cost +
                            '">' +
                            //  '<input type="hidden" name="product[' + num + '][unit_id]" value="' + unit_id + '">' +
                            '<input class="rowUnit_name" type="hidden" name="product[' + num + '][unit_name]" value="' +
                            unitName + '">' +
                            '<input type="hidden" name="product[' + num + '][store_name]" value="' + storeName + '">' +
                            '<input type="hidden" name="product[' + num + '][store_id]" value="' + store_id + '">' +
                            '<input type="hidden" name="product[' + num + '][status]" value="معلق">' +
                            num +
                            '</td>' +
                            '<td><input type="hidden" name="product[' + num + '][product_id]" value="' + productID +
                            '">' + productName + '</td>' +
                            '<td class="hide"><input class = "itemQty tdinput" type="number" name="product[' + num +
                            '][qty]" value="' + productQty + '"></td>' +
                            '<td class="hide">' + cloneUnitList + '</td>' +
                            '<td><input class="itemPrice tdinput" type="number" name="product[' + num +
                            '][price]" value="' + unitPrice + '"></td>';
                        data +=
                            '<td class="hide"><input class="itemTotal tdinput" readonly type="text" name="product[' +
                            num +
                            '][total]" value="' + total + '"></td>';
                        data += '<td><input class="tdinput" type="text" name="product[' + num +
                            '][comment]" value=""></td>';
                        data += '<td>' + employeeSelect + '</td>';
                        data += '<td><input required style="direction: rtl;" name="product[' + num +
                            '][serive_datetime]" type="datetime-local" value="" class="form-control"></td>';

                        data +=
                            '<td><a href="#" class="btn btn-sm btn-danger removeItem"><i class="fa fa-trash"></i></a></td>';
                        if ($('.' + rowClass).length) {
                            $('.' + rowClass).html(data);
                        } else {
                            $("#invoiceTable").append('<tr class="itemRow ' + rowClass + '">' + data + '</tr>');
                        }
                        calculateTotal();
                        toastr.success("تمت إضافة " + productQty + " " + " للصنف " + productName + " للفاتورة");
                        // $typeaheadSearch.typeahead('val','');
                        // $typeaheadSearch.focus();
                        // $("#unitPrice").val('');
                        // $("#productID").val('');
                        // $("#productQty").val(1);
                        // setTimeout("$('[name=search_input]').focus();",500);
                        return true;

                    });

            } else {
                var data = '<td>' +
                    '<input type="hidden" class="rowIndex" value="' + num + '">' +
                    '<input type="hidden" name="product[' + num + '][product_name]" value="' + productName + '">' +
                    '<input class="itemCost" type="hidden" name="product[' + num + '][cost]" value="' + cost + '">' +
                    //'<input type="hidden" name="product[' + num + '][unit_id]" value="' + unit_id + '">' +
                    '<input class="rowUnit_name" type="hidden" name="product[' + num + '][unit_name]" value="' + unitName +
                    '">' +
                    '<input type="hidden" name="product[' + num + '][store_name]" value="' + storeName + '">' +
                    '<input type="hidden" name="product[' + num + '][store_id]" value="' + store_id + '">' +
                    '<input type="hidden" name="product[' + num + '][status]" value="معلق">' +
                    num +
                    '</td>' +
                    '<td><input type="hidden" name="product[' + num + '][product_id]" value="' + productID + '">' +
                    productName + '</td>' +
                    '<td class="hide"><input class = "itemQty tdinput" type="text" name="product[' + num +
                    '][qty]" value="' +
                    productQty + '"></td>' +
                    '<td class="hide">' + cloneUnitList + '</td>' +
                    '<td><input class="itemPrice tdinput" type="text" name="product[' + num + '][price]" value="' +
                    unitPrice + '"></td>';
                data += '<td class="hide"><input class="itemTotal tdinput" readonly type="text" name="product[' + num +
                    '][total]" value="' + total + '"></td>';
                data += '<td><input class="tdinput" type="text" name="product[' + num +
                    '][comment]" value=""></td>';
                data += '<td>' + employeeSelect + '</td>';
                data += '<td><input required style="direction: rtl;" name="product[' + num +
                    '][serive_datetime]" type="datetime-local" value="" class="datepicker serive_datetime form-control"></td>';

                data += '<td><a href="#" class="btn btn-sm btn-danger removeItem"><i class="fa fa-trash"></i></a></td>';
                if ($('.' + rowClass).length) {
                    $('.' + rowClass).html(data);
                } else {
                    $("#invoiceTable").append('<tr class="itemRow bg-success ' + rowClass + '">' + data + '</tr>');
                }
                //var newInputDatepicker = $("#invoiceTable .datepicker").last();
                //initializeDateTimePicker(newInputDatepicker);
                calculateTotal();
                toastr.success("تمت إضافة " + productQty + " " + " للصنف " + productName + " للفاتورة");
                // $typeaheadSearch.typeahead('val','');
                // $typeaheadSearch.focus();
                // $("#unitPrice").val('');
                // $("#productID").val('');
                // $("#marketer").val(0);
                // $("#productQty").val(1);
                // $("#CostPriceSpan").html('');
                return false;
            }


        }

        $(document).on("input", "#paid", function(e) {
            e.preventDefault();
            var discountPercent = $("#discount_type").is(':checked');
            var discount = 0;
            var lastBalance = 0;
            if ($("#discount").val()) {
                discount = parseFloat($("#discount").val());
            }
            if ($("#lastBalance").val()) {
                lastBalance = parseFloat($("#lastBalance").val());
            }
            var paid = parseFloat($("#paid").val());
            var grandtotal = parseFloat($("#total").val());
            if (discountPercent) {
                grandtotal -= (grandtotal * (discount / 100));
            } else {
                grandtotal -= discount;
            }
            var tax = parseFloat($("#tax").val());

            var PriceIncludesTax = "<?php echo e($settings['PriceIncludesTax'] ?? 'no'); ?>";
            TaxValue = 0;
            if (PriceIncludesTax == "no") {
                var TaxValue = (grandtotal * (tax / 100));
            }
            $("#TaxValue").val(TaxValue);

            grandtotal += TaxValue;
            <?php if($settings['rounding_up'] == 1): ?>
                grandtotal = Math.ceil(grandtotal);
            <?php endif; ?>
            grandtotal = parseFloat(grandtotal.toFixed(2));
            $("#totalafter").val(grandtotal);
            var due = 0;
            if ($("#paymentMethod").val() == 'delayed') {
                due = grandtotal - paid;
                due = parseFloat(due).toFixed(2);
                $("#due").val(due);
            } else {
                var due = 0;
                if ($("#paymentMethod").val() == 'cash' || $("#paymentMethod").val() == 'visa') {
                    $("#paid").val(grandtotal);
                    $("#due").val(0);
                } else {
                    due = grandtotal - paid;
                    due = parseFloat(due).toFixed(1);
                    $("#due").val(due);
                }
            }
            var TotalBal = parseFloat(due) + parseFloat(lastBalance);
            var totalBalance = TotalBal.toFixed(1);
            $("#totalBalance").val(totalBalance);
        });
        $('input[type="checkbox"].flat-red').iCheck({
            checkboxClass: 'icheckbox_flat-green',
            radioClass: 'iradio_flat-green'
        });
        $(document).on('ifChanged', '#discount_type', function() {
            calculateTotal();
        });
        $(document).on("input", "#tax,#discount", function(e) {
            calculateTotal();
        });

        function calculateTotal() {
            var grandtotal = 0;
            $(".itemTotal").each(function() {
                grandtotal += parseFloat($(this).val());
            });


            grandtotal = parseFloat(grandtotal).toFixed(2);
            $("#total").val(grandtotal);

            $("#paid").trigger("input");
            var lastBalance = 0;
            if ($("#lastBalance").val()) {
                lastBalance = parseFloat($("#lastBalance").val());
            }

            var TotalBal = parseFloat($("#due").val()) + parseFloat(lastBalance);
            var totalBalance = TotalBal.toFixed(1);
            $("#totalBalance").val(totalBalance);
        }
        $(document).on("change", ".itemQty,.itemPrice", function(e) {
            var row = $(this).closest('tr');
            var qty = row.find(".itemQty").val();
            var itemPrice = row.find(".itemPrice").val();
            var total = parseFloat(qty) * parseFloat(itemPrice);
            row.find(".itemTotal").val(total.toFixed(2));
            calculateTotal();
        });

        // function initializeDateTimePicker(element) {
        //     $(element).datetimepicker({
        //         format: 'YYYY-MM-DD hh:mm A',
        //         sideBySide: true,
        //         toolbarPlacement: "bottom",
        //         showTodayButton: true,
        //         showClear: true,
        //         showClose: true,
        //         useCurrent: true,
        //         keepOpen: true,
        //         locale: "en"
        //     });
        // }
        //initializeDateTimePicker('.datepicker');
    </script>
<?php $__env->stopPush(); ?>
<?php $__env->startPush('css'); ?>
    <style>
        .nav-tabs-vertical {
            display: flex;
            flex-direction: column;
        }

        .nav-tabs-vertical .nav-tabs {
            height: 400px;
            overflow-y: auto;
            border-bottom: none;
        }

        .nav-tabs-vertical .nav-tabs li {
            float: none;
            margin-bottom: 5px;
        }


        a.addFirstUnit img:hover {
            transform: scale(1.1);
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
        }

        .posItem {
            text-align: center;
            border: 1px solid #000;
            padding: 10px;
            /* height: 180px; */
        }

        p.prodname {
            height: 50px;
        }

        .prices {
            font-size: 18px;
        }

        .posItem img {
            max-width: 40px;
            /* height: 100px; */
        }

        .posItem a:hover span {
            background-color: #e08e0b !important;
            font-weight: bold;
        }

        .posItem a {
            margin-bottom: 3px;
            text-decoration: none;
        }

        input.tdinput:focus {
            background-color: #fff !important;
        }

        input.tdinput {
            display: block;
            width: 100%;
            height: 28px;
            padding: 0;
            font-size: 14px;
            line-height: 1.42857143;
            color: #555;
            background-color: #dff0d8;
            border: 0px solid #fff;
            border-radius: 4px;
            border: 0px solid #fff !important;
            text-align: center;
        }
    </style>
<?php $__env->stopPush(); ?>
