<script>
	jQuery('.btn-add-product-transaction').on('click', function() {
		new_transaction();
	});

	jQuery('.btn-add-detail').on('click', function() {
		add_detail();
	});

	function add_detail() {
		var new_numb = jQuery('.table-detail .detail-numb').length;
		new_numb++;
		var table = '<tr>';
		table +=		'<td><input type="hidden" name="idtransaction_detail[]" class="detail-idtransaction-detail"><button class="btn btn-danger btn-remove-row" data-id="transaction-detail" type="button"><i class="fa fa-remove"></i></button></td>';
		table += 		'<td><input readonly type="text" class="form-control detail-numb numb" value="'+new_numb+'"></td>';
		table += 		'<td><input type="text" name="detail_description[]" class="form-control detail-description"></td>';
		table += 		'<td><input type="number" class="form-control detail-qty txt-center" name="detail_qty[]"></td>';
		table +=	'</tr>';

		jQuery(".table-detail tbody").append(table);
		calc_total_qty();		
	}

	calc_total_qty();
	jQuery('body').on('keyup keydown change mouseup', '.detail-qty', function() {
		calc_total_qty();
	});
	function calc_total_qty() {
		var total_qty = 0;
		jQuery('.detail-qty').each(function(adata, bdata) {
			var detail_qty = jQuery(bdata).val() || 0;
			total_qty += parseInt(detail_qty);
		});

		jQuery('.txt-total-qty').text(total_qty);
	}

	new_transaction();
	function new_transaction() {
		var tmp = jQuery('#tmp_transaction').html();

		var new_numb = jQuery('.table-transaction .numb').length;
		new_numb++;
		var table = tmp

		jQuery(".table-transaction > tbody").append(table);

		jQuery('.select-multi').select2();

        generate_add_id();
	}

	function new_transactionx() {
		var new_numb = jQuery('.table-transaction .numb').length;
		new_numb++;
		var table = '';
		table += '<tr>';
		table += '	<td><button class="btn btn-danger btn-remove-row" data-id="transaction" type="button"><i class="fa fa-remove"></i></button></td>';
		table += '	<td><input readonly type="text" class="form-control numb" value="'+new_numb+'"></td>';
		table += '	<td>';
		table += '		<input type="hidden" name="idtransaction[]" class="product-idtransaction">';
		table += '		<input type="hidden" name="idproduct[]" class="product-idproduct">';
		table += '		<div class="container-product-search">';
		table += '			<input readonly type="text" class="form-control product-name" placeholder="<?php echo azlang('Search Product');?>">';
		table += '			<button class="btn btn-default btn-search-product" type="button"><i class="fa fa-search"></i></button>';
		table += '		</div>';
		table += '	</td>';
		table += '	<td><input type="text" readonly class="form-control product-type"></td>';
		table += '	<td><input type="text" value="0,00" class="form-control product-price format-number-decimal" name="price[]"></td>';
		table += '	<td><input type="text" value="0,00" class="form-control product-add-cost format-number-decimal" name="add_cost[]"></td>';
		table += '	<td><input type="text" value="0,00" class="form-control product-total format-number-decimal" readonly name="total[]"></td>';
		table += '</tr>';

		jQuery(".table-transaction tbody").append(table);
	}

	jQuery('body').on('click', '.container-product-search', function() {
		var index = jQuery('.container-product-search').index(jQuery(this));
				
		if (jQuery('#idoutlet').val() == null) {
			bootbox.alert('<?php echo azlang("Please select outlet first");?>');
		}
		else if (jQuery('#idcustomer').val() == null) {
			bootbox.alert('Harap pilih pelanggan dahulu');
		}
		else {
			jQuery('#product_selected').val(index);
			show_modal('product');
		}

	});

	jQuery('body').on('click', '.btn-choose-product', function() {
		var idproduct = jQuery(this).attr('data-id');
		var index = jQuery("#product_selected").val();
        var code = jQuery(this).attr('data-code');

        choose_product(code, index);
	});

    function choose_product(code, index) {
        show_loading();
        jQuery.ajax({
            url: app_url + 'sales_transaction/choose_product',
            type: 'POST',
            dataType: 'JSON',
            data: {
                id: code
            },
            success: function(response) {
                hide_loading();
                
                jQuery('.product-idproduct:eq('+index+')').val(response.idproduct);
                jQuery('.product-price:eq('+index+')').val(thousand_separator_decimal(response.price));
                jQuery('.product-name:eq('+index+')').val(response.name);

                var sel_hue = response.idhue.split(',');
                jQuery('.product-hue:eq('+index+')').val(sel_hue).change();

                var sel_colour = response.idcolour.split(',');
                jQuery('.product-colour:eq('+index+')').val(sel_colour).change();

                if (response.idspot != null) {
	                var sel_spot = response.idspot.split(',');
	                jQuery('.product-spot:eq('+index+')').val(sel_spot).change();
                }

                jQuery('.trx-note:eq('+index+')').val(response.trx_note);

                jQuery("#idcustomer").append(new Option(response.customer_name, response.idcustomer, true, true)).trigger('change');

                jQuery('.az-modal').modal('hide');


                calculate_total();

            },
            error: function(resp) {}
        });   
    }

	jQuery('body').on('change keyup keydown', '.product-qty, .product-price, .product-tax, .product-add-cost, .product-discount, #info_discount, #info_add_cost, #info_add_cost_percent, #info_tax, #info_pay, #info_discount_percent, #total_panjar, #total_pay', function() {
		calculate_total();
	});

	calculate_total();
	function calculate_total() {
		var info_total = 0;
		var hd_idtable = "";
		jQuery('.product-idproduct').each(function(adata, bdata) {
			var total_add = 0;
			jQuery(bdata).parent('td').find('.select-additional').each(function(xdata, ydata) {
				if (jQuery(ydata).val() != '') {
					var add = jQuery(ydata).parent('td').parent('tr').find('.add-cost-price').val();
					add = remove_separator(add);
					total_add += parseFloat(add);
				}
			});

			var product_price = jQuery(bdata).parents('.tr-row').find('.product-price').val();
			product_price = remove_separator(product_price);

			var product_total = parseFloat(product_price) + parseFloat(total_add);
			jQuery(bdata).parents('.tr-row').find('.product-total').val(thousand_separator_decimal(product_total));

			jQuery(bdata).parent('td').parent('tr').find('.product-add-cost').val(thousand_separator_decimal(total_add));

			info_total += parseFloat(product_total);

			hd_idtable += "," + jQuery(bdata).val();
		});

		jQuery('#hd_idtable').val(hd_idtable);

		var info_discount = jQuery('#info_discount').val() || 0;
		var info_add_cost = jQuery('#info_add_cost').val() || 0;
		var info_tax = jQuery('#info_tax').val() || 0;
		info_discount = remove_separator(info_discount);
		info_add_cost = remove_separator(info_add_cost);
		info_tax = remove_separator(info_tax);

		var info_total_final = parseFloat(info_total) - parseFloat(info_discount) + parseFloat(info_add_cost) + parseFloat(info_tax);


		jQuery('#info_total').val(thousand_separator_decimal(info_total));
		jQuery('#info_total_final').val(thousand_separator_decimal(info_total_final));

        jQuery('#p_info_total_final').val(thousand_separator_decimal(info_total_final));

		var pay = jQuery('#total_panjar').val() || 0;
		pay = remove_separator(pay);
		var not_yet = parseFloat(info_total_final) - parseFloat(pay);

        var lack = not_yet;
        if (not_yet < 0) {
            lack = 0;
        }

        var ret_money = 0;
        var total_cash = jQuery('#total_pay').val() || 0;
        total_cash = remove_separator(total_cash);

        var payment_status = jQuery('#payment_status').val();
        if (payment_status == 'CASH') {
            pay = info_total_final;
        }

        var calc_ret = total_cash - pay;
        if (calc_ret > 0) {
            ret_money = calc_ret;
        }        
		
		jQuery('#p_info_lack').val(thousand_separator_decimal(lack));
        jQuery('#p_info_ret_money').val(thousand_separator_decimal(ret_money));

	}

	function calculate_percent(type) {
        var discount = remove_separator(jQuery('#info_'+ type).val()) || 0;
        var total_transaction = remove_separator(jQuery('#info_total').val());
        var discount_percent = parseInt(discount)/parseInt(total_transaction) * 100;
        discount_percent = discount_percent || 0;
        jQuery('#info_'+ type +'_percent').val(thousand_separator_decimal(discount_percent));
    }

    function calculate_discount(type) {
        var discount_percent = remove_separator(jQuery('#info_'+ type +'_percent').val()) || 0;
        var total_transaction = remove_separator(jQuery('#info_total').val());
        var discount_total = parseInt(discount_percent) / 100 * total_transaction;
        discount_percent = discount_total;
        jQuery('#info_'+ type).val(thousand_separator_decimal(discount_percent));
        calculate_total();
    }

    jQuery('#info_discount_percent').on('change keyup keydown', function() {
    	calculate_discount('discount');
    });

    jQuery('#info_add_cost_percent').on('change keyup keydown', function() {
    	calculate_discount('add_cost');
    });

    jQuery('#info_discount').on('keyup keydown', function() {
    	calculate_percent('discount');
    });

    jQuery('#info_tax_percent').on('keyup keydown', function() {
    	calculate_discount('tax');
    });

    jQuery('#info_tax').on('keyup keydown', function() {
    	calculate_percent('tax');
    });


    jQuery('body').on('change', '#idoutlet', function() {
    	var dtable = jQuery('#product').dataTable({bRetrieve: true});
        dtable.fnDraw();

        jQuery('.table-transaction tbody').html('');
        new_transaction();
        calculate_total();
    });

    jQuery('body').on('click', '.btn-remove-row', function() {
    	var the_table = jQuery(this).parents('table');
    	var attr = jQuery(this).attr('data-id');
    	if (attr == 'transaction') {
    		id = 'product-idtransaction';
    		field = 'x_transaction';
    	}
    	else {
    		id = 'detail-idtransaction-detail';
    		field = 'x_transaction_detail';
    	}

    	var old_val = jQuery('#' + field).val();
		var new_val = jQuery(this).parents('tr').find('.' + id).val();

		if (new_val.length > 0) {
			var val_remove = old_val + ',' + new_val;
			jQuery("#" + field).val(val_remove);
		}

    	jQuery(this).parents('tr').remove();
    	
    	var numb = the_table.find('.numb');
    	jQuery(numb).each(function(adata, bdata) {
    		jQuery(bdata).val((adata + 1));
    	});
    	calculate_total();
    	calc_total_qty();
    });

    jQuery('#btn_save_transaction').on('click', function() {
        show_modal('payment');

    	// save_transaction();
    });
    jQuery('#btn_save_print_transaction').on('click', function() {
        alert('belum');
    	// save_transaction('print');
    });

    function save_transaction(type) {
    	show_loading();
    	jQuery.ajax({
    		url: app_url + 'sales_transaction/save',
    		type: 'POST',
    		dataType: 'JSON',
    		data: jQuery('#form_transaction').serialize(),
    		success: function(response) {
    			hide_loading();
    			if (response.err_code == 0) {
    				bootbox.alert({
    					title: "<?php echo azlang('Success');?>",
    					message: "<?php echo azlang('Transaction Success Added');?>",
    					callback: function() {
    						if (type == 'print') {
    							window.open(app_url + 'sales_transaction/invoice/?t=small&c=' + response.invoice, '_blank');
    						}
    						location.href = app_url + 'sales_transaction';
    					}
    				});
    			}
    			else {
    				bootbox.alert({
    					title: "Error", 
    					message: response.err_message
    				});
    			}
    		},
    		error: function(response) {
    			hide_loading();
    		}
    	});    	
    }

    get_edit();
    function get_edit() {
    	var is_edit = "<?php echo $this->uri->segment(2);?>";
    	var id = "<?php echo $this->uri->segment(3);?>";
    	if (is_edit == 'edit' && id.length > 0) {
    		jQuery.ajax({
    			url: app_url + 'sales_transaction/get_edit',
    			type: 'POST',
    			dataType: 'JSON',
    			data: {
    				id: id
    			},
    			success: function(response) {
    				if (response.err_code > 0) {
    					bootbox.alert({
    						title: "<?php echo azlang('Error');?>",
    						message: response.err_message,
    						callback: function() {
    							location.href = app_url + 'sales_transaction'
    						}
    					});
    				}
    				else {
	    				jQuery.each(response.data, function(adata, bdata){
							jQuery('#'+adata).val(bdata);
							if (jQuery('#'+adata).hasClass('format-number-decimal')) {
								jQuery('#'+adata).val(thousand_separator_decimal(bdata));
							}

							var arr_ajax = [];
							var ajax_ = adata;

					        if (ajax_.indexOf("ajax_") >= 0) {
					            arr_ajax.push(ajax_);
					        }

							if (arr_ajax.length > 0) {
					            jQuery.each(arr_ajax, function(index_arr, value_arr) {
					                var idajax = value_arr.replace("ajax_", "");
					                if (response.data[value_arr] != null) {
					                    jQuery("#"+idajax+".select2-ajax").append(new Option(response.data[value_arr], response.data[idajax], true, true)).trigger('change');
					                }
					            });
					        }
						});

	    				jQuery(".table-transaction tbody").html('');
	    				jQuery.each(response.data_transaction, function(adata, bdata) {
	    					new_transaction();
	    					jQuery('.product-idtransaction').last().val(bdata.idtransaction);
	    					jQuery('.product-idproduct').last().val(bdata.idproduct);
	    					jQuery('.product-name').last().val(bdata.product_name);
	    					jQuery('.product-type').last().val(bdata.product_type);
	    					jQuery('.product-qty').last().val(thousand_separator_decimal(bdata.qty));
	    					jQuery('.product-price').last().val(thousand_separator_decimal(bdata.price));
	    					jQuery('.product-discount').last().val(thousand_separator_decimal(bdata.discount));
	    					jQuery('.product-add-cost').last().val(thousand_separator_decimal(bdata.add_cost));
	    					jQuery('.product-tax').last().val(thousand_separator_decimal(bdata.tax));
	    					jQuery('.product-total').last().val(thousand_separator_decimal(bdata.total));
	    					calculate_total();
	    				});

	    				jQuery(".table-detail tbody").html('');
						jQuery.each(response.data_detail, function(adata, bdata) {
							add_detail();
							jQuery('.detail-idtransaction-detail').last().val(bdata.idtransaction_detail);
							jQuery('.detail-description').last().val(bdata.detail_description);
							jQuery('.detail-qty').last().val(bdata.detail_qty);
							calc_total_qty();
						});
						check_pay();
    				}
    			},
    			error: function(response) {}
    		});
    	}
    }

    jQuery('#btn_add_customer').on('click', function() {
    	jQuery('.form-customer input').val('');
    	jQuery('.form-customer textarea').val('');
    	jQuery('.form-customer select').val('');

        if (jQuery('#idoutlet').val() == null) {
            bootbox.alert("Harap pilih outlet");
        }
        else {
    	   show_modal('customer');
           jQuery('#idcsoutlet').val(jQuery('#idoutlet').val());
        }

    });

    jQuery('body').on('click', '.btn-action-save_customer', function() {
    	var ca = function(response){
    		jQuery("#idcustomer.select2-ajax").append(new Option(response.customer_name, response.idcustomer, true, true)).trigger('change');
    	};
    	save(app_url + 'sales_transaction/save_customer', 'form', 'thetable', ca, '');
    });

    jQuery('body').on('change', '#pay', function() {
    	check_pay();
    });

    check_pay();
    function check_pay() {
    	var pay = jQuery('#pay').val();
    	if (pay == 'PAID') {
    		jQuery('.container-pay-date').removeClass('hide');
    	}
    	else {
    		jQuery('.container-pay-date').addClass('hide');
    	}
    }

    jQuery('body').on('click', '.btn-add-item-additional', function() {
    	var tmp = jQuery('#tmp_additional_cost').html();
    	jQuery(this).parents('.box-item-additional').find('table tbody').append(tmp);

        generate_add_id();

    	jQuery('.select-additional').select2();
    });	

    jQuery('body').on('click', '.btn-remove-additional-cost', function() {
    	jQuery(this).parent('td').parent('tr').remove();
        generate_add_id();
        calculate_total();
    });

    function generate_add_id() {
        jQuery('.table-transaction > tbody > tr').each(function(adata, bdata) {
            jQuery(bdata).find('.idspot').attr('name', 'idspot_' + adata + '[]');
            jQuery(bdata).find('.idcolour').attr('name', 'idcolour_' + adata + '[]');
            jQuery(bdata).find('.idhue').attr('name', 'idhue_' + adata + '[]');
            jQuery(bdata).find('.tb-additional-cost > tbody > tr').each(function(xdata, ydata) {
                jQuery(ydata).find('.select-additional').attr('name', 'idadditional_item_' + adata + '[]');
                jQuery(ydata).find('.add-cost-price').attr('name', 'add_cost_price_' + adata + '[]');
            });
        });
    }


    jQuery('body').on('change', '#idcustomer', function() {
    	get_detail_customer();
    });

    jQuery('#customer_detail').hide();

    function get_detail_customer() {
    	var id = jQuery('#idcustomer').val();
    	if (id == null) {
    		jQuery('#customer_detail').hide();
    	}
    	else {
    		show_loading();
    		jQuery.ajax({
    		    url: app_url + 'sales_transaction/get_customer_detail',
    		    type: 'POST',
    		    dataType: 'JSON',
    		    data: {
    		    	id: id
    		    },
    		    success: function(response) {
    		        hide_loading();
		            jQuery('.cd-phone').text(response.phone);
		            jQuery('.cd-address').text(response.address);
		            jQuery('.cd-category').text(response.category);

		            jQuery('#customer_detail').show();
                    var tb = jQuery('#product').dataTable({bRetrieve: true});
                    tb.fnDraw(false);
    		    },
    		    error: function(res){}
    		});    		      
    	}
    }

    jQuery('body').on('change', '.select-additional', function() {
    	var id = jQuery(this).val();
    	var elm = jQuery(this).parent('td').parent('tr');
    	show_loading();
    	jQuery.ajax({
    		url: app_url + 'sales_transaction/get_additional_price',
    		dataType: 'JSON',
    		type: "POST",
    		data: {
    			id: id
    		},
    		success: function(response) {
    			hide_loading();
    			jQuery(elm).find('.add-cost-price').val(response.price);
    			calculate_total();
    		},
    		error: function(resp) {}
    	});
    });

    jQuery('body').on('keyup keydown', '.add-cost-price', function() {
    	calculate_total();
    });

    check_payment_status();

    function check_payment_status() {
        var idpayment = jQuery('#idpayment').val();

    	
        var type = jQuery('#payment_status').val();
        if (type == 'BELUM BAYAR') {
            jQuery('.container-is-pay').hide();
            jQuery('.container-pay-tunai').hide();
        }
        else {
            jQuery('.container-is-pay').show();
            jQuery('.container-pay-tunai').show();
        }

        if (type == 'PANJAR') {
            jQuery('.container-panjar').show();
        }
        else {
            jQuery('.container-panjar').hide();
        }

    	
    	if (idpayment == '1' && type != 'BELUM BAYAR') {
    		jQuery('.container-pay-tunai').show();
    	}
    	else {
    		jQuery('.container-pay-tunai').hide();
    	}
    }

    jQuery('body').on('change', '#payment_status', function() {
        check_payment_status();
    });

    jQuery('body').on('click', '.money-list', function() {
        var val = jQuery(this).attr('data-id');
        jQuery('#total_pay').val(thousand_separator_decimal(val));
        calculate_total();
    });

    jQuery('body').on('click', '.btn-action-save-payment', function() {
        save_payment('');
    });

    jQuery('body').on('click', '.btn-action-save-payment-print', function() {
        save_payment('print');
    });

    function save_payment(save_type) {
        var formdata = new FormData();

        jQuery.each(jQuery('#form_payment').serializeArray(), function (a, b) {
            formdata.append(b.name, b.value);
        }); 

        jQuery.each(jQuery('#form_transaction').serializeArray(), function (a, b) {
            formdata.append(b.name, b.value);
        }); 

        show_loading();
        jQuery.ajax({
            url: app_url + 'sales_transaction/save',
            type: 'POST',
            dataType: 'JSON',
            processData: false,
            contentType: false,
            data: formdata,
            success: function(response) {
                hide_loading();
                if (response.err_code == 0) {
                    bootbox.alert({
                        message: "Transaksi Berhasil",
                        callback: function(ss) {
                            if (save_type == 'print') {
                                window.open(app_url + 'sales_transaction/print_bill/' + response.invoice + '/trx_print');
                            }
                            location.reload();
                        }
                    });
                }
                else {
                    bootbox.alert(response.err_message);
                }

            },
            error: function(response) {}
        });
    }

    jQuery('body').on('click', '.btn-create-item', function() {
        if (jQuery('#idoutlet').val() == null) {
            bootbox.alert("Harap pilih outlet");
        }
        else if (jQuery('#idcustomer').val() == null) {
            bootbox.alert("Harap pilih pelanggan");
        }
        else {
            show_modal('create_item');
            jQuery('#idnoutlet').val(jQuery('#idoutlet').val());
            jQuery('#idncustomer').val(jQuery('#idcustomer').val());

            jQuery('#idnproduct_type').val('').trigger('change');
            jQuery('#idcolour').val('').trigger('change');
            jQuery('#idhue').val('').trigger('change');
            jQuery('#idspot').val('').trigger('change');
            jQuery('#trx_note').val('');
        }
    });

    jQuery('body').on('click', '.btn-action-save_item', function(){
        show_loading();
        jQuery.ajax({
            url: app_url + 'sales_transaction/create_item',
            type: 'POST',
            dataType: 'JSON',
            data: jQuery("#form_create").serialize(),
            success: function(response) {
                hide_loading();
                if (response.err_code == 0) {
                    
                    hide_modal('create_item');
                    var tb = jQuery('#product').dataTable({bRetrieve: true});
                    tb.fnDraw(false);

                   	jQuery('.table-transaction > tbody > tr').each(function(adata, bdata) {
                   		
                   		var idproduct = jQuery(bdata).find('.product-idproduct').val();

                   		if (idproduct == '') {
                   			jQuery(bdata).remove();
                   		}
                   	}); 
                   	new_transaction();

                   	var index = jQuery('.tr-row').length;
                   	index = index - 1;

                   	choose_product(response.code, index);
                }
                else {
                    bootbox.alert(response.err_message);
                }
            },
            error: function(resp){}
        });
    });


    jQuery('body').on('change', '#idpayment', function() {
    	check_payment_status();
    });