	<link href="https://mutuo.ch/wp-content/themes/twentyeleven__18/sections/upload-docs/css/upload-styles.css" rel="stylesheet">
	<link href="https://mutuo.ch/wp-content/themes/twentyeleven__18/inc/font-awesome-4.7.0/css/font-awesome.min.css"
	      rel="stylesheet">

	<div class="upload-docs-section" id="upload-docs-section">
		<h1 class="upl-title" data-processing-title="Encore un instant, restez avec nous...">Transmettre les documents</h1>
		<p class="upl-info">Vous pouvez ici directment nous transmettre les documents nécessaires comme photos ou fichiers existants.</p>
		<p class="upl-warning-title">Veillez à ce que:</p>
		<ul class="upl-warning-list">
							<li>- les documents soient bien lisibles</li>
							<li>- les documents soient complets (page entière)</li>
					</ul>
		<form id="fileupload" action="/var/www/mutuo.ch/public/wp-content/themes/twentyeleven__18/php" method="POST"
		      enctype="multipart/form-data">
			<div class="col-lg-6">
				<div class="upl-input-block">
					<label for="user-email" class="upl-input-label">Votre e-mail</label>
					<input type="text" id="user-email" name="email-user" value="">
					<input type="hidden" id="user-ip" name="user_ip" value="216.73.216.207">
					<input type="hidden" class="session_field" id="session_field" name="session_value"
					       value="1782592227">
				</div>
				<!-- container for error msg -->
				<div id="error-email"></div>
				<div class="upl-upload-btn">
                    <span class="btn btn-success fileinput-button btn-lg">
                        <i class="fa fa-camera fa-lg" aria-hidden="true"></i>
                        <span>Ajouter des documents</span>
                        <input type="file" name="files[]" class="uploader_img" accept="image/*;capture=camera" multiple>
                    </span>
				</div>
				<div class="fileupload-progress fade">
					<div class="progress progress-striped active" role="progressbar"
					     aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
						<div class="progress-bar progress-bar-success" style="width:0;"></div>
					</div>
					<div class="progress-extended"></div>
				</div>
			</div>
			<div class="col-lg-10 upl-previews">
				<!-- container for previews -->
				<ul class="files">
				</ul>
				<div class="upload-next-btn">Ajouter le document suivant</div>
			</div>
		</form>
		<div style="clear:both;"></div>
		<form method="post" id="submit-docs-form">
			<div class="">
				<div class="submit_btn">
										<input type="hidden" class="test_fields" id="test_fields" name="email" value="">
					<input type="hidden" class="session_field" id="session_field" name="session_value"
					       value="1782592227">
					<input type="hidden" id="user-ip" name="user_ip" value="216.73.216.207">
					<input type="hidden" id="page_id" name="page_id" value="15105">
					<input type="hidden" id="lang" name="lang" value="fr">
																																								<input type="hidden" id="with_missing_docs_logic" name="with_missing_docs_logic" value="0">
															<input type="submit" id="submit_button" class="send-docs-button upload-send-docs-button"
					       name="submit-images" value="Envoyer les documents">
					
					<div id="submit-error-message" class="alert alert-danger" style="display: none; margin-top: 10px;"></div>
				</div>
			<div id="submit-processing-message" class="doc-analysis-waiting-card" style="display: none; margin-top: 10px; clear: both;">
								<div class="doc-analysis-card">
					<h2 class="doc-analysis-title">Documents en cours de vérification</h2>
					<div class="doc-analysis-status">
						<i class="fa fa-file-text-o doc-analysis-status-icon" aria-hidden="true"></i>
						<span>Analyse en cours …</span>
					</div>
					<div class="doc-analysis-timer-section">
						<div class="doc-analysis-timer-ring">
							<svg class="doc-analysis-timer-svg" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
								<circle class="doc-analysis-timer-bg" cx="60" cy="60" r="54" fill="none" stroke="#e8eef5" stroke-width="8"/>
								<circle class="doc-analysis-timer-progress" cx="60" cy="60" r="54" fill="none" stroke="#0363c2" stroke-width="8" stroke-linecap="round" stroke-dasharray="339.292" stroke-dashoffset="339.292"/>
							</svg>
							<span id="doc-analysis-timer-display" class="doc-analysis-timer-value">05:00</span>
						</div>
						<div class="doc-analysis-timer-text">
							<div class="doc-analysis-timer-label">
								<span id="doc-analysis-timer-label">Temps restant estimé: </span>
								<span id="doc-analysis-timer-value">05:00</span>
							</div>
							<div class="doc-analysis-timer-hint">La plupart du temps, c&#039;est plus rapide. Au maximum 5 minutes.</div>
							<div id="doc-analysis-long-wait" class="doc-analysis-long-wait" style="display: none;">La vérification prend un peu plus de temps que prévu. Nous poursuivons l&#039;analyse.</div>
						</div>
					</div>
					<div class="doc-analysis-slider">
						<div id="doc-analysis-slider-messages" class="doc-analysis-slider-messages" data-messages="[&quot;Nous traitons vos documents en toute confidentialit\u00e9.&quot;,&quot;Depuis plus de 40 ans, nous accompagnons nos clients dans leurs projets financiers.&quot;,&quot;En cas de question, n&#039;h\u00e9sitez pas \u00e0 nous contacter : 061 681 85 50 (Fran\u00e7ais)&quot;,&quot;Nous v\u00e9rifions gratuitement si de meilleures conditions sont possibles.&quot;,&quot;Presque termin\u00e9 \u2013 nous finalisons l&#039;analyse.&quot;,&quot;Une bonne lisibilit\u00e9 acc\u00e9l\u00e8re le traitement.&quot;,&quot;Merci pour votre patience.&quot;]">
															<div class="doc-analysis-slider-message active" data-index="0">Nous traitons vos documents en toute confidentialité.</div>
															<div class="doc-analysis-slider-message " data-index="1">Depuis plus de 40 ans, nous accompagnons nos clients dans leurs projets financiers.</div>
															<div class="doc-analysis-slider-message " data-index="2">En cas de question, n&#039;hésitez pas à nous contacter : 061 681 85 50 (Français)</div>
															<div class="doc-analysis-slider-message " data-index="3">Nous vérifions gratuitement si de meilleures conditions sont possibles.</div>
															<div class="doc-analysis-slider-message " data-index="4">Presque terminé – nous finalisons l&#039;analyse.</div>
															<div class="doc-analysis-slider-message " data-index="5">Une bonne lisibilité accélère le traitement.</div>
															<div class="doc-analysis-slider-message " data-index="6">Merci pour votre patience.</div>
													</div>
						<div class="doc-analysis-slider-dots">
															<span class="doc-analysis-slider-dot active" data-index="0"></span>
															<span class="doc-analysis-slider-dot " data-index="1"></span>
															<span class="doc-analysis-slider-dot " data-index="2"></span>
															<span class="doc-analysis-slider-dot " data-index="3"></span>
															<span class="doc-analysis-slider-dot " data-index="4"></span>
															<span class="doc-analysis-slider-dot " data-index="5"></span>
															<span class="doc-analysis-slider-dot " data-index="6"></span>
													</div>
					</div>
				</div>
							</div>
			<div class="loader-icon">
                <div class="bounce1"></div>
                <div class="bounce2"></div>
                <div class="bounce3"></div>
            </div>		</div>
	</form>
	<div id="submit-success-message" style="display: none; margin-top: 20px;">
		<div class="alert alert-success">
			<h4>✅ Merci pour vos documents!</h4>
			<p>Notre équipe traite maintenant votre demande de crédit et nous vous contacterons dès que possible avec une offre.</p>
		</div>
		<div id="missing-docs-message" style="display: none;">
			<h4>⚠️ Notre système a détecté que les documents suivants sont manquants : Les documents seront ensuite vérifiés par un conseiller clientèle.</h4>
			<ul id="missing-docs-list"></ul>
		</div>
	</div>
	</div>

<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <ul class="template-upload fade">
        <li>
			{%
            var str = file.name || '';
            var size = file.size || 0;
            var res = str.split(".");
            var ext = res.length ? res[res.length - 1].toLowerCase() : '';

            if(ext == 'pdf' || ext == 'jpg' || ext == 'jpeg' || ext == 'png' || ext == 'gif'){ %}
            
            {% }
            else{ %}
              <strong class="error invalid-type"></strong>
              {% if (!i) { %}
                <button class="btn btn-warning cancel">
                    Cancel
                </button>
            	{% } %}
            {% }

            if(size > 999000){ %}
              <strong class="error invalid-size"></strong>
              {% if (!i) { %}
                <button class="btn btn-warning cancel">
                    Cancel
                </button>
            	{% } %}
            {% }
            else{ %}
            
            {% }
          %}
            
            <!-- <strong class="error text-danger"></strong> -->
            <!-- {% if (!i) { %}
                <button class="btn btn-warning cancel">
                    Cancel
                </button>
            {% } %} -->
        </li>
    </ul>
{% } %}

</script>

<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
  <li class="template-download">
      <span class="preview">
                    {%
                    var str = file.name || '';
                    var res = str.split(".");
                    var ext = res.length ? res[res.length - 1].toLowerCase() : '';
                    if(ext == 'pdf'){ %}
                      <img src="https://mutuo.ch/wp-content/plugins/custom-seasia-plugin/img/pdf-logo.jpg">
                    {% }
                    else{ %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>

                    {% }
                      %}

                    <!-- <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a> -->

            </span>
            <span class="notfound">
                {% if (file.error) { %}
                  <div><span class="label label-danger">Error</span> {%=file.error%}</div>
              {% } %}
            </span>
            <span class="mu-delete">
                <button class="btn btn-danger delete mut-delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                </button>
            </span>
  </li>

{% } %}

</script>
<script>
	jQuery(document).ready(function () {
		var pendingRentStep = false;
		var currentMissingDocsStep = 'main';
		var missingDocsLeadId = '';
		var missingDocsZohoModule = 'Leads';
		var currentLangCode = 'fr';

		function renderMissingDocsHtml(payload, onRendered) {
			jQuery.ajax({
				url: '/wp-json/twentyeleven__18/v1/render_missing_docs',
				type: 'POST',
				contentType: 'application/json',
				data: JSON.stringify(payload),
				success: function(renderResponse) {
					if (renderResponse.success && renderResponse.html) {
						jQuery('#missing-docs-message').html(renderResponse.html).show();
						initMissingDocsFilePond();
						if (typeof onRendered === 'function') {
							onRendered();
						}
					} else if (payload.missing_doc_categories && payload.missing_doc_categories.length) {
						var $missingContainer = jQuery('#missing-docs-message');
						$missingContainer.html('<h4>⚠️ Notre système a détecté que les documents suivants sont manquants : Les documents seront ensuite vérifiés par un conseiller clientèle.</h4><ul id="missing-docs-list"></ul>');
						payload.missing_doc_categories.forEach(function(category) {
							$missingContainer.find('#missing-docs-list').append('<li>' + category + '</li>');
						});
						$missingContainer.show();
					}
				},
				error: function() {
					if (!payload.missing_doc_categories || !payload.missing_doc_categories.length) {
						return;
					}
					var $missingContainer = jQuery('#missing-docs-message');
					$missingContainer.html('<h4>⚠️ Notre système a détecté que les documents suivants sont manquants : Les documents seront ensuite vérifiés par un conseiller clientèle.</h4><ul id="missing-docs-list"></ul>');
					payload.missing_doc_categories.forEach(function(category) {
						$missingContainer.find('#missing-docs-list').append('<li>' + category + '</li>');
					});
					$missingContainer.show();
				}
			});
		}

		function showRentDocsStep(leadId, zohoModule) {
			currentMissingDocsStep = 'rent';
			renderMissingDocsHtml({
				missing_doc_categories: ['Mietvertrag'],
				lang: currentLangCode,
				lead_id: leadId,
				zoho_module: zohoModule,
				upload_step: 'rent'
			});
		}

		function showMissingDocsAfterClassifier(response) {
			var leadId = response.found_lead_id || response.found_contact_id || '';
			var zohoModule = response.found_lead_id ? 'Leads' : (response.found_contact_id ? 'Contacts' : 'Leads');
			var categories = response.missing_doc_categories || [];
			var needsRentStep = !!response.needs_rent_step;

			missingDocsLeadId = leadId;
			missingDocsZohoModule = zohoModule;
			pendingRentStep = needsRentStep;

			if (!categories.length && !needsRentStep) {
				return;
			}

			jQuery('#submit-success-message .alert-success').hide();

			if (!categories.length && needsRentStep) {
				showRentDocsStep(leadId, zohoModule);
				return;
			}

			currentMissingDocsStep = 'main';
			renderMissingDocsHtml({
				missing_doc_categories: categories,
				lang: currentLangCode,
				lead_id: leadId,
				zoho_module: zohoModule
			});
		}

		var n = jQuery("form#fileupload .table ul.files"); //.children('li').length;
		// console.log(n.children().length);
		// Initialize the jQuery File Upload widget:
		jQuery('#fileupload').fileupload({
			// Uncomment the following to send cross-domain cookies:
			//xhrFields: {withCredentials: true},
			url: '/wp-content/themes/twentyeleven__18/php/'
		});

		jQuery('#fileupload').bind('fileuploaddone', function (e, data) {
			jQuery('#submit_button').attr('style', 'display: block');
			jQuery('.upload-next-btn').addClass('visible-btn');
		});

        jQuery(document).on('click', '.mu-delete', function(){
            if ( jQuery(document).find('.template-download').length <= 1) {
                jQuery('.upload-next-btn').removeClass('visible-btn');
                jQuery('#submit_button').hide();
            }
        });

        jQuery(document).on('click', '.upload-next-btn', function(){
            jQuery(document).find('.uploader_img').trigger('click');
        });

		// Enable iframe cross-domain access via redirect option:
		jQuery('#fileupload').fileupload(
			'option',
			'redirect',
			window.location.href.replace(
				/\/[^\/]*$/,
				'/cors/result.html?%s'
			)
		);

		// AJAX form submission handler
		jQuery('#submit-docs-form').on('submit', function(e) {
			e.preventDefault();
			
			var $form = jQuery(this);
			var $submitBtn = $form.find('#submit_button');
			var $loader = $form.find('.loader-icon, .loader');
			var $errorMsg = $form.find('#submit-error-message');
			var $processingMsg = $form.find('#submit-processing-message');
			var $uploadSection = jQuery('#upload-docs-section');
			var $uploadTitle = $uploadSection.find('.upl-title');
			var originalUploadTitle = $uploadTitle.text();
			var processingUploadTitle = $uploadTitle.data('processing-title');
			var $allButtons = $uploadSection.find('.btn, .fileinput-button, .upload-next-btn, .delete, .mu-delete');
			
			// Get form data
			var formData = {
				email: $form.find('#test_fields').val(),
				session_value: $form.find('#session_field').val(),
				user_ip: $form.find('#user-ip').val(),
				page_id: $form.find('#page_id').val(),
				lang: $form.find('#lang').val()
			};
			
			// Add optional fields if they exist
			var gformLeadId = $form.find('#gform_lead_id').val();
			if (gformLeadId) {
				formData.gform_lead_id = gformLeadId;
			}
			
			var zohoId = $form.find('#zoho_id').val();
			if (zohoId) {
				formData.id = zohoId;
			}
			
			var employment = $form.find('#employment').val();
			if (employment) {
				formData.employment = employment;
			}
			
			var userCivilStatus = $form.find('#user_civil_status').val();
			if (userCivilStatus) {
				formData.user_civil_status = userCivilStatus;
			}
			
			var firstName = $form.find('#first_name').val();
			if (firstName) {
				formData.first_name = firstName;
			}
			
			var lastName = $form.find('#last_name').val();
			if (lastName) {
				formData.last_name = lastName;
			}
			
			var userSpouseIncome = $form.find('#user_spouse_income').val();
			if (userSpouseIncome) {
				formData['user-spouse-income'] = userSpouseIncome;
			}
			
			var showMieteInfo = $form.find('#show_miete_info').val();
			if (showMieteInfo) {
				formData['Show_Miete_Info'] = showMieteInfo;
			}
			
			var withMissingDocsLogic = $form.find('#with_missing_docs_logic').val();
			if (withMissingDocsLogic !== undefined) {
				formData.with_missing_docs_logic = withMissingDocsLogic;
			}

			var uploadStep = $form.find('#upload_step').val();
			if (uploadStep) {
				formData.upload_step = uploadStep;
			}
			
			// Disable submit button, all buttons and show loader + processing message
			$submitBtn.prop('disabled', true);
			$allButtons.prop('disabled', true).css('pointer-events', 'none').css('opacity', '0.5');
			$loader.show();
			var currentLang = $form.find('#lang').val();
			var docAnalysisIntervals = [];
			if (withMissingDocsLogic !== '0' && (currentLang === 'de' || currentLang === 'fr')) {
				$processingMsg.show();
				if (processingUploadTitle) {
					$uploadTitle.text(processingUploadTitle);
				}
				// Start document analysis waiting UI (timer + rotating messages)
				var $card = $processingMsg.find('.doc-analysis-card');
				if ($card.length) {
					var startTime = Date.now();
					var maxDuration = 300; // 5 minutes
					var circumference = 2 * Math.PI * 54;
					var formatTime = function(sec) {
						var m = Math.floor(sec / 60);
						var s = Math.floor(sec % 60);
						return (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
					};
					var timerTick = function() {
						var elapsed = Math.floor((Date.now() - startTime) / 1000);
						var remaining = Math.max(0, maxDuration - elapsed);
						jQuery('#doc-analysis-timer-display, #doc-analysis-timer-value').text(formatTime(remaining));
						var progress = Math.min(1, elapsed / maxDuration);
						var offset = circumference * (1 - progress);
						$card.find('.doc-analysis-timer-progress').css('stroke-dashoffset', offset);
						if (elapsed >= maxDuration) {
							$card.find('.doc-analysis-timer-section .doc-analysis-timer-label, .doc-analysis-timer-hint').hide();
							jQuery('#doc-analysis-long-wait').show();
						}
					};
					timerTick();
					docAnalysisIntervals.push(setInterval(timerTick, 1000));
					// Rotating message slider (8-12 sec, use 10)
					var $messages = $card.find('.doc-analysis-slider-message');
					var $dots = $card.find('.doc-analysis-slider-dot');
					var msgCount = $messages.length;
					if (msgCount > 1) {
						var currentIdx = 0;
						var sliderTick = function() {
							currentIdx = (currentIdx + 1) % msgCount;
							$messages.removeClass('active').eq(currentIdx).addClass('active');
							$dots.removeClass('active').eq(currentIdx).addClass('active');
						};
						docAnalysisIntervals.push(setInterval(sliderTick, 10000));
					}
				}
			}
			$errorMsg.hide();

			// Hide all elements inside .thx-content except .upload-docs-section
			jQuery(document).find('.thx-content')
				.find('.thx-accost, .thx-loan-positive, .thx-docs-title, .thx-missing-docs, .thx-docs-main, .thx-docs-extra, .thx-docs-extra-title, .upload-docs-info, .udi-btn-anchor, .upl-info, .upl-warning-title, .upl-warning-list, .upl-input-block, .upl-upload-btn, .fileupload-progress, .upl-previews, .thank-you-page-video')
				.hide();
			
			
			// Send AJAX request
			jQuery.ajax({
				url: '/wp-json/twentyeleven__18/v1/submit_documents',
				type: 'POST',
				data: formData,
				dataType: 'json',
				success: function(response) {
					console.log('Submit documents response:', response);
					
					if (response.success) {
						// Always redirect on rent step, or when classifier was not triggered
						var isRentStep = formData.upload_step === 'rent';
						if ((isRentStep || response.classifier_triggered === false) && response.redirect_url) {
							console.log('classifier_triggered:', response.classifier_triggered);
							console.log('Redirecting to:', response.redirect_url);
							window.location.href = response.redirect_url;
							return;
						}
						
						docAnalysisIntervals.forEach(function(id) { clearInterval(id); });
						$loader.hide();
						$processingMsg.hide();
						$uploadTitle.text(originalUploadTitle);
						
						// Hide the forms and show success message
						jQuery('#fileupload').hide();
						jQuery('#submit-docs-form').hide();
						jQuery('#submit-success-message').show();
						
						// Show missing docs if any, hide success alert if missing docs or rent step
						if (
							(response.missing_doc_categories && response.missing_doc_categories.length > 0)
							|| response.needs_rent_step
						) {
							showMissingDocsAfterClassifier(response);
						}
					} else {
						docAnalysisIntervals.forEach(function(id) { clearInterval(id); });
                        $loader.hide();
                        $processingMsg.hide();
						$uploadTitle.text(originalUploadTitle);
						// Re-enable buttons on failure
						$submitBtn.prop('disabled', false);
						$allButtons.prop('disabled', false).css('pointer-events', '').css('opacity', '');
					}
				},
				error: function(xhr, status, error) {
					var errorMessage = 'An error occurred. Please try again.';
					
					// Try to get error message from response
					if (xhr.responseJSON && xhr.responseJSON.message) {
						errorMessage = xhr.responseJSON.message;
					}
					
					docAnalysisIntervals.forEach(function(id) { clearInterval(id); });
					$errorMsg.text(errorMessage).show();
					$submitBtn.prop('disabled', false);
					$allButtons.prop('disabled', false).css('pointer-events', '').css('opacity', '');
					$loader.hide();
					$processingMsg.hide();
					$uploadTitle.text(originalUploadTitle);
					
					console.error('Submit documents error:', error);
				}
			});
		});

		if (window.location.hostname === 'blueimp.github.io') {
			// Demo settings:
			jQuery('#fileupload').fileupload('option', {
				url: '//jquery-file-upload.appspot.com/',
				// Enable image resizing, except for Android and Opera,
				// which actually support image resizing, but fail to
				// send Blob objects via XHR requests:
				disableImageResize: /Android(?!.*Chrome)|Opera/
					.test(window.navigator.userAgent),
				maxFileSize: 999000,
				acceptFileTypes: /(\.|\/)(pdf|gif|jpe?g|png)$/i
			});
			// Upload server status check for browsers with CORS support:
			if (jQuery.support.cors) {
				jQuery.ajax({
					url: '',
					type: 'HEAD'
				}).fail(function () {
					jQuery('<div class="alert alert-danger"/>')
						.text('Upload server currently unavailable - ' +
							new Date())
						.appendTo('#fileupload');
				});
			}
		} else {
			// Load existing files:
			jQuery('#fileupload').addClass('fileupload-processing');
			jQuery('.upload-next-btn').removeClass('visible-btn');

			jQuery('#fileupload').fileupload('option', {
				// Enable image resizing, except for Android and Opera,
				// which actually support image resizing, but fail to
				// send Blob objects via XHR requests:
				disableImageResize: /Android(?!.*Chrome)|Opera/
					.test(window.navigator.userAgent),
				maxFileSize: 10000000,
				acceptFileTypes: /(\.|\/)(pdf|gif|jpe?g|png)$/i,
				autoUpload: true
			});

			jQuery.ajax({
				// Uncomment the following to send cross-domain cookies:
				//xhrFields: {withCredentials: true},
				url: '/wp-content/themes/twentyeleven__18/php/',
				dataType: 'json',
				context: jQuery('#fileupload')[0]
			}).always(function () {
				jQuery(this).removeClass('fileupload-processing');
			}).done(function (result) {
				jQuery(this).fileupload('option', 'done')
					.call(this, jQuery.Event('done'), {result: result});
			});
		}
		
		// Function to initialize FilePond for missing docs upload inputs
		function initMissingDocsFilePond() {
			// Check if FilePond is available
			if (typeof FilePond === 'undefined') {
				console.error('FilePond is not loaded');
				return;
			}
			
			// Get lead_id and zoho_module from hidden fields or custom_vars
			var leadIdField = document.getElementById('missing_docs_lead_id');
			var zohoModuleField = document.getElementById('missing_docs_zoho_module');
			var uploadLeadId = leadIdField ? leadIdField.value : ((typeof custom_vars !== 'undefined' && custom_vars.upload_documents_lead_id) ? custom_vars.upload_documents_lead_id : '');
			var uploadZohoModule = zohoModuleField ? zohoModuleField.value : ((typeof custom_vars !== 'undefined' && custom_vars.upload_documents_zoho_module) ? custom_vars.upload_documents_zoho_module : 'Leads');
			var currentLang = 'fr';
			var uploadButtonTextSingle = currentLang === 'fr'
				? '<span class="filepond--label-action">Ajouter le document</span>'
				: '<span class="filepond--label-action">Dokument hinzufügen</span>';
			var uploadButtonTextMultiple = currentLang === 'fr'
				? '<span class="filepond--label-action">Ajouter le document</span>'
				: '<span class="filepond--label-action">Dokument hinzufügen</span>';
			var addMoreText = currentLang === 'fr'
				? '<span class="filepond--label-action add-one-more-file">Ajouter une autre page</span>'
				: '<span class="filepond--label-action add-one-more-file">Eine weitere Seite hinzufügen</span>';
			
			// Use custom_vars values if available
			if (typeof custom_vars !== 'undefined') {
				if (custom_vars.upload_button_text_single) uploadButtonTextSingle = custom_vars.upload_button_text_single;
				if (custom_vars.upload_button_text_multiple) uploadButtonTextMultiple = custom_vars.upload_button_text_multiple;
			}
			
			// Select upload inputs within the missing-docs-message container
			var uploadInputs = document.querySelectorAll('#missing-docs-message .upload-input');
			
			uploadInputs.forEach(function(input) {
				// Check if already initialized
				if (input.classList.contains('filepond--browser')) {
					return;
				}
				
				// Get the name attribute (e.g., "missing_Mietvertrag")
				var inputName = input.getAttribute('name') || '';
				var allowMultiple = inputName.indexOf('Mietvertrag') !== -1 || inputName.indexOf('Steuerveranlagung') !== -1;
				
				var pond = FilePond.create(input, {
					allowMultiple: allowMultiple,
					itemInsertLocation: 'after',
					credits: false,
					labelIdle: allowMultiple ? uploadButtonTextMultiple : uploadButtonTextSingle,
					acceptedFileTypes: ['image/*', 'application/pdf'],
					server: '/wp-json/twentyeleven__18/v1/upload_documents?lead_id=' + uploadLeadId + '&zoho_module=' + uploadZohoModule
				});
				
				// Update label after file is added
				pond.on('addfile', function(error, file) {
					if (error) {
						console.log('FilePond error:', error);
						return;
					}
					pond.labelIdle = addMoreText;
				});
			});
			
			// Attach submit handler for missing docs form
			var submitMissingBtn = document.querySelector('#missing-docs-message .submit-missing-docs');
			if (submitMissingBtn) {
				submitMissingBtn.addEventListener('click', function(event) {
					event.preventDefault();
					
					// Collect all hidden inputs within the missing-docs-message container
					var categories = {};
					var hiddenInputs = document.querySelectorAll('#missing-docs-message .upload-documents-container input[type="hidden"]:not(#missing_docs_lead_id):not(#missing_docs_zoho_module)');
					
					hiddenInputs.forEach(function(input) {
						// Remove "missing_" prefix from name if present
						var name = input.name.replace(/^missing_/, '');
						if (categories[name]) {
							categories[name] += ',' + input.value;
						} else {
							categories[name] = input.value;
						}
					});
					
					console.log('Missing docs categories:', categories);

					var websiteAutomissUserId = (typeof custom_vars !== 'undefined' && custom_vars.website_automiss_user_id)
						? custom_vars.website_automiss_user_id
						: 33;

					if (Object.keys(categories).length > 0) {
						console.log('[mutuo missing-docs] POST autoupload_user_id (WEBSITE_AUTOMISS)', {
							autoupload_user_id: websiteAutomissUserId,
							page: {
								href: window.location.href,
								pathname: window.location.pathname,
								bodyClass: document.body ? document.body.className : ''
							},
							form: {
								id: 'missing-docs-message',
								button: '.submit-missing-docs',
								lead_id: document.querySelector('#missing_docs_lead_id') ? document.querySelector('#missing_docs_lead_id').value : null,
								zoho_module: document.querySelector('#missing_docs_zoho_module') ? document.querySelector('#missing_docs_zoho_module').value : null
							},
							ajax_action: 'mutuo_send_docs'
						});

						jQuery.ajax({
							url: (typeof custom_vars !== 'undefined') ? custom_vars.ajax_url : '/wp-admin/admin-ajax.php',
							method: 'POST',
							data: {
								action: 'mutuo_send_docs',
								_wpnonce: (typeof custom_vars !== 'undefined') ? custom_vars._wpnonce : '',
								categories: categories,
								autoupload_user_id: websiteAutomissUserId,
								lang: currentLang
							},
							beforeSend: function() {
								var container = document.querySelector('#missing-docs-message .upload-documents-container');
								var submitBtn = document.querySelector('#missing-docs-message .submit-missing-docs');
								var spinner = document.querySelector('#missing-docs-message .upload-spinner');
								if (container) container.style.opacity = '0.5';
								if (submitBtn) submitBtn.disabled = true;
								if (spinner) spinner.style.display = 'block';
							},
							success: function(response) {
								if (response.success === true) {
									console.log('Missing docs submitted:', response);

									if (currentMissingDocsStep === 'main' && pendingRentStep) {
										pendingRentStep = false;
										var container = document.querySelector('#missing-docs-message .upload-documents-container');
										var submitBtn = document.querySelector('#missing-docs-message .submit-missing-docs');
										var spinner = document.querySelector('#missing-docs-message .upload-spinner');
										if (container) container.style.opacity = '1';
										if (submitBtn) submitBtn.disabled = false;
										if (spinner) spinner.style.display = 'none';
										showRentDocsStep(missingDocsLeadId, missingDocsZohoModule);
										return;
									}

									if (response.data && (response.data.redirect_url || response.data.thank_you_page_url)) {
										window.location.href = response.data.redirect_url || response.data.thank_you_page_url;
									} else {
								// Show success message
									jQuery('#missing-docs-message').html('<div class="alert alert-success"><h4>✅ Merci pour vos documents!</h4></div>');
									}
								} else {
									var container = document.querySelector('#missing-docs-message .upload-documents-container');
									var submitBtn = document.querySelector('#missing-docs-message .submit-missing-docs');
									var spinner = document.querySelector('#missing-docs-message .upload-spinner');
									if (container) container.style.opacity = '1';
									if (submitBtn) submitBtn.disabled = false;
									if (spinner) spinner.style.display = 'none';
									
									if (response.data && response.data.message) {
										alert(response.data.message);
									}
								}
							},
							error: function(error) {
								console.error('Missing docs submit error:', error);
								var container = document.querySelector('#missing-docs-message .upload-documents-container');
								var submitBtn = document.querySelector('#missing-docs-message .submit-missing-docs');
								var spinner = document.querySelector('#missing-docs-message .upload-spinner');
								if (container) container.style.opacity = '1';
								if (submitBtn) submitBtn.disabled = false;
								if (spinner) spinner.style.display = 'none';
							}
						});
					} else {
						alert('Veuillez télécharger au moins un document.');
					}
				});
			}
		}
	});
</script>
{"id":15105,"date":"2017-02-27T05:41:28","date_gmt":"2017-02-27T05:41:28","guid":{"rendered":"https:\/\/mutuo.ch\/?page_id=15105"},"modified":"2017-04-24T11:08:33","modified_gmt":"2017-04-24T11:08:33","slug":"upload","status":"publish","type":"page","link":"https:\/\/mutuo.ch\/fr\/upload\/","title":{"rendered":"Upload Documents FR"},"content":{"rendered":"\r\n<style>\r\n    .page-id-15105 .upload-section {\r\n        max-width: 960px;\r\n    }\r\n<\/style>","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"upload-page.php","meta":{"_acf_changed":false,"footnotes":""},"class_list":["post-15105","page","type-page","status-publish","hentry"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Upload Documents FR -<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/mutuo.ch\/fr\/upload\/\" \/>\n<meta property=\"og:locale\" content=\"fr_FR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Upload Documents FR -\" \/>\n<meta property=\"og:url\" content=\"https:\/\/mutuo.ch\/fr\/upload\/\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Mutuo-Kredit-123625001558689\/\" \/>\n<meta property=\"article:modified_time\" content=\"2017-04-24T11:08:33+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/mutuo.ch\/wp-content\/uploads\/2020\/03\/1000X1000.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1000\" \/>\n\t<meta property=\"og:image:height\" content=\"1000\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/mutuo.ch\/fr\/upload\/\",\"url\":\"https:\/\/mutuo.ch\/fr\/upload\/\",\"name\":\"Upload Documents FR -\",\"isPartOf\":{\"@id\":\"https:\/\/mutuo.ch\/fr\/#website\"},\"datePublished\":\"2017-02-27T05:41:28+00:00\",\"dateModified\":\"2017-04-24T11:08:33+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/mutuo.ch\/fr\/upload\/#breadcrumb\"},\"inLanguage\":\"fr-CH\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/mutuo.ch\/fr\/upload\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/mutuo.ch\/fr\/upload\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/mutuo.ch\/fr\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Upload Documents FR\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/mutuo.ch\/fr\/#website\",\"url\":\"https:\/\/mutuo.ch\/fr\/\",\"name\":\"\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/mutuo.ch\/fr\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"fr-CH\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Upload Documents FR -","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/mutuo.ch\/fr\/upload\/","og_locale":"fr_FR","og_type":"article","og_title":"Upload Documents FR -","og_url":"https:\/\/mutuo.ch\/fr\/upload\/","article_publisher":"https:\/\/www.facebook.com\/Mutuo-Kredit-123625001558689\/","article_modified_time":"2017-04-24T11:08:33+00:00","og_image":[{"width":1000,"height":1000,"url":"https:\/\/mutuo.ch\/wp-content\/uploads\/2020\/03\/1000X1000.jpg","type":"image\/jpeg"}],"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/mutuo.ch\/fr\/upload\/","url":"https:\/\/mutuo.ch\/fr\/upload\/","name":"Upload Documents FR -","isPartOf":{"@id":"https:\/\/mutuo.ch\/fr\/#website"},"datePublished":"2017-02-27T05:41:28+00:00","dateModified":"2017-04-24T11:08:33+00:00","breadcrumb":{"@id":"https:\/\/mutuo.ch\/fr\/upload\/#breadcrumb"},"inLanguage":"fr-CH","potentialAction":[{"@type":"ReadAction","target":["https:\/\/mutuo.ch\/fr\/upload\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/mutuo.ch\/fr\/upload\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/mutuo.ch\/fr\/"},{"@type":"ListItem","position":2,"name":"Upload Documents FR"}]},{"@type":"WebSite","@id":"https:\/\/mutuo.ch\/fr\/#website","url":"https:\/\/mutuo.ch\/fr\/","name":"","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/mutuo.ch\/fr\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"fr-CH"}]}},"_links":{"self":[{"href":"https:\/\/mutuo.ch\/fr\/wp-json\/wp\/v2\/pages\/15105","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mutuo.ch\/fr\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/mutuo.ch\/fr\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/mutuo.ch\/fr\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mutuo.ch\/fr\/wp-json\/wp\/v2\/comments?post=15105"}],"version-history":[{"count":0,"href":"https:\/\/mutuo.ch\/fr\/wp-json\/wp\/v2\/pages\/15105\/revisions"}],"wp:attachment":[{"href":"https:\/\/mutuo.ch\/fr\/wp-json\/wp\/v2\/media?parent=15105"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}