@extends('layouts.front')
@push('styles')
<link rel="stylesheet" href="{{ asset('assets/css/form.css') }}">
@endpush
@section('content')
    <div class="container py-3">
        
        @foreach ($errors->all() as $error)
            <div class="alert alert-danger">
                {{ $error }}
            </div>
        @endforeach
        <!-- Form Container -->
        <div class="form-container">

            <div class="form-title">
                <i class="fas fa-file-invoice-dollar"></i> FICHE DE DEPOT DE PLAINTES
            </div>
            <!-- Progress Bar -->
            <div class="progress-container">
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                <div class="progress-text" id="progressText">0% complété</div>
            </div>
            
            <!-- Form Content -->
            <form id="fundingForm" action="{{ route('plaintes.store') }}" method="POST" enctype="multipart/form-data" class="form-content my-3 needs-validation" novalidate>
                @csrf
                <!-- Section 0: Type de la plainte -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-building"></i>
                        <h3>Type de plainte</h3>
                    </div>
                    <div class="gap-2">
    
                        <div class="checkbox-group">
                            <div class="checkbox-item">
                                <input type="hidden" name="est_anonyme" value="0">
                                <input type="checkbox" name="est_anonyme" value="1" id="est_anonyme" required>
                                <label for="est_anonyme">Plainte anonyme</label>
                            </div>
    
                            <div class="checkbox-item">
                                <input type="hidden" name="est_lanceur_alerte" value="0">
                                <input type="checkbox" name="est_lanceur_alerte" value="1" id="est_lanceur_alerte">
                                <label for="est_lanceur_alerte">Lanceur d'alerte</label>
                            </div>
    
                        </div>
                    </div>
                </div>
                <!-- Section 1: Informations de la plainte -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-building"></i>
                        <h3>Informations du Plaignant</h3>
                    </div>
                    
                        <label class="form-label">Type de plaignant *</label>
                        <div class="checkbox-group">
                            <div class="checkbox-item">
                                <input type="radio" name="plaignant[type]" value="individu" id="individu" required>
                                <label for="individu">Individu</label>
                            </div>
    
                            <div class="checkbox-item">
                                <input type="radio" name="plaignant[type]" value="groupe" id="groupe">
                                <label for="groupe">Groupe</label>
                            </div>
    
                            <div class="checkbox-item">
                                <input type="radio" name="plaignant[type]" value="communaute" id="communaute">
                                <label for="communaute">Communaute</label>
                            </div>
    
                        </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label required">Nom</label>
                            <input type="text" name="plaignant[nom]" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Prénom</label>
                            <input type="text" name="plaignant[prenom]" class="form-control">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Téléphone</label>
                            <input type="tel" name="plaignant[telephone]" class="form-control">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Email</label>
                            <input type="email" name="plaignant[email]" class="form-control">
                        </div>
                    </div>

                </div>

                <!-- Section 2:  Détails de la Plainte -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-tasks"></i>
                        <h3>Détails de la Plainte</h3>
                    </div>
                    <div class="form-group">
                        <label class="form-label required">Objet de la plainte</label>
                        <input type="text" name="objet" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label required">Description détaillée</label>
                        <textarea name="description" class="form-control textarea" rows="5" required placeholder="Décrivez votre plainte de manière détaillée..."></textarea>
                    </div>
                    
                    <div class="form-row triple">
                        <div class="form-group">
                            <label class="form-label required">Canal de réception</label>
                            <select name="canal_reception" class="form-select" required>
                                <option value="">Choisissez...</option>
                                <option value="web">Site Web</option>
                                <option value="email">Email</option>
                                <option value="telephone">Téléphone</option>
                                <option value="courrier_physique">Courrier</option>
                                <option value="boite_plaintes">Boîte à plaintes</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label required">Type de plainte</label>
                            <select name="type_plainte" class="form-select" required>
                                <option value="">Choisissez...</option>
                                <option value="sociale">Sociale</option>
                                <option value="environnementale">Environnementale</option>
                                <option value="genre">Genre</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Options</label>
                            <div class="form-check">
                                <input type="hidden" name="est_anonyme" value="0">
                                <input type="checkbox" name="est_anonyme" value="1" class="form-check-input" id="est_anonyme">
                                <label class="form-check-label" for="est_anonyme">Plainte anonyme</label>
                            </div>
                            <div class="form-check">
                                <input type="hidden" name="est_lanceur_alerte" value="0">
                                <input type="checkbox" name="est_lanceur_alerte" value="1" class="form-check-input" id="est_lanceur_alerte">
                                <label class="form-check-label" for="est_lanceur_alerte">Lanceur d'alerte</label>
                            </div>
                        </div>
                    </div>
                    

                </div>
                <!-- Section 3: Pièces Jointes -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-paperclip"></i>
                        <h3>Pièces justificatives</h3>
                    </div>

                    <div class="form-group">
                        <label class="form-label required">Document du projet complet</label>
                        <input type="file" id="fileInput" name="preuves[]" class="file-input" 
                               accept=".pdf,.doc,.docx,.xls,.xlsx" multiple required>
                        <div class="file-upload-area" onclick="document.getElementById('fileInput').click()">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <h4>Cliquez pour télécharger vos documents</h4>
                            <p>Formats acceptés: PDF, DOC, DOCX, XLS, XLSX</p>
                            <p style="font-size: 0.9rem; color: #666;">Taille maximale: 10 MB par fichier</p>
                        </div>
                        <div class="file-list" id="fileList"></div>
                        <div class="help-text">
                            <i class="fas fa-info-circle"></i>
                            Vous pouvez télécharger plusieurs documents en les sélectionnant dans votre explorateur de fichiers.
                        </div>
                    </div>
                </div>
                <!-- Form Actions -->
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="resetForm()">
                        <i class="fas fa-redo"></i>
                        Réinitialiser
                    </button>
                    <button type="button" class="btn btn-outline" onclick="saveDraft()">
                        <i class="fas fa-save"></i>
                        Enregistrer le brouillon
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-paper-plane"></i>
                        Soumettre la demande
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Success Modal -->
    <div class="success-modal" id="successModal">
        <div class="success-content">
            <div class="success-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <h2>Demande soumise avec succès !</h2>
            <p>Votre demande de financement a été enregistrée.</p>
            <div class="reference-number">
                <i class="fas fa-hashtag"></i> Numéro de référence: <span id="referenceNumber"></span>
            </div>
            <p style="margin-top: 1rem; color: #666;">
                Vous recevrez une confirmation par email dans les prochaines 48 heures.
            </p>
            <button class="btn btn-primary" onclick="closeSuccessModal()" style="margin-top: 1.5rem;">
                <i class="fas fa-home"></i>
                Retour à l'accueil
            </button>
        </div>
    </div>

    
@endsection
@push('scripts')
   <script>
        // Progress tracking
        const form = document.getElementById('fundingForm');
        const progressFill = document.getElementById('progressFill');
        const progressText = document.getElementById('progressText');

        function updateProgress() {
            const inputs = form.querySelectorAll('input[required], textarea[required], select[required]');
            let filled = 0;
            
            inputs.forEach(input => {
                if (input.type === 'checkbox') {
                    const checkboxes = form.querySelectorAll('input[name="guichet[]"]');
                    const anyChecked = Array.from(checkboxes).some(cb => cb.checked);
                    if (anyChecked && !input.dataset.counted) {
                        filled++;
                        input.dataset.counted = true;
                    }
                } else if (input.value.trim() !== '') {
                    filled++;
                }
            });
            
            const percentage = Math.round((filled / inputs.length) * 100);
            progressFill.style.width = percentage + '%';
            progressText.textContent = percentage + '% complété';
        }

        // Add event listeners to all form inputs
        form.addEventListener('input', updateProgress);
        form.addEventListener('change', updateProgress);

        // File upload handling
        const fileInput = document.getElementById('fileInput');
        const fileList = document.getElementById('fileList');
        let uploadedFiles = [];

        fileInput.addEventListener('change', function(e) {
            Array.from(e.target.files).forEach(file => {
                if (file.size > 10 * 1024 * 1024) {
                    alert(`Le fichier ${file.name} dépasse 10 MB`);
                    return;
                }
                
                if (!uploadedFiles.find(f => f.name === file.name)) {
                    uploadedFiles.push(file);
                    addFileToList(file);
                }
            });
            updateProgress();
        });

        function addFileToList(file) {
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            fileItem.innerHTML = `
                <div class="file-item-info">
                    <i class="fas fa-file-${getFileIcon(file.name)}"></i>
                    <span>${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)</span>
                </div>
                <button type="button" class="remove-file" onclick="removeFile('${file.name}')">
                    <i class="fas fa-times"></i>
                </button>
            `;
            fileList.appendChild(fileItem);
        }

        function getFileIcon(filename) {
            const ext = filename.split('.').pop().toLowerCase();
            const icons = {
                'pdf': 'pdf',
                'doc': 'word',
                'docx': 'word',
                'xls': 'excel',
                'xlsx': 'excel'
            };
            return icons[ext] || 'alt';
        }

        function removeFile(filename) {
            uploadedFiles = uploadedFiles.filter(f => f.name !== filename);
            const items = fileList.querySelectorAll('.file-item');
            items.forEach(item => {
                if (item.textContent.includes(filename)) {
                    item.remove();
                }
            });
            updateProgress();
        }

        // Form validation and submission
        // form.addEventListener('submit', function(e) {
        //     e.preventDefault();
            
        //     // Validate required fields
        //     const requiredFields = form.querySelectorAll('[required]');
        //     let isValid = true;
        //     let firstInvalidField = null;

        //     requiredFields.forEach(field => {
        //         if (field.type === 'checkbox') {
        //             const checkboxes = form.querySelectorAll('input[name="guichet[]"]');
        //             const anyChecked = Array.from(checkboxes).some(cb => cb.checked);
        //             if (!anyChecked && !firstInvalidField) {
        //                 isValid = false;
        //                 firstInvalidField = field;
        //             }
        //         } else if (!field.value.trim()) {
        //             isValid = false;
        //             field.style.borderColor = '#dc3545';
        //             if (!firstInvalidField) {
        //                 firstInvalidField = field;
        //             }
        //         } else {
        //             field.style.borderColor = '#e9ecef';
        //         }
        //     });

        //     // Check if at least one guichet is selected
        //     const guichetCheckboxes = form.querySelectorAll('input[name="guichet[]"]');
        //     const guichetSelected = Array.from(guichetCheckboxes).some(cb => cb.checked);
            
        //     if (!guichetSelected) {
        //         isValid = false;
        //         alert('Veuillez sélectionner au moins un guichet du FIE');
        //         return;
        //     }

        //     // Check if files are uploaded
        //     if (uploadedFiles.length === 0) {
        //         isValid = false;
        //         alert('Veuillez joindre au moins un document de projet');
        //         return;
        //     }

        //     if (!isValid) {
        //         alert('Veuillez remplir tous les champs obligatoires');
        //         if (firstInvalidField) {
        //             firstInvalidField.scrollIntoView({ behavior: 'smooth', block: 'center' });
        //             firstInvalidField.focus();
        //         }
        //         return;
        //     }

        //     // Collect form data
        //     const formData = new FormData(form);
            
        //     // Add files to formData
        //     uploadedFiles.forEach(file => {
        //         formData.append('files[]', file);
        //     });

        //     // Show success modal
        //     showSuccessModal();
        // });

        function showSuccessModal() {
            const referenceNumber = 'FIE-' + Date.now().toString().slice(-8);
            document.getElementById('referenceNumber').textContent = referenceNumber;
            document.getElementById('successModal').classList.add('show');
            
            // Log form data (in production, this would be sent to server)
            console.log('Demande soumise:', {
                reference: referenceNumber,
                date: new Date().toISOString(),
                files: uploadedFiles.length
            });
        }

        function closeSuccessModal() {
            document.getElementById('successModal').classList.remove('show');
            resetForm();
        }

        // Reset form
        function resetForm() {
            if (confirm('Êtes-vous sûr de vouloir réinitialiser le formulaire ?')) {
                form.reset();
                uploadedFiles = [];
                fileList.innerHTML = '';
                updateProgress();
                
                // Reset checkbox counters
                form.querySelectorAll('input[type="checkbox"]').forEach(cb => {
                    delete cb.dataset.counted;
                });
            }
        }

        // Save draft
        function saveDraft() {
            const formData = {};
            const inputs = form.querySelectorAll('input, textarea, select');
            
            inputs.forEach(input => {
                if (input.type === 'checkbox') {
                    if (!formData[input.name]) {
                        formData[input.name] = [];
                    }
                    if (input.checked) {
                        formData[input.name].push(input.value);
                    }
                } else if (input.type !== 'file') {
                    formData[input.name] = input.value;
                }
            });

            // Save to localStorage
            localStorage.setItem('fie_funding_draft', JSON.stringify(formData));
            
            alert('Brouillon enregistré avec succès ! Vous pouvez revenir plus tard pour terminer votre demande.');
            
            console.log('Brouillon sauvegardé:', formData);
        }

        // Load draft on page load
        window.addEventListener('load', function() {
            const draft = localStorage.getItem('fie_funding_draft');
            
            if (draft) {
                const shouldLoad = confirm('Un brouillon a été trouvé. Voulez-vous le charger ?');
                
                if (shouldLoad) {
                    const formData = JSON.parse(draft);
                    
                    Object.keys(formData).forEach(key => {
                        const input = form.querySelector(`[name="${key}"]`);
                        
                        if (input) {
                            if (input.type === 'checkbox') {
                                const checkboxes = form.querySelectorAll(`[name="${key}"]`);
                                checkboxes.forEach(cb => {
                                    if (formData[key].includes(cb.value)) {
                                        cb.checked = true;
                                    }
                                });
                            } else {
                                input.value = formData[key];
                            }
                        }
                    });
                    
                    updateProgress();
                } else {
                    localStorage.removeItem('fie_funding_draft');
                }
            }
        });

        // Auto-save every 2 minutes
        setInterval(function() {
            const inputs = form.querySelectorAll('input, textarea, select');
            let hasContent = false;
            
            inputs.forEach(input => {
                if (input.value && input.value.trim() !== '') {
                    hasContent = true;
                }
            });
            
            if (hasContent) {
                saveDraft();
                console.log('Auto-sauvegarde effectuée');
            }
        }, 120000); // 2 minutes

        // Validate numeric inputs
        const numericInputs = form.querySelectorAll('input[type="number"]');
        numericInputs.forEach(input => {
            input.addEventListener('input', function() {
                if (this.value < 0) {
                    this.value = 0;
                }
            });
        });

        // Format currency display
        const currencyInputs = document.querySelectorAll('input[name="cout_total"], input[name="montant_sollicite"]');
        currencyInputs.forEach(input => {
            input.addEventListener('blur', function() {
                if (this.value) {
                    const formatted = parseFloat(this.value).toLocaleString('fr-FR');
                    const label = this.parentElement.querySelector('.form-label');
                    if (label && !label.querySelector('.formatted-value')) {
                        const span = document.createElement('span');
                        span.className = 'formatted-value';
                        span.style.cssText = 'color: #2e8b57; font-weight: normal; margin-left: 0.5rem;';
                        span.textContent = `(${formatted} FCFA)`;
                        label.appendChild(span);
                    }
                }
            });
        });

        // Initialize progress on load
        updateProgress();

        // Smooth scroll to top button
        window.addEventListener('scroll', function() {
            const scrollBtn = document.getElementById('scrollTopBtn');
            if (!scrollBtn) {
                const btn = document.createElement('button');
                btn.id = 'scrollTopBtn';
                btn.innerHTML = '<i class="fas fa-arrow-up"></i>';
                btn.style.cssText = `
                    position: fixed;
                    bottom: 2rem;
                    right: 2rem;
                    width: 50px;
                    height: 50px;
                    border-radius: 50%;
                    background: linear-gradient(135deg, #2e8b57, #228b22);
                    color: white;
                    border: none;
                    cursor: pointer;
                    display: none;
                    align-items: center;
                    justify-content: center;
                    font-size: 1.2rem;
                    box-shadow: 0 4px 15px rgba(46, 139, 87, 0.3);
                    transition: all 0.3s ease;
                    z-index: 1000;
                `;
                btn.addEventListener('click', function() {
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                });
                document.body.appendChild(btn);
            }
            
            const scrollTopBtn = document.getElementById('scrollTopBtn');
            if (window.pageYOffset > 300) {
                scrollTopBtn.style.display = 'flex';
            } else {
                scrollTopBtn.style.display = 'none';
            }
        });
    </script> 
    <script>
        (function () {
            'use strict'
            var forms = document.querySelectorAll('.needs-validation')
            Array.prototype.slice.call(forms)
                .forEach(function (form) {
                    form.addEventListener('submit', function (event) {
                        if (!form.checkValidity()) {
                            event.preventDefault()
                            event.stopPropagation()
                        }
                        form.classList.add('was-validated')
                    }, false)
                })
        })()
    </script>
@endpush
