/**
 * CustomerNotificationCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('CustomerNotificationCtrl', ['$scope', '$uibModalInstance', '$ClientsManager', 'ErrorsHandler', 'Messenger', 'Tasks', 'taskId', 'notification', 'CustomerNotificationsService', function ($scope, $uibModalInstance, $ClientsManager, ErrorsHandler, Messenger, Tasks, taskId, notification, CustomerNotificationsService) {


	$scope.email = {
		selected: false,
		enabled: $ClientsManager.data.email ? true : false,
		send_to: $ClientsManager.data.email,
		sending: false,
		subject: 'Job number ' + taskId + ' is now completed.'
	};

	$scope.email.text = "Dear " + $ClientsManager.data.name + ",<br><br>Just writing to inform you that your job (REF:  " + taskId + " ) is now ready for collection!<br><br>Opening Hours:<br>Monday - Friday 9:00am - 5:00pm<br><br><br>Kind Regards,<br>Your Company Name<br>";

	$scope.sms = {
		selected: false,
		enabled: $ClientsManager.data.mobile ? true : false,
		send_to: $ClientsManager.data.mobile,
		sending: false
	};

	$scope.sms.text = "Hi " + $ClientsManager.data.name + ", your repair " + taskId + " is ready to be collected. Computer Assistance.";

	$scope.notification = notification;
	$scope.submit = function () {

		if ($scope.email.selected == '1')
			$scope.sendEmail();

		if ($scope.sms.selected == '1')
			$scope.sendSMS();

	};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

	$scope.print = function (value) {
		console.log(value);
	};

	$scope.changeSMSSelection = function () {
		$scope.sms.selected = !$scope.sms.selected;
	};

	$scope.sendSMS = function () {
		if ($scope.sms.sending) return false;

		$scope.sms.sending = true;

		var params = {
			send_to: $scope.sms.send_to,
			message: $scope.sms.text,
			id: taskId
		};

		Tasks.sendSMS(params, function (response) {
			$scope.sms.sending = false;
			CustomerNotificationsService.notifications.push(response.notification);
			Messenger("Your text has been successfully sent to the client and should be delivered shortly");
			if (!$scope.email.sending)
				$uibModalInstance.close();

		}, function (a, b) {
			ErrorsHandler(a, b);
			$scope.sms.sending = false;
			if (!$scope.email.sending)
				$uibModalInstance.close();
		});

	};




	$scope.sendEmail = function () {

		if ($scope.email.sending) return false;

		$scope.email.sending = true;

		var params = {
			send_to: $scope.email.send_to,
			message: $scope.email.text,
			subject: $scope.email.subject,
			id: taskId
		};

		Tasks.sendEmail(params, function (response) {
			$scope.email.sending = false;
			CustomerNotificationsService.notifications.push(response.notification);
			Messenger("Your email has been successfully sent to the client and should be delivered shortly");
			if (!$scope.sms.sending)
				$uibModalInstance.close();

		}, function (a, b) {
			ErrorsHandler(a, b);
			$scope.email.sending = false;
			if (!$scope.sms.sending)
				$uibModalInstance.close();
		});
	};

}]);
