<?php $__env->startComponent('components.widget', ['class' => 'box-primary']); ?>
    <table class="table table-bordered table-striped hide-footer" style="width: 100%;" id="shipping-product-table">
        <thead>
        <tr>
            <th><?php echo app('translator')->get('sale.product'); ?></th>
            <th><?php echo e(__("lang_v1.location_from"), false); ?></th>
            <th><?php echo e(__('tpsTransfer::lang.transfer_qty'), false); ?></th>
            <th><?php echo e(__('tpsTransfer::lang.unit_price_before_shipping'), false); ?></th>
            <th><?php echo e(__('tpsTransfer::lang.total_price_before_shipping'), false); ?></th>
            <th><?php echo e(__('tpsTransfer::lang.shipping_ratio'), false); ?></th>
            <th><?php echo e(__('tpsTransfer::lang.shipping_value_unit'), false); ?></th>
            <th><?php echo e(__('tpsTransfer::lang.unit_price_after_shipping'), false); ?></th>
            <th><?php echo e(__('tpsTransfer::lang.total_price_after_shipping'), false); ?></th>
        </tr>
        </thead>
    </table>
<?php echo $__env->renderComponent(); ?>
<?php $__env->startComponent('components.widget', ['class' => 'box-primary']); ?>
    <div class="row">
        <div class="col-md-4">
            <div class="form-group">
                <?php echo Form::label('shipping_details', __('sale.shipping_details'). ' :'); ?>

                <?php echo Form::text('shipping_details',null, ['class' => 'form-control','placeholder' => __('sale.shipping_details')]); ?>

            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                <?php echo Form::label('shipping_method', __('tpsTransfer::lang.shipping_method')).':'; ?>

                <?php echo Form::select('shipping_method', $shippingMethods, $setting['shippingMethod'] ?? null, ['id' => 'shipping_method', 'class' => 'form-control', 'style' => 'width:100%']); ?>

            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                <?php echo Form::label('shipping_charges', __('tpsTransfer::lang.additional_shipping_charges')).':'; ?>

                <?php echo Form::number('shipping_charges',null, ['id' => 'shipping_charges', 'class' => 'form-control','placeholder' => __('tpsTransfer::lang.additional_shipping_charges')]); ?>

            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-4">
            <div class="form-group">
                <?php echo Form::label('additional_expense_name', __('lang_v1.additional_expense_name')); ?>

            </div>
            <div class="form-group">
                <?php echo Form::text('additional_expense_key_1',null, ['id' => 'additional_expense_key_1', 'class' => 'form-control','placeholder' => __('lang_v1.additional_expense_name')]); ?>

            </div>
            <div class="form-group">
                <?php echo Form::text('additional_expense_key_2',null, ['id' => 'additional_expense_key_2', 'class' => 'form-control','placeholder' => __('lang_v1.additional_expense_name')]); ?>

            </div>
            <div class="form-group">
                <?php echo Form::text('additional_expense_key_3',null, ['id' => 'additional_expense_key_3', 'class' => 'form-control','placeholder' => __('lang_v1.additional_expense_name')]); ?>

            </div>
            <div class="form-group">
                <?php echo Form::text('additional_expense_key_4',null, ['id' => 'additional_expense_key_4', 'class' => 'form-control','placeholder' => __('lang_v1.additional_expense_name')]); ?>

            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                <?php echo Form::label('additional_expense_amount', __('sale.amount')); ?>

            </div>
            <div class="form-group">
                <?php echo Form::text('additional_expense_value_1',0, ['id' => 'additional_expense_value_1', 'class' => 'form-control','placeholder' => __('sale.amount')]); ?>

            </div>
            <div class="form-group">
                <?php echo Form::text('additional_expense_value_2',0, ['id' => 'additional_expense_value_2', 'class' => 'form-control','placeholder' => __('sale.amount')]); ?>

            </div>
            <div class="form-group">
                <?php echo Form::text('additional_expense_value_3',0, ['id' => 'additional_expense_value_3', 'class' => 'form-control','placeholder' => __('sale.amount')]); ?>

            </div>
            <div class="form-group">
                <?php echo Form::text('additional_expense_value_4',0, ['id' => 'additional_expense_value_4', 'class' => 'form-control','placeholder' => __('sale.amount')]); ?>

            </div>
        </div>
    </div>
<?php echo $__env->renderComponent(); ?>
<?php $__env->startComponent('components.widget', ['class' => 'box-primary', 'title' => __('purchase.add_payment')]); ?>
    <div class="box-body payment_row">
        <div class="row">
            <div class="col-md-12">
                <strong><?php echo app('translator')->get('lang_v1.advance_balance'); ?>:</strong> <span id="advance_balance_text">0</span>
                <?php echo Form::hidden('advance_balance', null, ['id' => 'advance_balance', 'data-error-msg' => __('lang_v1.required_advance_balance_not_available')]); ?>

            </div>
        </div>
        <?php echo $__env->make('sale_pos.partials.payment_row_form', ['row_index' => 0, 'show_date' => true], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
        <hr>
        <div class="row">
            <div class="col-sm-12">
                <div class="pull-right"><strong><?php echo app('translator')->get('purchase.payment_due'); ?>:</strong> <span id="payment_due">0.00</span></div>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-sm-12">

            </div>
        </div>
    </div>
<?php echo $__env->renderComponent(); ?>
<script type="text/javascript">
    let tpsShippingCalculation = new Object();

    $(document).ready(function () {
        __select2($('.select2'));
        // autoChangeDataTable();

        // Handle form submission event
        $('#add_product_modal_buttom').on('click', function (e) {
            // Prevent actual form submission
            e.preventDefault();

            // Send selected rows to products datatable
            reloadProductDatatable(temp_rows_selected)
            temp_rows_selected = [];
            // Hide add product modal
            $("#add_product").modal('hide');
        });
    });

    //change shipping method or value
    $(document).on('change', '#shipping_method, #shipping_charges',function () {
        if(($('#shipping_method').val() ) && ($('#shipping_charges').val() != '')){
            $('#shipping_method').attr('readonly', true).css("cursor", "not-allowed").find("option").prop("hidden", true);
            $('#shipping_charges').attr('readonly', true);

            $('#shipping-product-table').DataTable({
                processing: true,
                serverSide: true,
                scrollY: "130vh",
                scrollX: true,
                scrollCollapse: true,
                ajax: {
                    url: '<?php echo e(action('\Modules\TpsTransfer\Http\Controllers\TpsPrepareStockController@addShippingTable'), false); ?>',
                    type: "POST",
                    data: {
                        tpsData: <?php echo json_encode($tpsData); ?>,
                        shipping_method: $('#shipping_method').val(),
                        shipping_charges: $('#shipping_charges').val(),
                    },
                },
                aaSorting: [],
                columns: [
                    {data: "products_name", name: "products.name"},
                    {data: "from_location_name", name: "business_locations.name"},
                    {data: "transfer_quantity", name: "nst_prepare_products.transfer_quantity"},
                    {data: "purchase_price", name: "purchase_lines.purchase_price"},
                    {data: "total_price_before_shipping", name: "total_price"},
                    {data: "shipping_ratio", name: "shipping_ratio"},
                    {data: "shipping_value_per_unit", name: "shipping_value_per_unit"},
                    {data: "unit_price_after_shipping", name: "unit_price_after_shipping"},
                    {data: "total_price_after_shipping", name: "total_price_after_shipping"},
                ],
                lengthMenu: [[10, 25, 50, 200, 500], [10, 25, 50, 200, 500]],
                pageLength: 10,
                searchDelay: 10,
                rowCallback: function (row, data) {
                    // write old inputs
                    if(tpsShippingCalculation[data['id']]){
                        if(tpsShippingCalculation[data['id']]['shipping_ratio']){
                            $(row).find('.shipping_ratio').val(tpsShippingCalculation[data['id']]['shipping_ratio']);
                        }
                        if(tpsShippingCalculation[data['id']]['value_per_unit']){
                            $(row).find('#shipping_value_per_unit_'+data['id']).html(tpsShippingCalculation['value_per_unit']);
                        }
                    }else{
                        tpsShippingCalculation[data['id']] = {};
                        tpsShippingCalculation[data['id']]['shipping_ratio'] = $(row).find('.shipping_ratio').val();
                        tpsShippingCalculation[data['id']]['value_per_unit'] = $(row).find('.shipping_value_per_unit').html();
                        tpsShippingCalculation[data['id']]['unit_price_after_shipping'] = $(row).find('.unit_price_after_shipping').html();
                    }
                },
            });
        }
    });

    $(document).on('change', '.shipping_ratio',function () {
        id = $(this).attr('data-id');
        if(!tpsShippingCalculation[id]){
            tpsShippingCalculation[id] = {};
        }
        tpsShippingCalculation[id]['shipping_ratio'] = parseFloat($(this).val())

        // Sum all shipping ratio to prevent over 100%
        let totalShippingRatio = 0;
        $.each(tpsShippingCalculation, function (key, valueObj) {
            totalShippingRatio += parseFloat(valueObj['shipping_ratio']);
        });
        if (totalShippingRatio > 100) {
            toastr.error('<?php echo e(__('tpsTransfer::lang.sum_of_shipping_ratios_are_more_than_100'), false); ?>');
        }

        ratio = parseFloat($(this).val())
        shipping_value = parseFloat($('#shipping_charges').val())
        transfer_quantity = parseInt($(this).attr('data-transfer-quantity'))
        purchase_price = parseFloat($(this).attr('data-purchase-price'))
        total_transfer_quantity = parseInt($(this).attr('data-total-transfer-quantity'))

        value_per_unit = ((shipping_value * (ratio / 100)).toFixed(2)) /  transfer_quantity;
        tpsShippingCalculation[id]['value_per_unit'] = value_per_unit
        tpsShippingCalculation[id]['unit_price_after_shipping'] = purchase_price + value_per_unit;

        $('#shipping_value_per_unit_'+id).html(value_per_unit);
        $('#unit_price_after_shipping_'+id).html(purchase_price + value_per_unit);
        $('#total_price_after_shipping_'+id).html( (purchase_price + value_per_unit) * transfer_quantity);
    });

    $(document).on("click", "#confirm_shipping_modal_button", function (e) {
        // Prevent actual form submission
        e.preventDefault();
        let shipping_method = $('#shipping_method').val();

        // Sum all shipping ratio to prevent over 100%
        let totalShippingRatio = 0;
        $.each(tpsShippingCalculation, function (key, valueObj) {
            totalShippingRatio += parseFloat(valueObj['shipping_ratio']);
        });
        if (shipping_method !== 'as_charge' && totalShippingRatio !== 100) {
            toastr.error('<?php echo e(__('tpsTransfer::lang.sum_of_shipping_ratios_not_equal_100'), false); ?>');
            return;
        }

        $.blockUI({ message: '<?php echo e(__('tpsTransfer::lang.preparing_data'), false); ?>' });

        $('#shipping-product-table').DataTable().page.len( -1 ).ajax.reload( function() { //todo need testing
            $.blockUI({ message: '<?php echo e(__('tpsTransfer::lang.inserting_data'), false); ?>' });

            // Send data by ajax to server side to start auto process and return with products and qty
            $.ajax({
                type: 'PUT',
                url: '<?php echo e(action('\Modules\TpsTransfer\Http\Controllers\TpsPrepareStockController@storeShipping'), false); ?>',
                data: {
                    data: $('#add_shipping_table_form').serialize(),
                    tpsShippingCalculation: tpsShippingCalculation,
                    from_location_id: $('#from_location_id').val(),
                    to_location_id: $('#to_location_id').val(),
                },
                beforeSend: function() {
                    requestWaitingMessage()
                    $.blockUI({ message: $('#block-waiting-div') });
                    $("#add_shipping").modal('hide');
                },
                success: function(r) {
                    // console.log('success')
                    if((r.status) && (r.status == 'success')){
                        $.unblockUI();
                        if(r.redirect){
                            window.location.href = r.redirect;
                        }
                    }else{
                        $.unblockUI();
                        toastr.error('<?php echo e(__('tpsTransfer::lang.an_error_has_been_occurred'), false); ?>');
                        return;
                    }
                    return
                },
                error: function(xhr) { // if error occurred
                    $.unblockUI();
                    toastr.error('<?php echo e(__('tpsTransfer::lang.an_error_has_been_occurred'), false); ?>');
                    return;
                }
            });
        })
    });

    function autoChangeDataTable() {
        $('#shipping-product-table').DataTable().ajax.reload();
    }
</script><?php /**PATH /home/static/public_html/Modules/TpsTransfer/Providers/../Resources/views/shipping_modal.blade.php ENDPATH**/ ?>