/**
 * SalesNewCtrl Controller
 * Extracted from invoices module
 */

Invoices.controller('SalesNewCtrl', ['$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.taskId) {
			if ($scope.labourTypesLoaded == true) {
				if ($location.path().indexOf('booking') != -1) {
					$scope.loadBookingFee();
				}
				else {
					$scope.service.loadTask($routeParams.taskId);
				}
			}
			else {
				if ($location.path().indexOf('booking') != -1) {
					$scope.$watch('service.labourTypesLoaded', function (newVal, oldVal, scopeSent) {
						if (newVal == true) {
							$scope.loadBookingFee();
						}
					});
				}
				else {
					$scope.$watch('scope.labourTypesLoaded', function (newVal, oldVal, scopeSent) {
						if (newVal == true) {
							$scope.service.loadTask($routeParams.taskId);
						}
					});
				}


			}
		}
	});

	$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.loadBookingFee = function () {
		$scope.service.data.items = [];
		$scope.service.data.booking_fee = $routeParams.taskId;
		$scope.service.data.items.push({
			type: $scope.service.types[$scope.service.bookingFeeTypeIndex].value,
			name: 'Booking fee (REF: ' + $routeParams.taskId + ')',
			price_sold_exc: 28,
			quantity: 1
		});

		// Load the client of the booking
		Tasks.get({ taskId: $routeParams.taskId, client: true }, function (response) {
			if (response.client) {
				$scope.service.client_search = response.client;
			}
		}, ErrorsHandler);


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

	$scope.save = function (print, email) {
		if (!$scope.service.data) {
			return;
		}

		// Frontend validation
		var errors = [];

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

		// For sales, payment method is required
		if ($scope.service.data.type === 'sale' && !$scope.service.data.method_of_payment) {
			errors.push("Please select a 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) {
			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;
		}

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

		// Prepare items for submission
		if (request_data.items) {
			request_data.items = _.filter(request_data.items, function (item) {
				return item.name && item.quantity;
			});
		}

		// Add client data
		if ($scope.service.client_search) {
			request_data.client_id = $scope.service.client_search.id;
			request_data.client_type = $scope.service.client_search.type;
		}

		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 for update
				var type = $scope.service.data.type === 'sale' ? 'Sale' : 'Invoice';
				if (typeof Messenger !== 'undefined' && Messenger().post) {
					Messenger().post({
						message: type + " updated successfully!",
						type: "success",
						showCloseButton: true
					});
				}

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

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

			}, function (a, b) {
				$scope.service.loading = false;
				if (typeof Messenger !== 'undefined' && Messenger().post) {
					Messenger().post({
						message: "An error occurred while updating the sale",
						type: "error",
						showCloseButton: true
					});
				}
				ErrorsHandler(a, b);
			});
		} else {
			// Create new sale
			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 for save
				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 sale",
							type: "error",
							showCloseButton: true
						});
					}
					ErrorsHandler(response);
				}
			});
		}
	};

	$scope.sendToXero = function () {
		if (!$scope.service.data || !$scope.service.data.id) {
			if (typeof Messenger !== 'undefined' && Messenger().post) {
				Messenger().post({
					message: "Please save the sale first before syncing to Xero",
					type: "error",
					showCloseButton: true
				});
			}
			return;
		}

		// Start Xero sync
		$scope.service.data.xero_syncing = true;
		if (typeof Messenger !== 'undefined' && Messenger().post) {
			Messenger().post({
				message: "Sending to Xero...",
				type: "info",
				showCloseButton: true
			});
		}

		Sale.sendToXero({ id: $scope.service.data.id }, function (xeroRes) {
			$scope.service.data.xero_syncing = false;
			if (xeroRes.invoice) {
				angular.extend($scope.service.data, xeroRes.invoice);
			} else {
				$scope.service.data.xeroId = xeroRes.xero_invoice_id;
				$scope.service.data.xero_synced_at = new Date();
			}

			if (typeof Messenger !== 'undefined' && Messenger().post) {
				Messenger().post({
					message: "Successfully synced with Xero!",
					type: "success",
					showCloseButton: true
				});
			}
		}, function (error) {
			$scope.service.data.xero_syncing = false;
			$scope.service.data.xero_sync_error = error.data.message || 'Failed to sync with Xero';
			if (typeof Messenger !== 'undefined' && Messenger().post) {
				Messenger().post({
					message: "Failed to sync with Xero: " + $scope.service.data.xero_sync_error,
					type: "error",
					showCloseButton: true
				});
			}
		});
	};

}]);
