/**
 * Clients Module - Cleaned Version
 * 
 * 16 controllers extracted to /controllers/ directory
 * Controllers are loaded via controllers.js manifest
 * 
 * This module now contains:
 * - Module definition and configuration
 * - Route configuration
 * - Services and factories
 * - Directives (if any)
 */

var ClientsModule = angular.module('ClientsModule', []);

ClientsModule.config(['$routeProvider', function ($routeProvider) {

	$routeProvider.when('/clients', {
		controller: 'ClientsMainCtrl',
		templateUrl: 'clients/overview.html'
	});

	$routeProvider.when('/client/:clientId', {
		controller: 'ClientCtrl',
		templateUrl: 'clients/client.html'
	});

	$routeProvider.when('/customer/:customerId', {
		controller: 'CustomerCtrl',
		templateUrl: 'clients/customer.html'
	});

}]);

/**
 * Services
 */
ClientsModule.factory('CustomerForm', function () {

	return {
		onUpdate: function () { },
		onCreate: function () { }
	};
});

/**
 * Services
 */
ClientsModule.factory('ClientForm', function () {

	return {
		onUpdate: function () { },
		onCreate: function () { }
	};
});

/**
 *	The main controller for the clients page.
 *
 */

ClientsModule.factory('Marketing', ['apiUrl', '$resource', 'ResourceMethods', 'ResourcePrototype', function (apiUrl, $resource, methods, _prototype) {

	// Create custom methods
	methods['reach'] = { method: 'GET', url: apiUrl('clients/marketing/reach') };
	methods['preview'] = { method: 'POST', url: apiUrl('clients/marketing/preview') };
	methods['export'] = { method: 'POST', url: apiUrl('clients/marketing/export') };

	var Stock = $resource(apiUrl('clients/marketing'), {}, methods);
	angular.extend(Stock.prototype, _prototype);
	return Stock;
}]);

ClientsModule.directive('clientCalls', function () {
	return {
		restrict: 'AE',
		templateUrl: 'clients/templates/calls.html',
		controller: 'ClientCallsCtrl',
		scope: {
			'clientId': '@',
			'clientType': '@',
			'taskId': '@'
		}
	};
});

ClientsModule.directive('clientTasksStats', [function () {
	return {
		template: '<div data-google-chart data-chart="chart"></div>',
		restrict: 'AE',
		scope: {
			type: '@',
			supportInf: '=',
			repairInf: '=',
			onsiteInf: '=',
		},
		controller: ['$scope', '$timeout', '$http', 'apiUrl', 'ErrorsHandler', function ($scope, $timeout, $http, apiUrl, ErrorsHandler) {

			/**
			 * Holds the piechart data
			 *
			 * @type Object
			 */
			$scope.chart = {
				type: 'PieChart',
				options: {
					'title': '',
					'width': 150,
					'height': 200,
					'legend': 'top',
					'vAxis': { maxValue: 10 },
					'chartArea': { width: '100%' }
				},
				data: {
					cols: [
						{
							id: 'type',
							label: 'Type',
							type: 'string'
						},
						{
							id: $scope.type,
							label: $scope.type.toUpperCase(),
							type: 'number'
						}
					],
					rows: []
				}
			};

			/**
			 * Sends an AJAX request to the server to load the data
			 *
			 * @return null
			 */
			$scope.loadData = function () {

				var data = [];
				data.push({
					c: [{ v: 'onsite' }, { v: parseInt($scope.onsiteInf, 10) }]
				});
				data.push({
					c: [{ v: 'support' }, { v: parseInt($scope.supportInf, 10) }]
				});
				data.push({
					c: [{ v: 'repair' }, { v: parseInt($scope.repairInf, 10) }]
				});

				// Set the data for the chart
				$scope.chart.data.rows = data;

			};

			$scope.loadData();

		}] // End of controller
	};
}]);

ClientsModule.directive('clientInvoices', ['Invoice', '$paginator', '$ClientsManager', 'ErrorsHandler', function (Invoice, $paginator, $ClientsManager, ErrorsHandler) {
	return {
		scope: {},
		transclude: true,
		link: function ($scope, $element, $attrs, ctrl, transclude) {

			transclude($scope, function (clone) {
				$element.append(clone);
			});

			$paginator = angular.copy($paginator);
			$scope.paginator = $paginator;

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

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

			$paginator.setOnLimitChange(function (page, limit) {
				$scope.load(page);
			});

			$scope.$watch(function () { return $ClientsManager.getClient(); }, function (value) {
				if (value && value.id)
					$scope.load();
			}, true);

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

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

				Invoice.get({ client_id: $ClientsManager.getClient().id, client_type: $ClientsManager.getClientType(), page: page }, function (response) {
					$scope.data = response.data;
					$scope.paginator.setFromResponse(response);
				}, ErrorsHandler);
			};

		}
	};
}]);

ClientsModule.directive('clientsTable', ['$http', 'ErrorsHandler', 'Client', '$paginator', function ($http, ErrorsHandler, Client, $paginator) {
	return {
		link: {
			pre: function ($scope, $element, $attrs) {

				// Make a copy of the paginator, so that we have
				// a unique instance
				$paginator = angular.copy($paginator);

				$scope.paginator = $paginator;

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

				$paginator.setOnLimitChange(function (page, limit) {
					$scope.load(page);
				});

				/**
				 * Loads a clients from the database.
				 *
				 * @return void
				 */
				$scope.load = function (page) {
					if (!page) page = 1;
					$scope.loading = true;

					Client.get({ primary_site: true, primary_contact: true, contract: true, active_tasks: true, revenue: true, page: page }, function (response) {
						$scope.data = response.data;
						$paginator.setFromResponse(response);
						$scope.loading = false;
					}, ErrorsHandler);
				};

				// Load the initial data
				$scope.load();

			}
		}
	};
}]);

ClientsModule.directive('clientsWidget', ['$ClientsManager', '$uibModal', 'Follow', 'ErrorsHandler', '$sce', '$rootScope', function ($ClientsManager, $uibModal, Follow, ErrorsHandler, $sce, $rootScope) {
	return {
		scope: {
			site: '=',
			site_user: '=siteUser',
			task: '=',
			showNewBooking: "@"
		},
		replace: true,
		templateUrl: 'clients/templates/widget.html',
		link: {
			pre: function ($scope, $element, $attrs) {

				$scope.ClientsManager = $ClientsManager;

				// 3CX Call state management
				$scope.callInProgress = {};

				/**
				 * Watch for when the client changes and unify all the changes.
				 */
				$scope.$watch(function () {
					return $scope.ClientsManager.client;
				}, function (value) {
					$ClientsManager.unify($scope.site, $scope.site_user);
				}, true);

				$rootScope.$on('open-licenses-modal', function () {
					$scope.licenses();
				});

				/**
				 * Displays a modal popup for sending an SMS
				 *
				 * @return null
				 */
				$scope.sms = function () {
					var modalInstance = $uibModal.open({
						templateUrl: 'bookings/modals/sms.html',
						controller: 'SmsCtrl',
						resolve: {
							task: function () {
								return $scope.task;
							},
							mobile: function () {
								return $scope.ClientsManager.data.mobile;
							}
						}
					});
				};

				/**
				 * 3CX Call functionality for widget buttons
				 *
				 * @param {string} phoneNumber - The phone number to call
				 * @param {string} type - The type of call (phone, phone2, mobile)
				 * @return null
				 */
				$scope.makeCall = function (phoneNumber, type) {
					console.log('=== ClientsWidget.makeCall CALLED ===');
					console.log('phoneNumber:', phoneNumber);
					console.log('type:', type);
					console.log('$scope.task:', $scope.task);
					console.log('window.ThreeCXTaskIntegration exists:', !!window.ThreeCXTaskIntegration);
					console.log('window.ThreeCXCore exists:', !!window.ThreeCXCore);
					console.log('window.ThreeCXCallModal exists:', !!window.ThreeCXCallModal);

					// Set call in progress for UI state
					$scope.callInProgress[type] = true;

					// Setup cleanup function for when call ends
					var cleanupCall = function () {
						$scope.callInProgress[type] = false;
						$scope.$apply();
						console.log('Call cleanup completed for type:', type);

						// Refresh call history when call dialog closes
						if (window.refreshCallHistory && $scope.task && $scope.task.id) {
							console.log('Triggering call history refresh after call dialog close');
							setTimeout(function () {
								window.refreshCallHistory();
							}, 1000); // Short delay to allow server-side logging to complete
						}
					};

					// Set up modal close listener for cleanup (check if ThreeCXCallModal exists)
					if (window.ThreeCXCallModal && window.ThreeCXCallModal.closeModal) {
						var originalCloseModal = window.ThreeCXCallModal.closeModal;
						window.ThreeCXCallModal.closeModal = function () {
							cleanupCall();
							originalCloseModal.call(this);
							// Restore original function
							window.ThreeCXCallModal.closeModal = originalCloseModal;
						};
					}

					// CRITICAL: Set task context before making the call
					window.ThreeCXCore.setContext('task');
					console.log('Task context set for automatic call logging:', $scope.task.id);

					// Use the same API as admin integration
					return window.ThreeCXCore.makeCall(phoneNumber, {
						extension: document.querySelector('meta[name="user-extension"]')?.content || '324',
						taskId: $scope.task.id,
						source: 'task_widget',
						call_type: type || 'phone'
					});

				};

				/**
				 * Changes the client for a task or a project
				 *
				 * @return null
				 */
				$scope.changeClient = function () {
					var modalInstance = $uibModal.open({
						templateUrl: 'bookings/modals/change-client.html',
						controller: 'ChangeClientCtrl',
						resolve: {
							task: function () {
								return $scope.task;
							}
						}
					});

					modalInstance.result.then(function (data) {
						var client = data[0];
						var task = data[1];

						$scope.site = task.site;
						$scope.site_user = task.site_user;

						$ClientsManager.setClient(client);
						$ClientsManager.setClientType(client.type);
						$ClientsManager.unify($scope.site, $scope.site_user);
					});
				};

				/**
				 * Displays the edit modal based on the client type.
				 */
				$scope.edit = function () {
					if ($ClientsManager.getClientType() == 'client') {
						$scope.editClient();
					}
					else {
						$scope.editCustomer();
					}
				};

				/**
				 * Edit a customer
				 */
				$scope.editCustomer = function () {
					var modalInstance = $uibModal.open({
						templateUrl: 'clients/modals/edit-customer.html',
						controller: 'EditCustomerCtrl',
						size: 'lg',
						resolve: {
							client: function () {
								return $ClientsManager.getClient();
							}
						}
					});

					modalInstance.result.then(function (client) {
						$ClientsManager.setClient(client);
						$ClientsManager.setClientType(client.type);
						$ClientsManager.unify($scope.site, $scope.site_user);
						
						// Refresh the page to show updated customer information
						setTimeout(function() {
							location.reload();
						}, 500);
					});
				};

				/**
				 * Edit a client
				 */
				$scope.editClient = function () {
					var modalInstance = $uibModal.open({
						templateUrl: 'clients/modals/edit-client.html',
						controller: 'EditClientCtrl',
						size: 'lg',
						resolve: {
							client: function () {
								return $ClientsManager.getClient();
							},
							site: function () {
								return $scope.site;
							},
							site_user: function () {
								return $scope.site_user;
							}
						}
					});

					modalInstance.result.then(function () {
						$ClientsManager.unify($scope.site, $scope.site_user);
					});
				};

				/**
				 * Starts following a client
				 */
				$scope.follow = function () {
					Follow.save({
						related_id: $ClientsManager.client.id,
						related_type: $ClientsManager.getClientType()
					}, function (response) {
						$ClientsManager.client.follow = response;
					}, ErrorsHandler);
				};

				/**
				 * Stops following a client
				 */
				$scope.unfollow = function () {
					Follow.delete({ followId: $ClientsManager.client.follow.id }, function (response) {
						$ClientsManager.client.follow = {};
					}, ErrorsHandler);
				};

				/**
				 * Display a modal with all the customer's passwords
				 *
				 * @return null
				 */
				$scope.keychain = function () {
					var modalInstance = $uibModal.open({
						templateUrl: 'clients/modals/keychain.html',
						controller: 'KeychainModalCtrl',
						resolve: {
							Customer: function () {
								return $ClientsManager.getClient();
							},
							TaskId: function () {
								return $scope.task.id;
							}
						}
					});
				};

				/**
				 * Display a modal with all the customer's passwords
				 *
				 * @return null
				 */
				$scope.licenses = function () {
					var modalInstance = $uibModal.open({
						templateUrl: 'clients/modals/licenses.html',
						controller: 'LicensesModalCtrl',
						resolve: {
							Customer: function () {
								return $ClientsManager.getClient();
							}
						}
					});
				};

				/**
				 * Trust the given url.
				 */
				$scope.trustSrc = function (src) {
					return $sce.trustAsResourceUrl(src);
				}

				$scope.dial = function (number, phone) {

					var promise = $scope.dialer.dial(number, phone, $scope.task.id, $ClientsManager.client.id, $ClientsManager.client.type);

					promise.then(function (response) {

					}, ErrorsHandler);
				};

				/**
				 * Send notification to client via the modal
				 */
				$scope.sendNotification = function () {
					$scope.sendingNotification = true;

					var modalInstance = $uibModal.open({
						templateUrl: 'bookings/modals/new-customer-notification.html',
						controller: 'CustomerNotificationCtrl',
						windowClass: 'modal-fixed',
						resolve: {
							taskId: function () {
								return $scope.task.id;
							},
							notification: null
						}
					});

					modalInstance.result.finally(function() {
						$scope.sendingNotification = false;
					});
				};

				/**
				 * Send completion SMS to customer
				 * @param {string} phoneType - The type of phone number (phone, phone2, mobile)
				 */
				$scope.sendCompletionSMS = function (phoneType) {
					var phoneNumber = '';

					// Get the phone number based on type
					switch(phoneType) {
						case 'phone':
							phoneNumber = $scope.ClientsManager.data.phone;
							break;
						case 'phone2':
							phoneNumber = $scope.ClientsManager.data.phone2;
							break;
						case 'mobile':
							phoneNumber = $scope.ClientsManager.data.mobile;
							break;
					}

					// Open SMS modal with completion template
					var modalInstance = $uibModal.open({
						templateUrl: 'bookings/modals/sms.html',
						controller: 'SmsCtrl',
						resolve: {
							task: function () {
								return $scope.task;
							},
							mobile: function () {
								return phoneNumber;
							}
						}
					});
				};

			}
		}
	};
}]);

ClientsModule.directive('customersTable', ['$http', 'ErrorsHandler', 'Customer', '$paginator', function ($http, ErrorsHandler, Customer, $paginator) {
	return {
		link: {
			pre: function ($scope, $element, $attrs) {

				// Make a copy of the paginator, so that we have
				// a unique instance
				$paginator = angular.copy($paginator);

				$scope.paginator = $paginator;

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

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

				$paginator.setOnLimitChange(function (page, limit) {
					$scope.load(page);
				});

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

				/**
				 * Loads a clients from the database.
				 *
				 * @return void
				 */
				$scope.load = function (page) {
					if (!page) page = 1;
					$scope.loading = true;

					Customer.get({ active_tasks: true, spent: true, page: page }, function (response) {
						$scope.data = response.data;
						$paginator.setFromResponse(response);
						$scope.loading = false;
					}, ErrorsHandler);
				};

				// Load the initial data
				$scope.load();

			}
		}
	};
}]);

ClientsModule.directive('taskTable', ['Repair', 'Support', 'Onsite', 'Message', 'Order', 'SaleLead', 'Project', 'ErrorsHandler', '$paginator', '$ClientsManager', function (Repair, Support, Onsite, Message, Order, SaleLead, Project, ErrorsHandler, $paginator, $ClientsManager) {

	return {
		scope: {},
		transclude: true,
		link: function ($scope, $element, $attrs, ctrl, transclude) {

			transclude($scope, function (clone) {
				$element.append(clone);
			});

			$paginator = angular.copy($paginator);

			$scope.paginator = $paginator;

			$scope.types = {
				'repairs': Repair,
				'support': Support,
				'onsite': Onsite,
				'messages': Message,
				'orders': Order,
				'sale-lead': SaleLead,
				'projects': Project
			};

			$scope.tooltips = {
				paid: 'Paid',
				open: 'In progress',
				payment: 'Awaiting payment',
				invoice: 'Needs invocing'
			};

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

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

			$paginator.setOnLimitChange(function (page, limit) {
				$scope.load(page);
			});

			$scope.$watch(function () { return $ClientsManager.getClient(); }, function (value) {
				if (value && value.id)
					$scope.load();
			}, true);

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

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

				$scope.types[$attrs['taskType']].get({ client_id: $ClientsManager.getClient().id, client_type: $ClientsManager.getClientType(), site_user: true, summary: true, client: true, user: true, page: page }, function (response) {
					$scope.data = response.data;
					$scope.paginator.setFromResponse(response);
				}, ErrorsHandler);
			};

		}
	};
}]);

