angular.module('edecApp')
    .controller('ExportController', function($scope, $http, $window) {
        $scope.vehicle = {};
        $scope.export = {
            export_type: 'temporary'
        };
        $scope.countries = {};

        $http.get('/api/countries').then(res => $scope.countries = res.data);

        $scope.generateExport = function() {
            const data = {
                ...$scope.vehicle,
                ...$scope.export,
                language: 'fr'
            };

            $http.post('/api/generate-export', data, {
                responseType: 'blob'
            }).then(response => {
                const blob = new Blob([response.data], { type: 'application/xml' });
                const url = $window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `edec-export-${Date.now()}.xml`;
                a.click();
                $window.URL.revokeObjectURL(url);

                alert('Déclaration d\'export générée avec succès !');
            }).catch(error => {
                alert('Erreur: ' + (error.data?.error || 'Erreur de génération'));
            });
        };
    });
