/**
 * InvoicePaymentModalCtrl Controller
 * Extracted from invoices module
 */

Invoices.controller('InvoicePaymentModalCtrl', ['$scope', '$uibModalInstance', 'data', 'type', 'InvoiceTransaction', 'ErrorsHandler', function ($scope, $uibModalInstance, data, type, InvoiceTransaction, ErrorsHandler) {

	// ------------------------------------------------------------------------
	//
	//	SCOPE VARIABLES BELOW -->
	//
	// ------------------------------------------------------------------------

	$scope.data = {
		amount: (data.amount_due > 0) ? data.amount_due : 0,
		invoice_id: data.id,
		method_of_payment: type,
		date: new Date(),
	};

	$scope.data.notes = 'Seraph3 sales receipt paid by ' + $scope.data.method_of_payment;

	// ------------------------------------------------------------------------
	//
	//	WATCHERS AND EVENT LISTENERS BELOW -->
	//
	// ------------------------------------------------------------------------


	// ------------------------------------------------------------------------
	//
	//	FUNCTIONS BELOW THIS LINE -->
	//
	// ------------------------------------------------------------------------

	$scope.save = function () {
		if ($scope.saving) return false;
		$scope.data.payment_date = moment($scope.data.date).format("YYYY-MM-DD");
		$scope.saving = true;

		InvoiceTransaction.save($scope.data, function (response) {
			angular.extend(data, response.invoice);
			data.transactions.push(response);
			$uibModalInstance.close(response);
			$scope.saving = false;
		}, function (a, b) {
			$scope.saving = false;
			ErrorsHandler(a, b);
		});
	};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

}]);
