{{-- Document Upload Modal --}}
{{-- Usage: @include('document.modal', ['types' => $types, 'id' => $dossier->id]) --}}

<div id="upload-modal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-light">
                <h5 class="modal-title">
                    <i class="uil uil-cloud-upload me-2"></i> Télécharger des Documents
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            
            <div class="modal-body">
                <form id="modalUploadForm" method="post" action="{{ route('Document.store') }}" enctype="multipart/form-data">
                    @csrf
                    <input type="hidden" name="dossier" value="{{ $id }}">
                    <input type="hidden" name="pdfs" id="pdfDataModal" value="">

                    {{-- Type Selection --}}
                    <div class="mb-4">
                        <label for="modal-type" class="form-label fw-bold">
                            Type de Document <span class="text-danger">*</span>
                        </label>
                        <select name="type" id="modal-type" class="form-select form-select-lg" required>
                            <option value="">-- Sélectionner le type --</option>
                            @foreach ($types as $type)
                                <option value="{{ $type->id }}">{{ $type->type }}</option>
                            @endforeach
                        </select>
                    </div>

                    {{-- Upload Zone --}}
                    <div class="upload-drop-zone" id="modalUploadZone">
                        <i class="uil uil-cloud-upload"></i>
                        <p class="mb-1"><strong>Glissez vos fichiers ici</strong></p>
                        <p class="text-muted mb-2">ou cliquez pour parcourir</p>
                        <span class="badge bg-secondary">JPG, PNG, GIF, PDF</span>
                        <input type="file" name="files[]" id="modalFileInput" class="d-none" accept="image/*,.pdf" multiple>
                    </div>

                    {{-- Preview Area --}}
                    <div class="preview-area" id="modalPreviewArea"></div>

                    {{-- File Count --}}
                    <div class="file-count mt-3" id="fileCount" style="display: none;">
                        <span class="badge bg-info"><span id="fileCountNum">0</span> fichier(s) sélectionné(s)</span>
                    </div>

                    {{-- Error Display --}}
                    <div class="alert alert-danger mt-3" id="modalErrors" style="display: none;"></div>
                </form>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                    <i class="uil uil-times me-1"></i> Annuler
                </button>
                <button type="button" class="btn btn-primary" id="modalSubmitBtn" disabled>
                    <i class="uil uil-upload me-1"></i> Télécharger
                </button>
            </div>
        </div>
    </div>
</div>

<style>
    .upload-drop-zone {
        border: 2px dashed #ced4da;
        border-radius: 12px;
        padding: 40px 20px;
        text-align: center;
        background: #f8f9fa;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .upload-drop-zone:hover,
    .upload-drop-zone.drag-over {
        border-color: #0d6efd;
        background: #e7f1ff;
    }

    .upload-drop-zone i {
        font-size: 50px;
        color: #6c757d;
        display: block;
        margin-bottom: 10px;
    }

    .preview-area {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 15px;
        max-height: 250px;
        overflow-y: auto;
        padding: 5px;
    }

    .preview-item {
        position: relative;
        width: 100px;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        overflow: hidden;
        background: #fff;
    }

    .preview-item img {
        width: 100%;
        height: 80px;
        object-fit: cover;
    }

    .preview-item .pdf-thumb {
        width: 100%;
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: linear-gradient(135deg, #ff6b6b, #c92a2a);
        color: #fff;
    }

    .preview-item .pdf-thumb i {
        font-size: 30px;
        color: #fff;
    }

    .preview-item .file-info {
        padding: 5px;
        font-size: 10px;
        color: #666;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        text-align: center;
        background: #f8f9fa;
    }

    .preview-item .remove-btn {
        position: absolute;
        top: 3px;
        right: 3px;
        width: 20px;
        height: 20px;
        background: rgba(220, 53, 69, 0.9);
        color: #fff;
        border: none;
        border-radius: 50%;
        font-size: 14px;
        line-height: 1;
        cursor: pointer;
        opacity: 0;
        transition: opacity 0.2s;
    }

    .preview-item:hover .remove-btn {
        opacity: 1;
    }

    .modal-footer .btn {
        min-width: 120px;
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const uploadZone = document.getElementById('modalUploadZone');
    const fileInput = document.getElementById('modalFileInput');
    const previewArea = document.getElementById('modalPreviewArea');
    const submitBtn = document.getElementById('modalSubmitBtn');
    const fileCount = document.getElementById('fileCount');
    const fileCountNum = document.getElementById('fileCountNum');
    const uploadForm = document.getElementById('modalUploadForm');
    const pdfDataInput = document.getElementById('pdfDataModal');
    const errorBox = document.getElementById('modalErrors');

    let files = [];
    let pdfImages = [];

    // Click to select files
    uploadZone.addEventListener('click', () => fileInput.click());

    // Drag & Drop
    uploadZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadZone.classList.add('drag-over');
    });

    uploadZone.addEventListener('dragleave', () => {
        uploadZone.classList.remove('drag-over');
    });

    uploadZone.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadZone.classList.remove('drag-over');
        processFiles(e.dataTransfer.files);
    });

    // File input change
    fileInput.addEventListener('change', () => {
        processFiles(fileInput.files);
    });

    // Process files
    function processFiles(newFiles) {
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
        const allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
        
        errorBox.style.display = 'none';
        
        for (let file of newFiles) {
            const ext = file.name.split('.').pop().toLowerCase();
            
            if (!allowedTypes.includes(file.type) && !allowedExt.includes(ext)) {
                showError('Type non autorisé: ' + file.name);
                continue;
            }
            
            if (file.size > 10 * 1024 * 1024) {
                showError('Fichier trop grand (max 10MB): ' + file.name);
                continue;
            }

            files.push(file);
            
            if (file.type === 'application/pdf' || ext === 'pdf') {
                createPdfPreview(file, files.length - 1);
            } else {
                createImagePreview(file, files.length - 1);
            }
        }
        
        updateUI();
    }

    // Create image preview
    function createImagePreview(file, index) {
        const reader = new FileReader();
        reader.onload = (e) => {
            const div = document.createElement('div');
            div.className = 'preview-item';
            div.dataset.index = index;
            div.innerHTML = `
                <img src="${e.target.result}" alt="${file.name}">
                <div class="file-info">${file.name}</div>
                <button type="button" class="remove-btn" onclick="removeModalFile(${index})">&times;</button>
            `;
            previewArea.appendChild(div);
        };
        reader.readAsDataURL(file);
    }

    // Create PDF preview
    function createPdfPreview(file, index) {
        const div = document.createElement('div');
        div.className = 'preview-item';
        div.dataset.index = index;
        div.innerHTML = `
            <div class="pdf-thumb">
                <i class="uil uil-file-alt"></i>
            </div>
            <div class="file-info">${file.name}</div>
            <button type="button" class="remove-btn" onclick="removeModalFile(${index})">&times;</button>
        `;
        previewArea.appendChild(div);

        // Convert PDF to images for backend if PDF.js is available
        if (typeof pdfjsLib !== 'undefined') {
            convertPdfToImages(file);
        }
    }

    // Convert PDF pages to images
    async function convertPdfToImages(file) {
        const reader = new FileReader();
        reader.onload = async (e) => {
            try {
                const data = atob(e.target.result.replace(/.*base64,/, ''));
                const pdf = await pdfjsLib.getDocument({ data }).promise;
                
                for (let i = 1; i <= pdf.numPages; i++) {
                    const page = await pdf.getPage(i);
                    const viewport = page.getViewport({ scale: 2 });
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    canvas.width = viewport.width;
                    canvas.height = viewport.height;
                    
                    await page.render({ canvasContext: ctx, viewport }).promise;
                    pdfImages.push(canvas.toDataURL('image/png'));
                }
            } catch (err) {
                console.error('PDF conversion error:', err);
            }
        };
        reader.readAsDataURL(file);
    }

    // Remove file (global function for onclick)
    window.removeModalFile = function(index) {
        files[index] = null;
        document.querySelector(`.preview-item[data-index="${index}"]`)?.remove();
        updateUI();
    };

    // Update UI
    function updateUI() {
        const validFiles = files.filter(f => f !== null);
        const count = validFiles.length;
        
        fileCountNum.textContent = count;
        fileCount.style.display = count > 0 ? 'block' : 'none';
        submitBtn.disabled = count === 0;
    }

    // Show error
    function showError(msg) {
        errorBox.style.display = 'block';
        errorBox.innerHTML = '<i class="uil uil-exclamation-triangle me-2"></i>' + msg;
    }

    // Submit form
    submitBtn.addEventListener('click', () => {
        const typeSelect = document.getElementById('modal-type');
        if (!typeSelect.value) {
            showError('Veuillez sélectionner un type de document');
            return;
        }

        // Set PDF data
        if (pdfImages.length > 0) {
            pdfDataInput.value = pdfImages.join(',');
        }

        // Create FormData
        const formData = new FormData(uploadForm);
        formData.delete('files[]');
        
        files.forEach(file => {
            if (file) formData.append('files[]', file);
        });

        // Submit
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> Envoi...';
        
        uploadForm.submit();
    });

    // Reset on modal close
    const modal = document.getElementById('upload-modal');
    if (modal) {
        modal.addEventListener('hidden.bs.modal', function() {
            files = [];
            pdfImages = [];
            previewArea.innerHTML = '';
            fileInput.value = '';
            errorBox.style.display = 'none';
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="uil uil-upload me-1"></i> Télécharger';
            updateUI();
        });
    }
});
</script>