@extends('adminlte::page')
@section('content')
@include('administrator.client-payment.payment.form-payoff')
@include('administrator.client-payment.payment.form-add-deposite')
@include('administrator.client-payment.payment.form-approve-deposite')
@include('administrator.client-payment.payment.form-reject-deposite')
@include('administrator.client-payment.payment.form-add-commission')
@include('administrator.client-payment.payment.form-reject-commission')
@include('administrator.client-payment.payment.form-approve-commission')
@include('administrator.client-payment.payment.form-cancel-payment')
@include('administrator.client-payment.payment.form-delete-payment')
@include('administrator.client-payment.payment.form-commission-info')
@include('administrator.client-payment.payment.commission-preview')

<?php Fun::lang() ?>
<div class="page-wrapper">
	<div class="row">
		<div class="col-sm-12 col-xs-12">
			<div class="box-header">
				<div class="pull-left">
					<h2>Add Commission</h2>
				</div>
			</div>
			<div class="box-body table-responsive">
				<table id="datatable_client_payment" class="table table-striped table-bordered table-hover nowrap">
					<thead>
						<tr>
							<th></th>
							<th>No</th>
							<th>Client Name</th>
							<th>Agency Name</th>
							<th>Close Sale</th>
							<th>Item Name</th>
							<th>Category</th>
							<th>Project</th>
							<th>Commission Amount</th>
							<th>Commission Close</th>
							<th>Action</th>
						</tr>
					</thead>
				</table>
			</div>
		</div>
	</div>
</div>
@endsection
@section('js')
<script type="text/javascript" src="{{asset('assets/scripts/yajrabox-datatable/handlebars.min.js')}}"></script>
<script src="{{asset('assets/controller/collapse.js')}}"></script>
<script id="details-template" type="text/x-handlebars-template">
	@verbatim
	    <div style="border-top:2px solid #000;"></div>
	    <table class="table details-table" id="commission-{{id}}">
	        <thead>
	        <tr>
	        	<th>No</th>
	            <th>Agency</th>
	            <th>Level</th>
	            <th>Commission</th>
	            <th>Receive</th>
	        </tr>
	        </thead>
	    </table>
	    @endverbatim
	</script>
<script type="text/javascript">
	var template = Handlebars.compile($("#details-template").html());
	var index = $('#datatable_client_payment').DataTable({
		ordering: false,
		"serverSide": true,
		"lengthMenu": [
			[20, 30, 50, 100, -1],
			[20, 30, 50, 100, "All"]
		],
		ajax: "{{ route('datatable.get_client_payment_list') }}",
		columns: [{
				"className": 'details-control',
				"orderable": false,
				"data": null,
				"defaultContent": ''
			},
			{
				data: 'DT_RowIndex'
			},
			{
				data: 'client_fullname'
			},
			{
				data: 'sale_name'
			},
			{
				data: 'close_name'
			},
			{
				data: 'item_name'
			},
			{
				data: 'category_name'
			},
			{
				data: 'project_name'
			},
			{
				data: 'commission_amount'
			},
			{
				data: 'close_commission'
			},
			{
				data: 'action'
			}
		],

		"initComplete": function(settings, json) {
			$('.main-spinner').hide();
		}
	});
	index.on('order.dt search.dt', function() {
		index.column(0, {
			search: 'applied',
			order: 'applied'
		}).nodes().each(function(cell, i) {
			cell.innerHTML = i + 1;
		});
	}).draw();
	$.fn.dataTable.ext.errMode = 'throw';


	$(document).ready(function() {
		$('.number-only').keypress(function(e) {
			if (isNaN(this.value + "" + String.fromCharCode(e.charCode))) return false;
		});
	});

	function pay(obj) {
		var id = $(obj).closest("tr").attr("id");
		$.ajax({
			url: "/realty/payment-loan-process/" + id,
			type: "get",
			success: function(data) {
				var d = $.parseJSON(data);
				var penalty = Math.floor(d['penalty'] * 100) / 100;
				if (penalty > 0) {
					$('#penalty_option').prop('required', true);
				}
				$("#pid").val(d['loan_process'].id);
				$("#loan_id").val(d['loan_process'].loanprocess_loanid);
				$("#principle").val(d['loan_process'].loanprocess_principlepay);
				$("#interest").val(d['loan_process'].loanprocess_interestpay);
				$("#pay").val(d['loan_process'].loanprocess_owepay);
				$("#payment").val(d['loan_process'].loanprocess_owepay);
				$('#penalty').val(penalty);
			}
		});
	}
	$(document).on('click', '.downpayment', function() {
		var id = $(this).data('id');
		var route = `{{route('get-down-payment',':id')}}`;
		route = route.replace(':id', id);
		$.ajax({
			type: 'GET',
			url: route,
			dastaType: 'json',
			data: {
				"_token": "{{ csrf_token() }}",
				"id": id,
			},
			success: function(data) {
				data = JSON.parse(data);
				var down_payment = parseFloat(data.loan_downpayment);
				$('#deposit_amount').val((down_payment == null) ? 0 : down_payment);
				$('#sale_id').val(data.loan_saleid);
				$('#add_deposit').modal('show');
			}
		});

	});

	function save_payment(obj) {

		var pid = $('#pid').val();
		var principle = $('#principle').val();
		var interest = $('#interest').val();
		var payment = $('#payment').val();
		var pay = $('#pay').val();
		var condition = $('#condition').val();
		var penalty = $('#penalty').val();
		var invoice = $('#invoice').val();
		var date = $('#date').val();
		var remark = $('#remark').val();
		var loan_id = $('#loan_id').val();
		var bank_list = $('#bank-list').val();
		var extra_amount = $('#extra_amount').val();
		var penalty = $('#penalty').val();
		var option = $('#penalty_option').find(':selected').val();
		var amount_pay = parseFloat(pay);
		var amount_payment = parseFloat(payment);
		var condition_type = parseFloat(condition);
		if (!amount_pay) {
			$("#_msg_paymentPopup").html('Payment amount is empty, Please enter your payment!');
			$("#_div_paymentPopup").attr("style", "display:block");

		} else if (bank_list == "") {
			$("#_msg_paymentPopup").html('Bank Name No Select, Please Select Bank Name!');
			$("#_div_paymentPopup").attr("style", "display:block");
		} else if (condition_type == 1 && amount_payment > amount_pay) {
			$("#_msg_paymentPopup").html('Your money must be smaller than payment!');
			$("#_div_paymentPopup").attr("style", "display:block");
		} else if (condition_type == 2 && amount_payment <= amount_pay) {
			$("#_msg_paymentPopup").html('Money must be bigger than payment!');
			$("#_div_paymentPopup").attr("style", "display:block");
		} else if (penalty > 0 && option == "") {
			$("#_msg_paymentPopup").html('Please Select Penalty Option!');
			$("#_div_paymentPopup").attr("style", "display:block");
		} else if ((amount_pay >= amount_payment && condition_type == 1) || (amount_pay < amount_payment && condition_type == 2)) {
			$(obj).attr("disabled", "disabled");
			$.ajax({
				type: 'POST',
				url: "{{ route('submit_payment_data') }}",
				data: {
					"_token": "{{ csrf_token() }}",
					"pid": pid,
					"principle": principle,
					"interest": interest,
					"payment": payment,
					"pay": pay,
					"penalty_condition": option,
					"condition": condition,
					"penalty": penalty,
					"invoice": invoice,
					"date": date,
					"remark": remark,
					"bank_list": bank_list,
					"extra_amount": extra_amount,
					"loan_id": loan_id
				},
				success: function(data) {
					var d = $.parseJSON(data);
					if (d.message == "success") {
						window.location.reload();
						$('#done').show();
					}
				}
			});
		} else if (parseFloat(amount_pay) < parseFloat(amount_payment) && condition_type == 2) {
			$("#_msg_paymentPopup").html('Your money is smaller than payment, Please select condition!');
			$("#_div_paymentPopup").attr("style", "display:block");
		} else {
			$("#_msg_paymentPopup").html('Your money is more than payment, Please select condition!');
			$("#_div_paymentPopup").attr("style", "display:block");
		}
	}
	$("#extra_amount").keyup(function() {
		var extra_amount = $(this).val();
		$('#payment').val(extra_amount);

	});
	$("#condition").change(function() {
		document.getElementById('btn-submit').disabled = false;
		$("#_div_paymentPopup").attr("style", "display:none");
	});

	function save_deposit(obj) {
		$(obj).attr("disabled", "disabled");
		var sale_id = $('#sale_id').val();
		var date = $('#date').val();
		var date_contract = $('#date_contract').val();
		var deposit_amount = $('#deposit_amount').val();
		var payamount = $('#payamount').val();
		if (!payamount) {
			$("#_msg_depositPopup").html('Deposit amount is empty, Please enter your deposit amount!');
			$("#_div_depositPopup").attr("style", "display:block");
		} else {
			$.ajax({
				type: 'POST',
				url: "{{ route('submit_deposit_on_downpayment') }}",
				data: {
					"_token": "{{ csrf_token() }}",
					"sale_id": sale_id,
					"date": date,
					"date_contract": date_contract,
					"deposit_amount": deposit_amount,
					"payamount": payamount

				},
				success: function(data) {
					var d = $.parseJSON(data);
					if (d.message == "success") {
						window.location.reload();
					}
				}
			});
		}
	}
	$(document).on('keyup', '#payamount', function() {
		var amount = $(this).val();
		var down = $('#deposit_amount').val();
		if (parseFloat(amount) > parseFloat(down)) {
			$.alert({
				title: 'Over Amount',
				content: 'Payment is greater than down payment',
				type: 'blue',
				animation: 'scale',
				draggable: true,
			});
			$('.btn-save-deposite').prop('disabled', true);
		} else {
			$('.btn-save-deposite').prop('disabled', false);
		}
	});
	$(document).on('click', '.approve_deposite', function() {
		var id = $(this).data('id');
		var route = "{{route('downpayment.approve-deposite',':id')}}";
		route = route.replace(':id', id);
		$('#form-approve-deposite').attr('action', route);
		$('#approve_deposite').modal('show');
	});
	$(document).on('click', '.reject_deposite', function() {
		var id = $(this).data('id');
		var route = "{{route('downpayment.reject-deposite',':id')}}";
		route = route.replace(':id', id);
		$('#form-reject-deposite').attr('action', route);
		$('#reject_deposite').modal('show');
	});
	$(document).on('click', '.btn-add-commission', function() {
		var id = $(this).data('id');
		$('#commission_sale_id').val(id);
		var route = "{{route('get_commission_amount',':id')}}";
		route = route.replace(':id', id);
		$.ajax({
			type: 'GET',
			url: route,
			dastaType: 'json',
			data: {
				"_token": "{{ csrf_token() }}",
				"id": id,
			},
			success: function(data) {
				obj = JSON.parse(data);
				$('#commission_amount').val(obj["total_comm"]);
				$('#commission_amounts').val(obj["total_comm"]);
				$('#agency_id').val(obj["agency_id"]);
				$('#agency_name').val(obj["agency_name"]);
				$('#agent_type').val(obj["agency_type_name"]);
				$('#close_sale').val(obj["close_sale"]);
				$('#close_sale_condi').val(obj["close_sale_condi"]);
				$('#close_sale_commis').val(obj["close_sale_commis"]);
				$('#agency_type_id').val(obj["agency_type_id"]);
				$('#agency_type_condition').val(obj["agency_type_condition"]);
				$('#agency_type_percentage').val(obj["agency_type_percentage"]);
				$('#close_sale_id').val(obj["close_sale_id"]);
				$('#close_sale_name').val(obj["close_sale_name"]);
				$('#company_amount').val(obj["company_amount"]);
				$('#company_condi').val(obj["company_condi"]);
				$('#company_commis').val(obj["company_commis"]);

			}
		});
		$('#add_commission').modal('show');
	});
	$(document).on('change', '#agent_type', function() {
		var id = $(this).find(':selected').val();
		$('#commission_option').empty();
		$("#condition_com_option").hide();
		$("#condition_option").hide();
		if (id != 1 && id != "") {
			$("#condition_com_option").show();
			$("#condition_option").show();
			$.ajax({
				type: 'GET',
				url: "{{route('get_commission_network')}}",
				dastaType: 'text',
				data: {
					"_token": "{{ csrf_token() }}",
					"id": id,
				},
				success: function(data) {
					$('#commission_option').append(data);
				}
			});
		}
	});
	$(document).on('change', '#condition_com_option', function() {
		var id = $(this).find(':selected').val();
		$(".conditions").empty();
		$.ajax({
			type: 'post',
			url: "{{route('get_commission_network_condition')}}",
			dataType: 'json',
			data: {
				"_token": "{{ csrf_token() }}",
				"id": id,
			},
			success: function(data) {
				$(".conditions").empty();
				var opt = '<option>please select</option>';

				$.each(data, function(index, value) {
					opt = '<option value="' + value.commission + '">' + value.commission + '</option>';
					$('.agent_condition').val(value.condition);
				});
				$('.conditions').append(opt);

			}
		});

	});
	$(document).on('keyup', '.commission_close_sale', function() {
		var id = $(this).val();
		var commission = $('#commission_amounts').val();
		var total_comm = commission - id;
		$('#commission_amount').val(total_comm);
	});
	$(document).on('click', '.btn-approve-commission', function() {
		var id = $(this).data('id');
		var route = "{{route('approve-request-commission.agent')}}";
		$('#commission_approve').val(id);
		$('#form-approve-commission').attr('action', route);
		$('#approve_commission').modal('show');
	});
	$(document).on('click', '.btn-reject-commission', function() {
		var id = $(this).data('id');
		var route = "{{route('reject-request-commission.agent')}}";
		$('#commission_reject').val(id);
		$('#form-reject-commission').attr('action', route);
		$('#reject_commission').modal('show');
	});
	$(document).on('click', '.btn_cancel_payment', function() {
		var id = $(this).data('id');
		var message = "Your Request Will be processed Soon";
		var route = "{{route('request-cancel-payment',':id')}}";
		route = route.replace(':id', id);
		$('#form_cancel_payment').attr('action', route);
		$('#message').text(message);
		$('#cancel_payment').modal('show');
	});
	$(document).on('click', '.btn_reject_cancel', function() {
		var id = $(this).data('id');
		var route = "{{route('reject-cancel-payment',':id')}}";
		var message = "This Request will be rejected";
		route = route.replace(':id', id);
		$('#message').text(message);
		$('#form_cancel_payment').attr('action', route);
		$('#cancel_payment').modal('show');
	});
	$(document).on('click', '.btn_approve_cancel', function() {
		var id = $(this).data('id');
		var message = "This Request will be Approve";
		var route = "{{route('approve-cancel-payment',':id')}}";
		route = route.replace(':id', id);
		$('#message').text(message);
		$('#form_cancel_payment').attr('action', route);
		$('#cancel_payment').modal('show');
	});
	$(document).on('click', '.btn-outline-danger', function() {
		var id = $(this).data('id');
		var route = "{{route('delete-client-payment.loan-process',':id')}}";
		route = route.replace(':id', id);
		$('#form_delete_payment').attr('action', route);
		$('#delete_payment').modal('show');
	});
	$(document).on('click', '.btn-commission-info', function() {
		var id = $(this).data('id');
		var route = "{{route('commission-info',':id')}}";
		route = route.replace(':id', id);
		$.ajax({
			type: "GET",
			dataType: 'text',
			url: route,
			data: {
				'_token': "{{csrf_token()}}"
			},
			success: function(data) {
				$('.body-result').empty().append(data);
				$('#commission-preview').modal('show');
			}
		});
	});
</script>
@endsection