angular.module('edecApp')
    .controller('ImportController', function($scope, $http, $window, $rootScope, $timeout, $location, ConfigService, TranslationService) {
        
        function initScope() {
            $scope.step = 1;
            $scope.method = null;
            $scope.vehicle = {};
            $scope.parties = {
                importer: { name: '', firstname: '', address: '', zip: '', city: '', ide: '' },
                consignee: { name: '', firstname: '', address: '', zip: '', city: '', ide: '' },
                declarant: { name: '', firstname: '', address: '', zip: '', city: '', ide: '' }
            };
            $scope.declarantType = 'importer';
            $scope.declaration = {
                transport_mode: '',
                purchase_currency: '',
                purchase_price: 0,
                transport_cost: 0,
                other_costs: 0,
                dispatch_country: '',
                language: $rootScope.lang || 'fr'
            };
            $scope.classification = null;
            $scope.ocrLoading = false;
            $scope.preparing = false;
            $scope.ocrAttempted = false;
			$scope.ocrCountdownActive = false;
            $scope.vinValid = null;
			$scope.classificationError = null; // <-- NOUVEAU: Stocke le message d'erreur de classification
			$scope.reporting = false;          // <-- NOUVEAU: Flag de chargement pour le signalement
            $scope.statisticalValueCHF = 0;
            $scope.vatValueCHF = 0;
            $scope.isCompany = false;
            $scope.sessionToken = null;
            $scope.submissionProgress = 0;
            $scope.submissionStep = '';
            $scope.submissionResult = null;
            $scope.showProgress = false;
            $scope.eventSource = null;
            $scope.showStripeButton = false;
            $scope.tooltips = {
                transportMode: false,
                relocation: false,
                ivaExempt: false
            };
            $scope.ocrCountdown = 0;
            $scope.ocrCountdownActive = false;
        }
		
        const SESSION_STORAGE_KEY = 'edec_import_form';
        let saveTimeout = null;

		// Nouvelle fonction pour gérer le chargement du script Stripe
		function loadStripeBuyButtonScript() {
			$timeout(function() {
				if (!document.getElementById('stripe-buy-button-script')) {
					const script = document.createElement('script');
					script.id = 'stripe-buy-button-script';
					script.src = 'https://js.stripe.com/v3/buy-button.js';
					script.async = true;
					document.head.appendChild(script);
				}
			}, 100);
		}

		function loadStripeBuyButtonScript() {
            $timeout(function() {
                if (!document.getElementById('stripe-buy-button-script')) {
                    const script = document.createElement('script');
                    script.id = 'stripe-buy-button-script';
                    script.src = 'https://js.stripe.com/v3/buy-button.js';
                    script.async = true;
                    document.head.appendChild(script);
                }
            }, 100);
        }

		// Fonction pour mettre en évidence TOUS les champs obligatoires manquants
		$scope.highlightInvalidFields = function(formName) {
			const form = $scope[formName];
			if (!form) return false;

			let hasErrors = false;

			// Remove validation-error class from all form fields
			const formElement = document.querySelector('form[name="' + formName + '"]');
			if (formElement) {
				const allFields = formElement.querySelectorAll('input, select');
				allFields.forEach(field => field.classList.remove('validation-error'));
			}

			// Marquer tous les champs invalides comme "touched" et "dirty"
			angular.forEach(form, function(field, fieldName) {
				if (fieldName.indexOf('$') !== 0) { // Ignorer les propriétés internes d'AngularJS
					if (field && field.$invalid) {
						field.$setDirty();
						field.$setTouched();
						// Add validation-error class to the DOM element
						const element = document.querySelector('[name="' + fieldName + '"]');
						if (element) {
							element.classList.add('validation-error');
						}
						hasErrors = true;
					}
				}
			});

			// Forcer un digest pour mettre à jour l'affichage
			if (!$scope.$$phase) {
				$scope.$apply();
			}

			// Scroll vers le premier champ invalide après un court délai
			$timeout(function() {
				const firstInvalid = document.querySelector('.validation-error');
				if (firstInvalid) {
					firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });

					// Focus sur le champ si c'est un input/select
					if (firstInvalid.tagName === 'INPUT' || firstInvalid.tagName === 'SELECT') {
						firstInvalid.focus();
					}
				}
			}, 200);

			return hasErrors;
		};

        function saveState() {
            $timeout.cancel(saveTimeout);
            saveTimeout = $timeout(function() {
                const dataToSave = {
                    step: Math.min($scope.step || 1, 3),
                    method: $scope.method,
                    vehicle: angular.copy($scope.vehicle),
                    parties: angular.copy($scope.parties),
                    declarantType: $scope.declarantType,
                    declaration: angular.copy($scope.declaration),
                    sessionToken: $scope.sessionToken
                };
                sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(dataToSave));
            }, 500);
        }

        function loadSavedState() {
            const savedData = sessionStorage.getItem(SESSION_STORAGE_KEY);
            if (savedData) {
                try {
                    const parsedData = JSON.parse(savedData);
                    $scope.step = parsedData.step || 1;
                    $scope.method = parsedData.method || null;
                    angular.extend($scope.vehicle, parsedData.vehicle || {});
                    angular.extend($scope.parties, parsedData.parties || {
                        importer: {}, consignee: {}, declarant: {}
                    });
                    $scope.declarantType = parsedData.declarantType || 'importer';
                    angular.extend($scope.declaration, parsedData.declaration || {});
                    $scope.sessionToken = parsedData.sessionToken || null;
                    $scope.isCompany = !!$scope.parties.importer.ide && $scope.parties.importer.ide.trim() !== 'CHE222251936';
                    
                    // Si on a un sessionToken, on peut afficher le bouton Stripe
                    if ($scope.sessionToken && $scope.step === 3) {
                        $scope.showStripeButton = true;
						loadStripeBuyButtonScript();
                    }
                    
                    $rootScope.showNotification($rootScope.t('data_restored'), 'info');
                    return true;
                } catch (e) {
                    sessionStorage.removeItem(SESSION_STORAGE_KEY);
                    return false;
                }
            }
            return false;
        }

        // Gestion du retour de paiement annulé
        const urlParams = new URLSearchParams($window.location.search);
        if (urlParams.get('payment_cancelled') === 'true') {
            $rootScope.showNotification('Paiement annulé. Vous pouvez réessayer.', 'warning');
            // Nettoyer l'URL
            $location.search('payment_cancelled', null);
        }

        initScope();
        loadSavedState();
		
        ConfigService.getCurrencies().then(data => $scope.currencies = data);

		// Initialiser vide
		$scope.transportModes = [];

		// Attendre que les traductions soient chargées
		TranslationService.getPromise.then(function() {
			// Fonction pour générer les modes de transport traduits
			$scope.getTransportModes = function() {
				return [
					{ value: '9', label: $rootScope.t('transport_mode_9') },
					{ value: '3', label: $rootScope.t('transport_mode_3') },
					{ value: '2', label: $rootScope.t('transport_mode_2') },
					{ value: '4', label: $rootScope.t('transport_mode_4') },
					{ value: '8', label: $rootScope.t('transport_mode_8') },
					{ value: '7', label: $rootScope.t('transport_mode_7') }
				];
			};
			
			// Initialiser les modes de transport
			$scope.transportModes = $scope.getTransportModes();
			
			// Mettre à jour quand la langue change
			$scope.$watch(() => $rootScope.lang, function(newLang) {
				if (newLang) {
					$scope.transportModes = $scope.getTransportModes();
				}
			});
		});

        $scope.$watch('parties.importer.ide', function(newVal) {
            $scope.isCompany = !!newVal && newVal.trim() !== 'CHE222251936';
        });

        $scope.$watch('vehicle', saveState, true);
        $scope.$watch('parties', saveState, true);
        $scope.$watch('declaration', saveState, true);
        $scope.$watch('declarantType', saveState);
        $scope.$watch('step', saveState);
        $scope.$watch('method', saveState);
		// Gestion de l'exclusivité IDE vs Prénom pour tous les parties
		$scope.$watch('parties.importer.ide', function(newVal) {
			$scope.importerHasIDE = !!newVal && newVal.trim() !== '';
		});

		$scope.$watch('parties.importer.firstname', function(newVal) {
			$scope.importerHasFirstname = !!newVal && newVal.trim() !== '';
		});

		$scope.$watch('parties.consignee.ide', function(newVal) {
			$scope.consigneeHasIDE = !!newVal && newVal.trim() !== '';
		});

		$scope.$watch('parties.consignee.firstname', function(newVal) {
			$scope.consigneeHasFirstname = !!newVal && newVal.trim() !== '';
		});

		$scope.$watch('parties.declarant.ide', function(newVal) {
			$scope.declarantHasIDE = !!newVal && newVal.trim() !== '';
		});

		$scope.$watch('parties.declarant.firstname', function(newVal) {
			$scope.declarantHasFirstname = !!newVal && newVal.trim() !== '';
		});

        $scope.$watch('submissionResult', function(newVal) {
            if (newVal) {
                sessionStorage.removeItem(SESSION_STORAGE_KEY);
            }
        });

        $scope.selectMethod = function(method) {
            $scope.method = method;
            $scope.step = 2;
        };

        $scope.triggerFileInput = () => document.getElementById('file-upload').click();

		$scope.handleFileSelect = function(event, context) {
			const files = event.target.files;
			if (!files || files.length === 0) return;

			$scope.$apply(() => {
				$scope.ocrLoading = true;
				$scope.ocrAttempted = true;
			});
			
			const formData = new FormData();
			formData.append('registration_card', files[0]);

			$http.post('/api/ocr', formData, {
				transformRequest: angular.identity,
				headers: { 'Content-Type': undefined }
			}).then(function(response) {
				const ocrData = response.data;
				// Pour import: utiliser paper_origin pour dispatch_country
				if (context === 'import' && ocrData.paper_origin && $rootScope.countries) {
					const ocrCountryName = ocrData.paper_origin.toLowerCase().trim();
					const countryCode = Object.keys($rootScope.countries).find(code => {
						const fullCountryName = $rootScope.countries[code].toLowerCase().trim();
						const mainCountryName = fullCountryName.split('(')[0].trim();
						return mainCountryName === ocrCountryName;
					});
					if (countryCode) {
						$scope.declaration.dispatch_country = countryCode;
					}
				}
				
				delete ocrData.paper_origin;
				angular.extend($scope.vehicle, ocrData);
				
				if ($scope.vehicle.vin) $scope.validateVIN();
				$scope.updateClassification();
				$rootScope.showNotification($rootScope.t('ocr_success'), 'success');
				$scope.startOcrCountdown();
			}).catch(function(error) {
				const details = error.data?.details || error.data?.error || 'Erreur inconnue';
				$rootScope.showNotification('Erreur OCR: ' + details, 'error');
			}).finally(() => {
				$scope.ocrLoading = false;
			});
		};

        $scope.startOcrCountdown = function() {
            $scope.ocrCountdown = 30;
            $scope.ocrCountdownActive = true;
            
            const interval = setInterval(function() {
                $scope.$apply(function() {
                    $scope.ocrCountdown--;
                    if ($scope.ocrCountdown <= 0) {
                        $scope.ocrCountdownActive = false;
                        clearInterval(interval);
                    }
                });
            }, 1000);
        };

        $scope.validateVIN = function() {
            if (!$scope.vehicle.vin || $scope.vehicle.vin.length !== 17) {
                $scope.vinValid = false;
                return;
            }
            $http.post('/api/validate-vin', { vin: $scope.vehicle.vin })
                .then(function(response) {
                    $scope.vinValid = response.data.valid;
                    if (response.data.valid && response.data.country && !$scope.declaration.dispatch_country) {
                        $scope.declaration.dispatch_country = response.data.country;
                    }
                }).catch(function() {
                    $scope.vinValid = false;
                });
        };

        $scope.updateClassification = function() {
			// Réinitialisation des erreurs précédentes avant le nouvel appel
			$scope.classification = null;
			$scope.classificationError = null; // <-- IMPORTANT: Réinitialiser l'état d'erreur

			if (!$scope.vehicle.fuel_type || !$scope.vehicle.weight_empty) return;
			
			$http.post('/api/classify-vehicle', $scope.vehicle)
				.then(function(response) {
					
					// 🛑 GESTION DE L'ERREUR DE CLASSIFICATION (NOUVEAU)
					if (response.data.error) {
						// Le backend a retourné un objet d'erreur
						$scope.classificationError = response.data.message; // Stocke le message
						$rootScope.showNotification(response.data.message, 'error');
						return; // Stoppe l'exécution, on ne classe rien.
					}

					// Cas de succès (Logique originale)
					$scope.classification = response.data;
					$scope.vehicle.commodity_code = response.data.commodity_code;
					if (!response.data.needs_user_selection) {
						$scope.vehicle.statistical_key = response.data.statistical_key;
					}
				})
				.catch(function(error) {
					// Gestion des erreurs de connexion/serveur HTTP
					const message = error.data?.message || 'Erreur réseau lors de la classification.';
					$scope.classificationError = message; 
					$rootScope.showNotification(message, 'error');
				});
		};
		
		/**
		 * NOUVELLE FONCTION : Signale les données du véhicule non classées.
		 * Envoie les données à un endpoint pour enregistrement en DB.
		 */
		$scope.reportClassificationError = function() {
			if ($scope.reporting) return;
			
			$scope.reporting = true; // Active le flag de chargement
			
			const payload = {
				vehicle: $scope.vehicle,
				classification_error: $scope.classificationError || 'Classification non trouvée (signalement manuel)',
				// Ajouter des informations de contexte utiles
				importer_ide: $scope.parties.importer.ide || null,
				user_lang: $scope.declaration.language
			};

			$http.post('/api/report-classification-error', payload)
				.then(function(response) {
					if (response.data.success) {
						// Vous pouvez choisir de remettre à zéro le formulaire ou de laisser l'utilisateur corriger
						$rootScope.showNotification($rootScope.t('error_reported_success') + ' - Merci pour votre aide!', 'success');
					} else {
						$rootScope.showNotification(response.data.message || $rootScope.t('error_reporting_failed'), 'error');
					}
				})
				.catch(function(error) {
					$rootScope.showNotification($rootScope.t('error_reporting_network') + ': ' + (error.data?.message || 'Erreur réseau'), 'error');
				})
				.finally(() => {
					$scope.reporting = false;
				});
		};

        $scope.calculateTotal = function() {
            const price = parseFloat($scope.declaration.purchase_price) || 0;
            const transport = parseFloat($scope.declaration.transport_cost) || 0;
            const other = parseFloat($scope.declaration.other_costs) || 0;
            const currency = $scope.declaration.purchase_currency;
            
            ConfigService.getExchangeRates().then(function(rates) {
                if (!rates || !rates[currency]) return;
                const rate = rates[currency].rate;
                $scope.statisticalValueCHF = Math.round(price * rate);
                $scope.vatValueCHF = Math.round((price + transport + other) * rate);
            });
        };

		$scope.nextStep = function() {
			if ($scope.classificationError) {
				$rootScope.showNotification($rootScope.t('classification_error_block'), 'error');
				return;
			}

			if ($scope.step === 2) {
				const hasErrors = $scope.highlightInvalidFields('vehicleForm');
				
				if (hasErrors || !$scope.vehicle.vin || !$scope.vehicle.brand || !$scope.vehicle.model || 
					!$scope.vehicle.fuel_type || !$scope.vehicle.weight_empty || !$scope.vehicle.weight_total) {
					$rootScope.showNotification($rootScope.t('fill_required_vehicle'), 'error');
					return;
				}
			}
			
			$scope.step++;
			
			$timeout(function() {
				window.scrollTo({ top: 0, behavior: 'smooth' });
			}, 100);
		};

        $scope.prevStep = () => $scope.step--;

        $scope.copyConsigneeToImporter = function() {
            $scope.parties.importer = angular.copy($scope.parties.consignee);
            $rootScope.showNotification($rootScope.t('info_copied'), 'success');
        };

        $scope.showTooltip = function(tooltip, show) {
            $scope.tooltips[tooltip] = show;
        };

        $scope.toggleTooltip = function(tooltip) {
            $scope.tooltips[tooltip] = !$scope.tooltips[tooltip];
        };

        $scope.copyLinkToClipboard = function(link) {
            const tempInput = document.createElement('input');
            tempInput.style.position = 'absolute';
            tempInput.style.left = '-9999px';
            tempInput.value = 'myautoimport.ch' + link;

            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand('copy');
            document.body.removeChild(tempInput);
            $rootScope.showNotification($rootScope.t('link_copied'), 'success');
        };

        /**
         * NOUVELLE FONCTION : Préparer la déclaration (génération XML AVANT paiement)
         */
		// CORRECTION 3: Remplacer prepareDeclaration dans importController.js
		$scope.prepareDeclaration = function() {
			if ($scope.preparing) return;

			const hasErrors = $scope.highlightInvalidFields('valuationForm');
			
			const imp = $scope.parties.importer;
			if (hasErrors || !imp.name || !imp.zip || !imp.city || !$scope.declaration.dispatch_country) {
				$rootScope.showNotification($rootScope.t('fill_required_importer'), 'error');
				return;
			}
			
			if (!$scope.declaration.purchase_price || $scope.declaration.purchase_price <= 0) {
				$rootScope.showNotification($rootScope.t('fill_valid_price'), 'error');
				// Highlight the purchase_price field
				const priceElement = document.querySelector('[name="purchase_price"]');
				if (priceElement) {
					priceElement.classList.add('validation-error');
				}
				return;
			}
			
			if ($scope.declaration.purchase_price < 2000 && !$scope.declaration.price_confirmation) {
				$rootScope.showNotification($rootScope.t('confirm_low_price'), 'error');
				return;
			}

			$scope.preparing = true;

			const payload = {
				type: 'import',
				vehicle: $scope.vehicle,
				parties: $scope.parties,
				declaration: $scope.declaration,
				declarantType: $scope.declarantType
			};

			$http.post('/api/prepare-declaration', payload)
				.then(function(response) {
					if (response.data.success) {
						$scope.sessionToken = response.data.sessionToken;
						$scope.showStripeButton = true;
						saveState();
						loadStripeBuyButtonScript();
						$rootScope.showNotification('Déclaration prête ! Procédez au paiement.', 'success');
					} else {
						$rootScope.showNotification(response.data.message || 'Erreur de préparation', 'error');
					}
				})
				.catch(function(error) {
					$rootScope.showNotification('Erreur: ' + (error.data?.message || 'Erreur réseau'), 'error');
				})
				.finally(() => {
					$scope.preparing = false;
				});
		};

        /**
         * Écoute du statut de soumission après paiement validé
         */
        $scope.listenForSubmissionStatus = function() {
            if (!$scope.sessionToken) return;

            if ($scope.eventSource) {
                $scope.eventSource.close();
            }

            $scope.step = 4;
            $scope.showProgress = true;

            const source = new EventSource('/api/submission-status-sse/' + $scope.sessionToken);
            $scope.eventSource = source;

            console.log('[SSE-CLIENT] Connexion SSE établie pour:', $scope.sessionToken);

            // Fallback polling au cas où SSE ne reçoit pas l'événement final
            let fallbackTimeout = setTimeout(() => {
                console.log('[SSE-CLIENT] Timeout SSE - Activation du polling de secours');
                $scope.checkSubmissionStatusFallback();
            }, 120000); // 2 minutes

            source.onopen = function() {
                console.log('[SSE-CLIENT] Connexion SSE ouverte');
            };

            source.onmessage = function(event) {
                console.log('[SSE-CLIENT] Message SSE reçu:', event.data);
                $scope.$apply(() => {
                    try {
                        const status = JSON.parse(event.data);

                        $scope.submissionProgress = status.progress;
                        $scope.submissionStep = status.step;

                        if (status.status === 'submitted') {
                            console.log('[SSE-CLIENT] Statut "submitted" reçu - Succès!');
                            clearTimeout(fallbackTimeout);
                            $scope.submissionResult = status;
                            $scope.showProgress = false;
                            source.close();
                            sessionStorage.removeItem(SESSION_STORAGE_KEY);
                            $rootScope.showNotification($rootScope.t('submission_success'), 'success');
                        } else if (status.status === 'submission_error') {
                            console.log('[SSE-CLIENT] Statut "submission_error" reçu');
                            clearTimeout(fallbackTimeout);
                            $scope.showProgress = false;
                            source.close();
                            $rootScope.setErrorContext($scope.sessionToken);
                            $rootScope.showNotification($rootScope.t('submission_error_detected'), 'error');
                        }
                    } catch (e) {
                        console.error('[SSE-CLIENT] Erreur parsing:', e);
                    }
                });
            };

            source.onerror = function(error) {
                console.error('[SSE-CLIENT] Erreur de connexion SSE:', error);
                $scope.$apply(() => {
                    $scope.submissionStep = 'Erreur de connexion SSE...';
                });
            };

            source.onclose = function() {
                console.log('[SSE-CLIENT] Connexion SSE fermée');
            };
        };

        // Fallback polling si SSE échoue
        $scope.checkSubmissionStatusFallback = function() {
            if (!$scope.sessionToken) return;

            console.log('[FALLBACK] Vérification du statut via HTTP polling');

            $http.get('/api/submission-status/' + $scope.sessionToken)
                .then(function(response) {
                    const status = response.data;
                    console.log('[FALLBACK] Statut récupéré:', status);

                    if (status.status === 'submitted') {
                        console.log('[FALLBACK] Statut final "submitted" détecté');
                        $scope.submissionResult = status;
                        $scope.showProgress = false;
                        if ($scope.eventSource) $scope.eventSource.close();
                        sessionStorage.removeItem(SESSION_STORAGE_KEY);
                        $rootScope.showNotification($rootScope.t('submission_success'), 'success');
                    } else if (status.status === 'submission_error') {
                        console.log('[FALLBACK] Erreur de soumission détectée');
                        $scope.showProgress = false;
                        if ($scope.eventSource) $scope.eventSource.close();
                        $rootScope.setErrorContext($scope.sessionToken);
                        $rootScope.showNotification($rootScope.t('submission_error_detected'), 'error');
                    } else {
                        // Si pas encore terminé, revérifier dans 5 secondes
                        setTimeout(() => $scope.checkSubmissionStatusFallback(), 5000);
                    }
                })
                .catch(function(error) {
                    console.error('[FALLBACK] Erreur HTTP:', error);
                    // Réessayer dans 10 secondes en cas d'erreur
                    setTimeout(() => $scope.checkSubmissionStatusFallback(), 10000);
                });
        };

        $scope.downloadPDF = function(path) {
            if (!path) return;
            $window.open('/api/download-pdf?path=' + encodeURIComponent(path), '_blank');
        };

        $scope.clearValidationError = function(element) {
            angular.element(element).removeClass('validation-error');
        };

        $scope.resetForm = function() {
            if ($scope.eventSource) $scope.eventSource.close();
            sessionStorage.removeItem(SESSION_STORAGE_KEY);
            // Remove validation-error classes from all forms
            const forms = ['vehicleForm', 'valuationForm'];
            forms.forEach(formName => {
                const formElement = document.querySelector('form[name="' + formName + '"]');
                if (formElement) {
                    const allFields = formElement.querySelectorAll('input, select');
                    allFields.forEach(field => field.classList.remove('validation-error'));
                }
            });
            initScope();
            $rootScope.showNotification($rootScope.t('form_reset'), 'info');
        };

        // Gestion du retour de Stripe (depuis payment-success)
        $scope.checkPaymentReturn = function() {
            const returnData = sessionStorage.getItem('stripe_payment_return');
            if (returnData) {
                try {
                    const data = JSON.parse(returnData);
                    if (data.sessionToken === $scope.sessionToken) {
                        sessionStorage.removeItem('stripe_payment_return');
                        $scope.listenForSubmissionStatus();
                    }
                } catch (e) {
                    console.error('Erreur parsing returnData:', e);
                }
            }
        };

        // Vérifier au chargement
        $scope.checkPaymentReturn();

        ConfigService.getCurrencies().then(data => $scope.currencies = data);

        $scope.$watch('vehicle', saveState, true);
        $scope.$watch('parties', saveState, true);
        $scope.$watch('declaration', saveState, true);
        $scope.$watch('declarantType', saveState);
        $scope.$watch('step', saveState);
        $scope.$watch('method', saveState);

        $scope.selectMethod = function(method) {
            $scope.method = method;
            $scope.step = 2;
        };

        $scope.validateVIN = function() {
            if (!$scope.vehicle.vin || $scope.vehicle.vin.length !== 17) {
                $scope.vinValid = false;
                return;
            }
            $http.post('/api/validate-vin', { vin: $scope.vehicle.vin })
                .then(function(response) {
                    $scope.vinValid = response.data.valid;
                    if (response.data.valid && response.data.country && !$scope.declaration.dispatch_country) {
                        $scope.declaration.dispatch_country = response.data.country;
                    }
                }).catch(function() {
                    $scope.vinValid = false;
                });
        };
    });

