/**
 * InvoicesNewCtrl Controller
 * Extracted from invoices module
 */

Invoices.controller('InvoicesNewCtrl', ['$scope', 'Invoice', 'Tasks', 'ErrorsHandler', '$routeParams', '$location', 'InvoiceService', '$window', function ($scope, Invoice, Tasks, ErrorsHandler, $routeParams, $location, InvoiceService, $window) {

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

	$scope.title = 'Invoices';
	$scope.type = 'invoice';
	$scope.service = InvoiceService.create(Invoice);

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

	$scope.$on('$routeChangeSuccess', function (ev, currentRoute, previousRoute) {
		if ($routeParams.taskId) {
			if ($scope.labourTypesLoaded == true) {
				$scope.service.loadTask($routeParams.taskId);
			}
			else {
				$scope.$watch('service.labourTypesLoaded', function (newVal, oldVal, scopeSent) {
					if (newVal == true) {
						$scope.service.loadTask($routeParams.taskId);
					}
				});
			}
		}
		else if ($routeParams.projectId) {
			if ($scope.labourTypesLoaded == true) {
				$scope.service.loadProject($routeParams.projectId);
			}
			else {
				$scope.$watch('service.labourTypesLoaded', function (newVal, oldVal, scopeSent) {
					if (newVal == true) {
						$scope.service.loadProject($routeParams.projectId);
					}
				});
			}
		}
	});

	$scope.$watch('service.data.items', function () {
		$scope.service.calculateTotals();
	}, true);

	$scope.$watch('service.data.include_vat', function () {
		$scope.service.calculateTotals();
	});

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

	/**
	 * Clears the form
	 */
	$scope.reset = function () {
		$scope.service.data.items = [{ type: $scope.service.types[0].value }];
		$scope.service.data.id = null;
	};

	/**
	 * Saves the invoice (direct implementation like browse pages)
	 */
	$scope.save = function (print, email) {
		if (!$scope.service.data) {
			return;
		}

		// Frontend validation
		var errors = [];

		// Check if client is selected
		if (!$scope.service.client_search) {
			errors.push("Please select a customer");
		}

		// Check if there are any items
		var hasItems = false;
		_.each($scope.service.data.items, function (item) {
			if (item.name && item.quantity) {
				hasItems = true;
			}
		});
		if (!hasItems) {
			errors.push("Please add at least one item");
		}

		// If there are validation errors, show them and return
		if (errors.length > 0) {
			if (typeof Messenger !== 'undefined' && Messenger().post) {
				Messenger().post({
					message: errors.join("\n"),
					type: "error",
					showCloseButton: true
				});
			}
			return false;
		}

		// Show loading state
		$scope.service.loading = true;

		var request_data = angular.copy($scope.service.data);

		// Remove empty items
		_.each($scope.service.data.items, function (item, index) {
			if (!item.name) {
				$scope.service.data.items.splice(index, 1);
			}
		});

		request_data.client_type = $scope.service.client_search.type;
		request_data.client_id = $scope.service.client_search.id;
		request_data.total_price = $scope.service.total;
		request_data.invoice_date = moment(request_data.invoice_date).format("X");
		if (print) request_data.print = true;

		if ($scope.service.data.id) {
			// Update existing invoice
			Invoice.update(request_data, function (res) {
				angular.extend($scope.service.data, res || {});
				$scope.service.data.invoice_date = moment(res.invoice_date).toDate();
				$scope.service.loading = false;

				// Show success message
				if (typeof Messenger !== 'undefined' && Messenger().post) {
					Messenger().post({
						message: "Invoice was successfully updated!",
						type: "success",
						showCloseButton: true
					});
				}

				if (print)
					$window.open(res.print_url, '_blank');

				if (email)
					$scope.service.showEmailModal();

			}, function (a, b) {
				$scope.service.loading = false;
				ErrorsHandler(a, b);
			});
		} else {
			// Create new invoice
			Invoice.save(request_data, function (res) {
				angular.extend($scope.service.data, res || {});
				$scope.service.data.invoice_date = moment(res.invoice_date).toDate();
				$scope.service.loading = false;

				// Show success message
				var type = $scope.service.data.type === 'sale' ? 'Sale' : 'Invoice';
				if (typeof Messenger !== 'undefined' && Messenger().post) {
					Messenger().post({
						message: type + " created successfully!",
						type: "success",
						showCloseButton: true
					});
				}

				if (print)
					$window.open(res.print_url, '_blank');

				if (email) {
					$scope.service.showEmailModal($scope.service.data);
				} else {
					// Only redirect if email is not requested
					$location.path(res.type + 's/view/' + res.id);
				}
			}, function (response) {
				$scope.service.loading = false;

				// Handle validation errors
				if (response.status === 422) {
					if (typeof Messenger !== 'undefined' && Messenger().post) {
						Messenger().post({
							message: response.data.error || "Validation failed",
							type: "error",
							showCloseButton: true
						});
					}
				} else {
					// Handle other errors
					if (typeof Messenger !== 'undefined' && Messenger().post) {
						Messenger().post({
							message: response.data.error || "An error occurred while saving the invoice",
							type: "error",
							showCloseButton: true
						});
					}
					ErrorsHandler(response);
				}
			});
		}
	};

}]);
