/**
 * ClientCtrl Controller
 * Extracted from clients module
 */

ClientsModule.controller('ClientCtrl', ['$scope', 'Client', '$routeParams', 'ErrorsHandler', '$ClientsManager', 'apiUrl', '$http', 'Messenger', '$location', '$uibModal', '$window', 'ClientForm', function ($scope, Client, $routeParams, ErrorsHandler, $ClientsManager, apiUrl, $http, Messenger, $location, $uibModal, $window, ClientForm) {

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

	$scope.data = {};

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



	$scope.tabs = [
		{
			title: 'Summary',
			template: 'clients/client-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: []
	};

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

	$scope.$on('$routeChangeSuccess', function () {
		if ($routeParams.clientId)
			$scope.load();
		else
			$scope.data = {};
	});

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

	$scope.load = function () {
		Client.get({ client: $routeParams.clientId, site_users: true }, function (response) {
			$scope.data = response.data;

			_.each($scope.data.sites, function (el, i) {
				if (i > 0) el.hide = true;
			});

			$ClientsManager.setClient(response.data);
			$ClientsManager.setClientType('client');
		}, ErrorsHandler);

		$http.get(apiUrl('clients/helpers/client-summary/' + $routeParams.clientId))
			.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);
	};

	$scope.showSiteModal = function (site) {
		var modalInstance = $uibModal.open({
			templateUrl: 'clients/site.html',
			controller: 'SiteModalCtrl',
			resolve: {
				DoNotSave: function () {
					return false;
				},
				client_id: function () {
					return $scope.data.id;
				},
				data: function () {
					return site;
				}
			}
		});

		modalInstance.result.then(function (SiteData) {
			if (!site) {
				$scope.data.sites.push(SiteData);
			}
			else {
				site = angular.extend(site, SiteData || {});
			}
		});
	};

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

		Client.get({ name: value, equal: true }, function (response) {
			$scope.duplicate_data = response;
		}, ErrorsHandler);
	};


	$scope.showSiteUserModal = function (site, user) {
		var modalInstance = $uibModal.open({
			templateUrl: 'clients/site-user.html',
			controller: 'SiteUserModalCtrl',
			resolve: {
				DoNotSave: function () {
					return false;
				},
				site: function () {
					return site;
				},
				data: function () {
					return user;
				}
			}
		});

		modalInstance.result.then(function (UserData) {
			if (!site.users) site.users = [];
			if (!user) {
				site.users.push(UserData);
			} else {
				user = angular.extend(user, UserData || {});
			}
		});
	};

	$scope.save = function () {
		Client.update($scope.data, function (response) {
			angular.extend($scope.data, response);
			Messenger("I've succesfully saved the client!");
		}, ErrorsHandler);
	};

	$scope.deleteClient = function () {
		Client.delete({ clientId: $scope.data.id }, function (response) {
			Messenger('I have successfully deleted the client!');
			$location.path('/clients');
		}, ErrorsHandler);
	};

	$scope.syncKashflow = function () {
		$http.get(apiUrl('kashflow/sync-client/client/' + $scope.data.id)).success(function (response) {
			Messenger("The customer details have been successfully stored in Kashflow");
		}).error(ErrorsHandler);
	};

	$scope.subscribe = function () {
		$http.post(apiUrl('clients/subscribe/' + $scope.data.id)).success(function (response) {
			$scope.data.subscribed = true;
			$scope.data.subscribers = response;
			Messenger("You have successfully subscribed to this client");
		}).error(ErrorsHandler);
	};

	$scope.unsubscribe = function () {
		$http.post(apiUrl('clients/unsubscribe/' + $scope.data.id)).success(function (response) {
			$scope.data.subscribed = false;
			$scope.data.subscribers = response;
			Messenger("You have successfully unsubscribed from this client");
		}).error(ErrorsHandler);
	};

	$scope.convert = function () {
		$http.post('/clients/convert-to-customer/' + $scope.data.id)
			.success(function (response) {
				$location.path('/customer/' + 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.createReport = function () {

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

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


	};


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

	$scope.fillPrimaryPhone = function () {
		$scope.data.sites[0].primary_phone = $scope.data.sites[0].users[0].mobile;
	};

	$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.sites[0], {
				address: res.postcode.street ? res.postcode.street : '',
				address2: res.postcode.town && res.postcode.county ? res.postcode.town + ", " + res.postcode.county : ''
			});

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

}]);
