/**
 * CustomerCtrl Controller
 * Extracted from clients module
 */

ClientsModule.controller('CustomerCtrl', ['$scope', 'Customer', '$routeParams', 'ErrorsHandler', '$ClientsManager', 'apiUrl', '$http', 'CustomerForm', 'Messenger', '$timeout', '$location', '$uibModal', '$window', '$injector',
	function ($scope, Customer, $routeParams, ErrorsHandler, $ClientsManager, apiUrl, $http, CustomerForm, Messenger, $timeout, $location, $uibModal, $window, $injector) {

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

		$scope.data = {};

		$scope.postcode = {
			icon: 'fa fa-crosshairs'
		};

		// Modal title - will be set based on whether we're editing or creating
		$scope.modalTitle = 'Add New Customer';

		$scope.tabs = [
			{
				title: 'Summary',
				template: 'clients/customer-summary.html'
			},
			{
				title: 'Repairs',
				template: 'clients/repairs.html'
			},
			{
				title: 'Remote Support',
				template: 'clients/support.html'
			},
			{
				title: 'Onsite',
				template: 'clients/onsite.html'
			},
			{
				title: 'Messages',
				template: 'clients/messages.html'
			},
			{
				title: 'Orders',
				template: 'clients/orders.html'
			},
			{
				title: 'Sale Leads',
				template: 'clients/sale-leads.html'
			},
			{
				title: 'Projects',
				template: 'clients/projects.html'
			},
			{
				title: 'Calls',
				template: 'clients/calls.html'
			},
			{
				title: 'Invoices',
				template: 'clients/invoices.html'
			}
		];

		$scope.tasks_pie = {
			labels: [],
			data: []
		};

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

		// Simple modal close function for editing existing customers in modal context
		$scope.close = function () {
			console.log('Close function called');
			try {
				// First try to use the injector to get modal instance
				if ($injector && $injector.has && $injector.has('$uibModalInstance')) {
					console.log('Using injector modal instance');
					var modalInstance = $injector.get('$uibModalInstance');
					modalInstance.dismiss('cancel');
					return;
				}

				// Look for customerModal in the scope hierarchy
				var currentScope = $scope;
				while (currentScope) {
					if (currentScope.customerModal && currentScope.customerModal.dismiss) {
						console.log('Found customerModal in scope hierarchy');
						currentScope.customerModal.dismiss('cancel');
						return;
					}
					currentScope = currentScope.$parent;
				}

				// Last resort: try root scope
				if ($scope.$root && $scope.$root.customerModal && $scope.$root.customerModal.dismiss) {
					console.log('Using root scope modal');
					$scope.$root.customerModal.dismiss('cancel');
					return;
				}

				console.log('No modal instance found to close');
			} catch (e) {
				console.error('Error in close function:', e);
			}
		};

		// Alias for cancel function
		$scope.cancel = $scope.close;

		$scope.load = function (custId) {
			if (!custId) custId = $routeParams.customerId;

			Customer.get({ customer: custId }, function (response) {
				$scope.data = response.data;
				$ClientsManager.setClient(response.data);
				$ClientsManager.setClientType('customer');
			}, ErrorsHandler);

			$http.get(apiUrl('clients/helpers/customer-summary/' + custId))
				.success(function (response) {
					$scope.summary = response;
					$scope.tasks_pie.labels = ['Repairs', 'Support', 'Onsite'];
					$scope.tasks_pie.data = [response.count.repairs, response.count.support, response.count.onsite];
				})
				.error(ErrorsHandler);
		};

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

		// Initialize data on controller load if customerId is present
		if ($routeParams.customerId) {
			// We're editing an existing customer
			$scope.modalTitle = 'Edit Customer';
			// Check if we already have the customer data loaded
			if ($ClientsManager.isSelected() && $ClientsManager.getClient().id == $routeParams.customerId) {
				$scope.data = $ClientsManager.getClient();
			} else {
				$scope.load();
			}
		}

		$scope.$on('$routeChangeSuccess', function () {
			if ($routeParams.customerId) {
				// We're editing an existing customer
				$scope.modalTitle = 'Edit Customer';
				// Check if we already have the customer data loaded
				if ($ClientsManager.isSelected() && $ClientsManager.getClient().id == $routeParams.customerId) {
					$scope.data = $ClientsManager.getClient();
				} else {
					$scope.load();
				}
			} else {
				// We're creating a new customer
				$scope.modalTitle = 'Add New Customer';
				$scope.data = {};
			}
		});

		$scope.lookupPostcode = function (postcode) {
			$scope.postcode.icon = 'fa fa-spinner fa-spin';

			$http.post('/clients/postcode', { postcode: postcode }).success(function (res) {

				$scope.postcode.icon = 'fa fa-crosshairs';

				angular.extend($scope.data, {
					address2: res.postcode.street,
					town: res.postcode.town,
					county: res.postcode.county
				});

			}).error(function () {
				$scope.postcode.icon = 'fa fa-crosshairs';
			});
		};

		$scope.submit = function () {
			if ($scope.data.id) {
				Customer.update($scope.data, function (response) {
					$scope.data = response.data;
					Messenger("I've successfully updated the customer!");
					CustomerForm.onUpdate(response.data);
				}, ErrorsHandler);
			}
			else {
				Customer.save($scope.data, function (response) {
					$scope.data = response;
					Messenger("I've successfully created the customer!");
					CustomerForm.onCreate(response.data);
				}, ErrorsHandler);
			}
		};

		$scope.deleteCustomer = function () {
			Customer.delete({ customerId: $scope.data.id }, function (response) {
				Messenger('I have succesfully deleted the customer!');
				$location.path('/clients');
			}, ErrorsHandler);
		};

		$scope.syncXero = function () {
			$http.post(apiUrl('xero/sync-customer/' + $scope.data.id)).success(function (response) {
				// Reload the customer data to get updated Xero ID
				$scope.load();
				Messenger("The customer details have been successfully synced with Xero");
			}).error(ErrorsHandler);
		};

		$scope.convert = function () {
			$http.post('/clients/convert-to-client/' + $scope.data.id)
				.success(function (response) {
					$location.path('/client/' + response.id);
				})
				.error(ErrorsHandler);
		};

		$scope.findDuplicates = function () {
			var modalInstance = $uibModal.open({
				templateUrl: 'clients/modals/duplicates.html',
				controller: 'DuplicatesCtrl',
				resolve: {
					currentClient: function () {
						return $scope.data;
					}
				}
			});
		};

		$scope.lookupDuplicates = function (value) {
			if (!value) return false;

			Customer.get({ q: value }, function (response) {
				$scope.duplicate_data = response;
			}, ErrorsHandler);
		};


		$scope.createReport = function () {

			var modalInstance = $uibModal.open({
				templateUrl: 'clients/modals/report_period.html',
				controller: 'ReportPeriodCtrl',
			});

			modalInstance.result.then(function (selectedPeriod) {
				// console.log(selectedPeriod);
				$window.location.href = "/clients/customer-report/" + $scope.data.id + "?start_date=" + selectedPeriod.startDate + "&end_date=" + selectedPeriod.endDate;
			});
		};

	}]);
