/**
 * TaskDedicatedTimeCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('TaskDedicatedTimeCtrl', ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {

	$scope.data = {
		attendant_time: 0,
		unattendant_time: 0
	};
	$scope.response = {
		attendant_time: 0,
		unattendant_time: 0
	};

	$scope.helper = {
		valid_attended: true,
		valid_unattended: true
	}


	$scope.submit = function () {

		$scope.response.attended_time = $scope.convertToSeconds($scope.data.attended_time);

		// FIXED: Since convertToSeconds now always returns >= 0, check for valid input differently
		if ($scope.response.attended_time >= 0)
			$scope.helper.valid_attended = true;
		else
			$scope.helper.valid_attended = false;


		$scope.response.unattended_time = $scope.convertToSeconds($scope.data.unattended_time);

		// FIXED: Since convertToSeconds now always returns >= 0, check for valid input differently  
		if ($scope.response.unattended_time >= 0)
			$scope.helper.valid_unattended = true;
		else
			$scope.helper.valid_unattended = false;

		if ($scope.helper.valid_attended && $scope.helper.valid_unattended)
			$uibModalInstance.close($scope.response);
	};

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

	$scope.convertToSeconds = function (time) {
		// CRITICAL FIX: Handle empty/null/undefined time values
		if (!time || time.trim() === '') {
			return 0;
		}

		var splited = time.split(" ");
		var seconds = 0;

		for (i = 0; i < splited.length; i++) {
			// Skip empty segments
			if (!splited[i] || splited[i].trim() === '') {
				continue;
			}

			var num = 0;  // FIXED: Default to 0 instead of -1

			if (splited[i].indexOf("d") >= 0) {
				num = parseInt(splited[i].replace('d', '')) || 0;  // FIXED: Default to 0
				num = num * 86400; //second per day
			}
			else if (splited[i].indexOf("h") >= 0) {
				num = parseInt(splited[i].replace('h', '')) || 0;  // FIXED: Default to 0
				num = num * 3600; //second per hour
			}
			else if (splited[i].indexOf("m") >= 0) {
				num = parseInt(splited[i].replace('m', '')) || 0;  // FIXED: Default to 0
				num = num * 60; //second per minute
			}

			// REMOVED: if (num < 0) return num; - this was causing the null values
			seconds = seconds + num;
		}

		return seconds;

	};

}]);
