/**
 * EmailCustomerModalCtrl Controller
 * Handles email customer modal functionality
 */

Bookings.controller("EmailCustomerModalCtrl", [
	"$scope",
	"$uibModalInstance",
	"data",
	"customerEmail",
	"$http",
	"apiUrl",
	"ErrorsHandler",
	"Messenger",
	function (
		$scope,
		$uibModalInstance,
		data,
		customerEmail,
		$http,
		apiUrl,
		ErrorsHandler,
		Messenger
	) {
		// ------------------------------------------------------------------------
		//
		//	SCOPE VARIABLES BELOW -->
		//
		// ------------------------------------------------------------------------

		// Build subject with ticket number and title
		var subject = '[' + data.id + '] ' + (data.title || 'Task');

		$scope.data = {
			task_id: data.id,
			ticket_number: data.id,
			send_to: customerEmail,
			subject: subject,
			message:
				"Dear " +
				(data.client_name || "Customer") +
				",\n\n" +
				"Thank you for your enquiry.\n\n" +
				"We will get back to you as soon as possible.\n\n" +
				"If you have any further questions, please do not hesitate to contact us.\n\n" +
				"Best regards,\n" +
				"Computer Assistance\n" +
				"01865 451177"
		};

		// Loading state
		$scope.sending = false;

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

		$scope.send = function () {
			// Set loading state
			$scope.sending = true;

			// Show sending notification
			if (typeof Messenger !== 'undefined') {
				Messenger("Sending email...");
			}

			$http
				.post(apiUrl("bookings/email-customer"), $scope.data, {
					headers: {
						'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
					}
				})
				.success(function (response) {
					$scope.sending = false;

					// Show success notification
					if (typeof Messenger !== 'undefined') {
						Messenger("Email sent successfully!");
					}

					// Close modal after showing notification
					$uibModalInstance.close('success');
				})
				.error(function (error, status) {
					$scope.sending = false;

					// Show error notification
					var errorMessage = error && error.error ? error.error : 'Failed to send email';
					if (typeof Messenger !== 'undefined') {
						Messenger("Email failed: " + errorMessage);
					}

					// Also call the original error handler for any additional processing
					ErrorsHandler(error, status);
				});
		};

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