angular.module('edecApp')
    .controller('SubmissionErrorController', function($scope, $http, $rootScope) {
        $scope.sessionToken = sessionStorage.getItem('error_session_token');
		console.log('SessionToken :', $scope.sessionToken);
        $scope.data = {}; // <--- CREATE AN OBJECT
        $scope.data.email = ''; // <--- BIND THE EMAIL TO THE OBJECT
        $scope.submitted = false;
        $scope.errorMessage = '';

        $scope.reportError = function() {
            if (!$scope.data.email || $scope.data.email.trim() === '') { // <--- CHECK THE OBJECT PROPERTY
                $scope.errorMessage = $rootScope.t('email_required') || 'Veuillez saisir une adresse email.';
                return;
            }
            
            // Validation email simple mais correcte
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test($scope.data.email)) {
                $scope.errorMessage = $rootScope.t('email_invalid') || 'Format d\'email invalide.';
                return;
            }
            
            if (!$scope.sessionToken) {
                $scope.errorMessage = 'Session expirée. Veuillez nous contacter au +41 76 360 73 63.';
                return;
            }
            
            $scope.errorMessage = '';
            
            $http.post('/api/submission-error/report', {
                sessionToken: $scope.sessionToken,
                email: $scope.data.email
            }).then(function(response) {
                if (response.data.success) {
                    $scope.submitted = true;
					console.log('response :', response);
                } else {
                    $scope.errorMessage = response.data.error || 'Une erreur est survenue.';
                }
            }).catch(function(error) {
                $scope.errorMessage = error.data?.error || 'Une erreur est survenue.';
            });
        };
    });