/**
 * InvoicesBrowseCtrl Controller
 * Extracted from invoices module
 */

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

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

	// The list of sales currently loaded
	$scope.data = [];
	$scope.title = 'Browse Invoices';
	$paginator = angular.copy($paginator);
	$scope.paginator = $paginator;
	$scope.filters = {};
	$scope.service = InvoiceService.create(Invoice);
	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 (invoice) {
		$location.path('/invoices/view/' + invoice.id + '/');
	};

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

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

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

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

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

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

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

}]);
