/**
 * SalesBrowseCtrl Controller
 * Extracted from invoices module
 */

Invoices.controller('SalesBrowseCtrl', ['$scope', 'Sale', 'ErrorsHandler', '$filter', '$location', '$paginator', '$timeout', 'InvoiceService', function ($scope, Sale, ErrorsHandler, $filter, $location, $paginator, $timeout, InvoiceService) {

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

	// The list of sales currently loaded
	$scope.data = [];
	$scope.title = 'Browse sales';
	$paginator = angular.copy($paginator);
	$scope.paginator = $paginator;
	$scope.filters = {};
	$scope.service = InvoiceService.create(Sale);
	var search_timeout;

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

	$paginator.setOnPageChange(function (page) {
		$scope.loadData(page);
	});

	$scope.$watch('filters', function (value) {

		if (search_timeout) $timeout.cancel(search_timeout);

		search_timeout = $timeout(function () {
			$scope.loadData();
		}, 100);
	}, true);

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

	$scope.loadInvoice = function (sale) {
		$location.path('/sales/view/' + sale.id + '/');
	};

	$scope.loadData = function (page) {
		if (!page) page = 1;

		var prepared_filter = angular.copy($scope.filters);
		angular.extend(prepared_filter, { page: page, type: 'sale', client: true });

		if ($scope.filters.client) {
			prepared_filter.client_id = $scope.filters.client.id;
			prepared_filter.client_type = $scope.filters.client.type;
		}

		Sale.get(prepared_filter, function (response) {
			$scope.data = response.data;
			
			// Initialize xero_syncing property for all sales to ensure proper binding
			$scope.data.forEach(function(sale) {
				if (typeof sale.xero_syncing === 'undefined') {
					sale.xero_syncing = false;
				}
			});
			
			$paginator.setFromResponse(response);
		}, ErrorsHandler);
	};

	$scope.sendToXero = function (sale) {
		// Show loading state
		sale.xero_syncing = true;

		// Make API call to send to Xero
		Sale.sendToXero({ id: sale.id }, function (response) {
			// Success - reload the data to ensure fresh state from server
			$scope.loadData($scope.paginator.getCurrentPage());
			
			// Show success message
			Messenger().post({
				message: 'Sale successfully sent to Xero',
				type: 'success',
				showCloseButton: true
			});

		}, function (error) {
			// Error - update the sale with error
			sale.xero_sync_error = error.data.message || 'Failed to send to Xero';
			sale.xero_syncing = false;
			
			// Show error message
			Messenger().post({
				message: 'Failed to send sale to Xero: ' + (error.data.message || 'Unknown error'),
				type: 'error',
				showCloseButton: true
			});
		});
	};

}]);
