/**
 * InvoicesViewCtrl Controller
 * Extracted from invoices module
 */

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

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

	$scope.data = {};
	$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.invoiceId) {
			$scope.loadInvoice($routeParams.invoiceId);
		}
	});

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

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

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

	/**
	 * Loads an existing sale data
	 */
	$scope.loadInvoice = function (invoice_id) {
		Invoice.get({ 'invoice': invoice_id, client: true }, function (response) {

			$scope.service.data = response;
			$scope.service.data.invoice_date = moment(response.invoice_date).toDate();
			$scope.service.data.include_vat = (response.include_vat == '1') ? true : false;

			$scope.service.client_search = response.client;
		});
	};

	/**
	 * Clears the form
	 */
	$scope.reset = function () {
		$location.path('invoices/new/');
	};

	/**
	 * Sends the invoice to Xero (direct implementation like browse pages)
	 */
	$scope.sendToXero = function () {
		if (!$scope.service.data || !$scope.service.data.id) {
			return;
		}

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

		// Make API call to send to Xero
		Invoice.sendToXero({ id: $scope.service.data.id }, function (response) {
			// Success - update the invoice with Xero data
			if (response.invoice) {
				// Update the invoice object with the response data
				angular.extend($scope.service.data, response.invoice);
			} else {
				// Fallback for backward compatibility
				$scope.service.data.xeroId = response.xero_invoice_id;
				$scope.service.data.xero_synced_at = new Date();
			}

			$scope.service.data.xero_sync_error = null;
			$scope.service.data.xero_syncing = false;

			// Show success message
			Messenger().post({
				message: 'Invoice successfully sent to Xero',
				type: 'success',
				showCloseButton: true
			});
		}, function (error) {
			// Error - update the invoice with error
			$scope.service.data.xero_sync_error = error.data.message || 'Failed to send to Xero';
			$scope.service.data.xero_syncing = false;

			// Show error message
			Messenger().post({
				message: 'Failed to send invoice to Xero: ' + (error.data.message || 'Unknown error'),
				type: 'error',
				showCloseButton: true
			});
		});
	};

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

		// Frontend validation
		var errors = [];

		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);

				// Redirect to the view
				$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);
				}
			});
		}
	};

}]);
