/**
 * SalesViewCtrl Controller
 * Extracted from invoices module
 */

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

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

	$scope.title = 'Sale Receipts';
	$scope.type = 'sale';
	$scope.service = InvoiceService.create(Sale);

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

	$scope.$on('$routeChangeSuccess', function (ev, currentRoute, previousRoute) {
		if ($routeParams.saleId) {
			$scope.loadSale($routeParams.saleId);
		}
	});

	$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.loadSale = function (sale_id) {

		Sale.get({ 'sale': sale_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;
		});
	};

	/**
	 * Checks if the sales receipt has been paid and if not
	 * show a prompt before the user leaves the page.
	 *
	 * @return null
	 */
	$window.onbeforeunload = function () {
		if ($scope.service.data && $scope.service.data.paid == '0') {
			return "You haven't marked this sales receipt as paid. Are you sure you want to leave?";
		}
	};

	$scope.$on('$locationChangeStart', function (event, next, current) {
		if ($scope.service.data && $scope.service.data.paid == '0') {
			if (!confirm("You haven't marked this sales receipt as paid. Are you sure you want to leave?")) {
				event.preventDefault();
			}
		}
	});

	/**
	 * Clean up before the scope gets destroyed.
	 *
	 * @return void
	 */
	$scope.$on("$destroy", function () {
		$window.onbeforeunload = function () { };
	});

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

	/**
	 * Sends the sale 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
		Sale.sendToXero({ id: $scope.service.data.id }, function (response) {
			// Success - update the sale with Xero data
			if (response.invoice) {
				// Update the sale 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: 'Sale successfully sent to Xero',
				type: 'success',
				showCloseButton: true
			});
		}, function (error) {
			// Error - update the sale 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 sale to Xero: ' + (error.data.message || 'Unknown error'),
				type: 'error',
				showCloseButton: true
			});
		});
	};

	/**
	 * Saves the sale (direct implementation like browse pages)
	 */
	$scope.save = function (print, email) {
		console.log('Save function called with:', { print, email });
		console.log('Service data:', $scope.service.data);
		console.log('Client search:', $scope.service.client_search);

		if (!$scope.service.data) {
			console.log('No service data, returning');
			return;
		}

		// Frontend validation
		var errors = [];

		// Check if client is selected (same as original InvoiceService)
		if (!$scope.service.client_search) {
			console.log('No client selected');
			errors.push("Please select a customer");
		} else {
			console.log('Client selected:', $scope.service.client_search);
		}

		// For sales, payment method is required
		if ($scope.service.data.type === 'sale' && !$scope.service.data.method_of_payment) {
			console.log('No payment method selected');
			errors.push("Please select a method of payment");
		} else {
			console.log('Payment method:', $scope.service.data.method_of_payment);
		}

		// 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) {
			console.log('No items found');
			errors.push("Please add at least one item");
		} else {
			console.log('Items found:', $scope.service.data.items);
		}

		// If there are validation errors, show them and return
		if (errors.length > 0) {
			console.log('Validation errors:', errors);
			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 sale
			Sale.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: "Sale 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 sale
			console.log('About to call Sale.save with data:', request_data);
			Sale.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) {
				console.log('Sale.save error:', 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 sale",
							type: "error",
							showCloseButton: true
						});
					}
					ErrorsHandler(response);
				}
			});
		}
	};

}]);
