function sub_total() {
	var totals = 0;
	$('.li_prd_total').each(function (e) {
		totals += parseFloat($(this).text());
	});
	$('.li_srv_total').each(function (e) {
		totals += parseFloat($(this).text());
	});
	return totals;
}
function items_sub_total() {
	var totals = 0;
	$('.li_prd_total').each(function (e) {
		totals += parseFloat($(this).text());
	});
	if (isNaN(totals)) { totals = 0; }
	$('#item-subtotal').text(totals.toFixed(2));
}
function services_sub_total() {
	var totals = 0;
	$('.li_srv_total').each(function (e) {
		totals += parseFloat($(this).text());
	});
	if (isNaN(totals)) { totals = 0; }
	$('#service-subtotal').text(totals.toFixed(2));
}

function grand_total() {
	var subtotal = parseFloat($('#subtotal').text());
	if (isNaN(subtotal)) { subtotal = 0; }
	var discount = parseFloat($('#discount').val());
	if (isNaN(discount)) { discount = 0; }
	$('#grandtotal').text((subtotal - discount).toFixed(2));
}
function purchase_total() {
	var totals = 0;
	$('.li_prd_pprice').each(function (e) {
		totals += parseFloat($(this).text());
	});
	return totals;
}

$(document).ready(function () {

	$(document).on('keypress', '.isnumber', function (e) {
		return isNumber(e, this);
	});
	$('.datepicker').datepicker({ dateFormat: 'yy-mm-dd' });


	$('#salesStkItemsTable').DataTable({
		ajax: {
			url: base_url + 'quotations/show_stock_items',
			type: 'GET' // or 'POST' if needed
		},
		pageLength: 100,
		order: [],
		responsive: true,
	});

	$('#show-stock-modal').on('show.bs.modal', function (e) {
		$('#salesStkItemsTable').DataTable().ajax.reload();
	});

	$("#prd_stk").autocomplete({
		source: base_url + 'quotations/search-prd',
		minLength: 2
	});


	$('#btn-add-prd-stk-atl').on('click', function () {
		var prd_stk = $('#prd_stk').val();
		var prd_stk_qty = $('#prd_stk_qty').val();
		var flag = 0;
		if (prd_stk == "") { return false; }
		if (prd_stk_qty == "") { return false; }
		var form_data = new FormData();
		form_data.append('prd_stk', prd_stk);
		$.ajax({
			url: base_url + 'quotations/add_items_to_list',
			type: 'POST',
			processData: false,
			contentType: false,
			data: form_data,
			success: function (response) {
				var res = $.parseJSON(response)
				if (res[1] != 'no') {
					$('#prd_stk_tbody').append('<tr><td></td><td class="li_prd_stk">' + prd_stk + '</td><td class="li_prd_pprice">' + res[3] + '</td><td><span class="li_prd_qty">' + prd_stk_qty + '</span></td><td class="li_prd_price">' + res[1] + '</td><td class="li_prd_total">' + eval(prd_stk_qty * res[1]) + '</td><td><a href="#" class="tr-rmv"><i class="fa fa-close"></a></td></tr>');
					$('#subtotal').text(sub_total().toFixed(2));
					$('#purchase_total').text(purchase_total().toFixed(2));
					items_sub_total();
					grand_total();
					recalcId();
				}
				else {
					flag = 1;
				}
			}
		});
		if (flag == 1) { return false; }
		$('#prd_stk').val("");
		$('#prd_stk_qty').val("");
		$('#prd_stk').focus();
	});


	

	$(document).on('click', '.tr-rmv', function (e) {
		e.preventDefault();
		$(this).closest('tr').remove();
		$('#subtotal').text(sub_total().toFixed(2));
		$('#purchase_total').text(purchase_total().toFixed(2));
		recalcId();
		grand_total();
	});

	

	$('#customer_contact').on('keypress', function (e) {
		var key = e.which;
		if (key === 13) {
			var form_data = new FormData();
			form_data.append('customer_contact', $(this).val());
			$.ajax({
				url: base_url + 'quotations/get-customer',
				type: 'POST',
				processData: false,
				contentType: false,
				data: form_data,
				success: function (response) {
					var res = $.parseJSON(response)
					$('#customer_name').val(res.customer_name);
					$('#customer_email').val(res.customer_email);

				}
			});
		}
	});

	$('#customer_contact').on('blur', function (e) {
		if ($(this).val() != "") {
			$('#advance').removeAttr('readonly');
		}
		else {
			$('#advance').attr('readonly', 'readonly');
		}
	});



	$('#btn-process-items').on('click', function () {
		var customer_contact = $('#customer_contact').val();
		var customer_name = $('#customer_name').val();
		var customer_email = $('#customer_email').val();
		var notes = $('#notes').val();
		var type = 'CUSTOMER';

		if (type == 'CUSTOMER' && customer_name == "") {
			swal('Customer Name Required', 'Please add customer name', 'info');
			return false;
		}
		if (type == 'CUSTOMER' && customer_contact == "") {
			swal('Customer Contact Required', 'Please add customer contact', 'info');
			return false;
		}


		var purchases = 0;
		$('.li_prd_pprice').each(function (e) {
			var p = parseFloat($(this).text());
			var q = parseFloat($(this).closest('tr').find('.li_prd_qty').text());
			purchases += (p * q);
		});

		var itm_subtotal = parseFloat($('#item-subtotal').text());
		var srv_subtotal = parseFloat($('#service-subtotal').text());
		var subtotal = parseFloat($('#subtotal').text());
		var discount = parseFloat($('#discount').val());
		var grandtotal = parseFloat($('#grandtotal').text());

		if (isNaN(purchases)) { purchases = 0; }
		if (isNaN(subtotal)) { subtotal = 0; }
		if (isNaN(discount)) { discount = 0; }
		if (isNaN(grandtotal)) { grandtotal = 0; }
		if (grandtotal == 0) {
			swal('Add Some Items', 'Please add some items/services to continue', 'info');
			return false;
		}
		if (discount > subtotal) {
			swal('Discount Limit', 'Discount must be equals or less subtotal', 'warning');
			return false;
		}

		var item_name = [];
		var item_pprice = [];
		var item_price = [];
		var item_qty = [];
		var item_total = [];
		$('.li_prd_stk').each(function () {
			item_name.push($(this).text());
			item_pprice.push($(this).closest('tr').find('.li_prd_pprice').text());
			item_price.push($(this).closest('tr').find('.li_prd_price').text());
			item_qty.push($(this).closest('tr').find('.li_prd_qty').text());
			item_total.push($(this).closest('tr').find('.li_prd_total').text());
		});

		var service_name = [];
		var service_price = [];
		var service_qty = [];
		var service_total = [];
		$('.li_prd_srv').each(function () {
			service_name.push($(this).text());
			service_price.push($(this).closest('tr').find('.li_srv_price').text());
			service_qty.push($(this).closest('tr').find('.li_srv_qty').text());
			service_total.push($(this).closest('tr').find('.li_srv_total').text());
		});
		var form_data = new FormData();
		form_data.append('type', type);
		form_data.append('customer_contact', customer_contact);
		form_data.append('customer_name', customer_name);
		form_data.append('customer_email', customer_email);
		form_data.append('purchases', purchases);
		form_data.append('itm_subtotal', itm_subtotal);
		form_data.append('srv_subtotal', srv_subtotal);
		form_data.append('subtotal', subtotal);
		form_data.append('discount', discount);
		form_data.append('grandtotal', grandtotal);
		form_data.append('item_name', JSON.stringify(item_name));
		form_data.append('item_pprice', JSON.stringify(item_pprice));
		form_data.append('item_price', JSON.stringify(item_price));
		form_data.append('item_qty', JSON.stringify(item_qty));
		form_data.append('item_total', JSON.stringify(item_total));
		form_data.append('service_name', JSON.stringify(service_name));
		form_data.append('service_price', JSON.stringify(service_price));
		form_data.append('service_qty', JSON.stringify(service_qty));
		form_data.append('service_total', JSON.stringify(service_total));
		form_data.append('notes', notes);

		$.ajax({
			url: base_url + 'quotations/process-items',
			type: 'POST',
			processData: false,
			contentType: false,
			async: false,
			data: form_data,
			success: function (response) {
				var res = $.parseJSON(response)
				if (res['msg'] == 1) {
					notify('success', 'Quotation Created Successfully');
					window.open(base_url + 'quotations/invoice/' + res['invoice']);
					$('#prd_stk_tbody').html("");
					$('#srv_tbody').html("");
					$('#purchase_total').text('');
					$('#customer_contact').val('');
					$('#customer_name').val('');
					$('#customer_email').val('');
					$('#item-subtotal').text('0.00');
					$('#service-subtotal').text('0.00');
					$('#subtotal').text('0.00');
					$('#grandtotal').text('0.00');
					$('#discount').val('');
					$('#notes').val('');
				}
				else {
					notify('error', 'Something went wrong, please try again');
				}
			}
		});
	});

	$('#dpercent').on('click', function (e) {
		e.preventDefault();
		var chk = $(this).attr('title');
		if (chk == 'off') {
			$(this).attr('title', 'on');
			$(this).removeClass('text-secondary');
			$(this).addClass('text-danger');
		}
		else if (chk == 'on') {
			$(this).attr('title', 'off');
			$(this).removeClass('text-danger');
			$(this).addClass('text-secondary');
		}
		$('#discount').trigger('keyup');
	});

	$('#discount').on('keyup', function (e) {
		var sub_total = parseFloat($('#subtotal').text());
		var discount = parseFloat($(this).val());
		if (isNaN(sub_total)) { sub_total = 0; }
		if (isNaN(discount)) { discount = 0; }
		var distchk = $('#dpercent').attr('title');
		// alert(distchk);
		if (distchk == 'on') {
			var discount_amount = ((sub_total * discount) / 100);
			var grandtotal = (sub_total - discount_amount);
		}
		else if (distchk == 'off') {
			var grandtotal = (sub_total - discount);
		}
		$('#grandtotal').text(grandtotal.toFixed(3));
	});
});// End Ready Function
