@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> @lang('messages.funding_request_form')
            </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% @lang('messages.complete')</div>
            </div>
            <!-- Form Content -->
            <form id="fundingForm" action="{{ route('financements.store') }}" method="POST" enctype="multipart/form-data" class="form-content my-3 needs-validation" novalidate>
                @csrf
                <!-- Section 1: Informations de la Structure -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-building"></i>
                        <h3>@lang('messages.structure_information')</h3>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.structure_name')</label>
                            <input type="text" name="nom_structure" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.legal_status')</label>
                            <select name="statut_juridique" class="form-control" required>
                                <option value="">@lang('messages.select')...</option>
                                <option value="association">@lang('messages.association')</option>
                                <option value="ong">@lang('messages.ngo')</option>
                                <option value="cooperative">@lang('messages.cooperative')</option>
                                <option value="entreprise">@lang('messages.company')</option>
                                <option value="groupement">@lang('messages.group')</option>
                                <option value="autre">@lang('messages.other')</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.email')</label>
                            <input type="email" name="email" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.phone')</label>
                            <input type="tel" name="telephone" class="form-control" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label required">@lang('messages.complete_address')</label>
                        <textarea name="adresse" class="form-textarea" required></textarea>
                        <div class="help-text" style="margin-top: 1rem;">
                            <i class="fas fa-info-circle"></i>
                            @lang('messages.attach_documents')
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.ifu_number')</label>
                            <input type="text" name="numero_ifu" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.rccm_number')</label>
                            <input type="text" name="numero_rccm" class="form-control" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.region')</label>
                            <select name="region" class="form-control" required>
                                <option value="">@lang('messages.select')...</option>
                                <option value="Boucle du Mouhoun">Boucle du Mouhoun</option>
                                <option value="Cascades">Cascades</option>
                                <option value="Centre">Centre</option>
                                <option value="Centre-Est">Centre-Est</option>
                                <option value="Centre-Nord">Centre-Nord</option>
                                <option value="Centre-Ouest">Centre-Ouest</option>
                                <option value="Centre-Sud">Centre-Sud</option>
                                <option value="Est">Est</option>
                                <option value="Hauts-Bassins">Hauts-Bassins</option>
                                <option value="Nord">Nord</option>
                                <option value="Plateau-Central">Plateau-Central</option>
                                <option value="Sahel">Sahel</option>
                                <option value="Sud-Ouest">Sud-Ouest</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.municipality')</label>
                            <input type="text" name="commune" class="form-control" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label required">@lang('messages.authorized_person')</label>
                        <input type="text" name="personne_habilitee" class="form-control" required 
                               placeholder="@lang('messages.authorized_person_placeholder')">
                        <div class="help-text">
                            <i class="fas fa-info-circle"></i>
                            Nom complet et fonction de la personne responsable
                        </div>
                    </div>
                </div>

                <!-- Section 2: Informations sur l'Activité -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-tasks"></i>
                        <h3>@lang('messages.activity_information')</h3>
                    </div>

                    <div class="form-group">
                        <label class="form-label required">@lang('messages.activity_title')</label>
                        <input type="text" name="intitule_activite" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label required">@lang('messages.activity_summary')</label>
                        <textarea name="resume_activite" class="form-textarea large" required></textarea>
                        <div class="help-text">
                            <i class="fas fa-info-circle"></i>
                            @lang('messages.activity_summary_help')
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.implementation_period')</label>
                            <input type="text" name="periode_mise_en_oeuvre" class="form-control" required 
                                   placeholder="Ex: Janvier 2025 - Décembre 2025">
                        </div>
                        <div class="form-group">
                            <label class="form-label">@lang('messages.partner_organizations')</label>
                            <input type="text" name="organisations_partenaires" class="form-control" 
                                   placeholder="Ex: ONG XYZ, Association ABC">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.total_activity_cost')</label>
                            <input type="number" name="cout_total" class="form-control" required min="0">
                        </div>
                        <div class="form-group">
                            <label class="form-label required">@lang('messages.amount_requested')</label>
                            <input type="number" name="montant_sollicite" class="form-control" required min="0">
                        </div>
                    </div>
                </div>

                <!-- Section 3: Résultats Attendus -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-chart-line"></i>
                        <h3>@lang('messages.expected_results')</h3>
                    </div>

                    <div class="results-grid">
                        <div class="result-item">
                            <div class="result-number">1</div>
                            <div style="flex: 1;">
                                <label class="form-label required">@lang('messages.expected_result') 1</label>
                                <textarea name="resultat_1" class="form-textarea" required></textarea>
                            </div>
                        </div>

                        <div class="result-item">
                            <div class="result-number">2</div>
                            <div style="flex: 1;">
                                <label class="form-label">@lang('messages.expected_result') 2</label>
                                <textarea name="resultat_2" class="form-textarea"></textarea>
                            </div>
                        </div>

                        <div class="result-item">
                            <div class="result-number">3</div>
                            <div style="flex: 1;">
                                <label class="form-label">@lang('messages.expected_result') 3</label>
                                <textarea name="resultat_3" class="form-textarea"></textarea>
                            </div>
                        </div>

                        <div class="result-item">
                            <div class="result-number">4</div>
                            <div style="flex: 1;">
                                <label class="form-label">@lang('messages.expected_result') 4</label>
                                <textarea name="resultat_4" class="form-textarea"></textarea>
                            </div>
                        </div>

                        <div class="result-item">
                            <div class="result-number">5</div>
                            <div style="flex: 1;">
                                <label class="form-label">@lang('messages.expected_result') 5</label>
                                <textarea name="resultat_5" class="form-textarea"></textarea>
                            </div>
                        </div>

                        <div class="result-item">
                            <div class="result-number">6</div>
                            <div style="flex: 1;">
                                <label class="form-label">@lang('messages.expected_result') 6</label>
                                <textarea name="resultat_6" class="form-textarea"></textarea>
                            </div>
                        </div>
                    </div>
                </div>

                
                <!-- Section 4: Guichets du FIE -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-window-restore"></i>
                        <h3>@lang('messages.fie_window')</h3>
                    </div>

                    <div class="checkbox-group">
                        <div class="checkbox-item">
                            <input type="checkbox" name="guichet[]" value="environnement_cadre_vie" id="guichet1">
                            <label for="guichet1">@lang('messages.environment_window')</label>
                        </div>

                        <div class="checkbox-item">
                            <input type="checkbox" name="guichet[]" value="risques_catastrophes" id="guichet2">
                            <label for="guichet2">@lang('messages.risk_window')</label>
                        </div>

                        <div class="checkbox-item">
                            <input type="checkbox" name="guichet[]" value="gestion_ressources_sols_eaux" id="guichet3">
                            <label for="guichet3">@lang('messages.soil_water_resources')</label>
                        </div>

                        <div class="checkbox-item">
                            <input type="checkbox" name="guichet[]" value="ressources_forestieres_fauniques" id="guichet4">
                            <label for="guichet4">@lang('messages.forest_fauna_resources')</label>
                        </div>

                        <div class="checkbox-item">
                            <input type="checkbox" name="guichet[]" value="pratiques_durables_energie" id="guichet5">
                            <label for="guichet5">@lang('messages.sustainable_practices')</label>
                        </div>
                    </div>

                    <div class="help-text" style="margin-top: 1rem;">
                        <i class="fas fa-info-circle"></i>
                        @lang('messages.select_window_help')
                    </div>
                </div>

                <!-- Section 5: Contribution aux Cibles -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-bullseye"></i>
                        <h3>@lang('messages.contribution_targets')</h3>
                    </div>

                    <div class="help-text" style="margin-bottom: 1.5rem;">
                        <i class="fas fa-info-circle"></i>
                        @lang('messages.contribution_help')
                    </div>

                    <div class="form-group">
                        <label class="form-label required">@lang('messages.target') 1</label>
                        <textarea name="cible_1" class="form-textarea" required 
                                  placeholder="Ex: Reboisement de 50 hectares"></textarea>
                    </div>

                    <div class="form-group">
                        <label class="form-label">@lang('messages.target') 2</label>
                        <textarea name="cible_2" class="form-textarea" 
                                  placeholder="Ex: Formation de 200 agriculteurs"></textarea>
                    </div>

                    <div class="form-group">
                        <label class="form-label">@lang('messages.target') 3</label>
                        <textarea name="cible_3" class="form-textarea" 
                                  placeholder="Ex: Réduction de 30% des émissions de CO2"></textarea>
                    </div>

                    <div class="form-group">
                        <label class="form-label">@lang('messages.target') 4</label>
                        <textarea name="cible_4" class="form-textarea" 
                                  placeholder="Ex: Installation de 100 dispositifs d'économie d'énergie"></textarea>
                    </div>
                </div>

                <!-- Section 6: Visibilité du FIE -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-eye"></i>
                        <h3>@lang('messages.fie_visibility')</h3>
                    </div>

                    <div class="form-group">
                        <label class="form-label required">Comment votre projet contribuera-t-il à la visibilité du FIE ?</label>
                        <textarea name="contribution_visibilite" class="form-textarea large" required 
                                  placeholder="Décrivez les actions de communication, de sensibilisation et de promotion du FIE prévues dans le cadre de votre projet"></textarea>
                        <div class="help-text">
                            <i class="fas fa-info-circle"></i>
                            Mentionnez les actions de communication, les événements publics, les supports de communication, etc.
                        </div>
                    </div>
                </div>

                <!-- Section 7: Pièces Jointes -->
                <div class="form-section">
                    <div class="section-header">
                        <i class="fas fa-paperclip"></i>
                        <h3>@lang('messages.attachments')</h3>
                    </div>

                    <div class="form-group">
                        <label class="form-label required">@lang('messages.project_document')</label>
                        <input type="file" id="fileInput" name="piece_jointes[]" 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>@lang('messages.click_to_upload')</h4>
                            <p>@lang('messages.accepted_formats')</p>
                            <p style="font-size: 0.9rem; color: #666;">@lang('messages.max_file_size')</p>
                        </div>
                        <div class="file-list" id="fileList"></div>
                        <div class="help-text">
                            <i class="fas fa-info-circle"></i>
                            @lang('messages.multiple_files_info')
                        </div>
                    </div>
                </div>
                <!-- Form Actions -->
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="resetForm()">
                        <i class="fas fa-redo"></i>
                        @lang('messages.reset')
                    </button>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-paper-plane"></i>
                        @lang('messages.submit_application')
                    </button>
                </div>
            </form>
        </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 + '% ' + '@lang('messages.complete')';
        }

        // 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();
        }

        

        // 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;
                });
            }
        }


        // 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
