@extends('layouts.dashboard.app')

@section('style')
<link rel="stylesheet" href="{{ asset('css/imageuploadify.css') }}">
<style>
    .upload-container {
        background: #fff;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.08);
        padding: 25px;
        margin-top: 20px;
    }

    .upload-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #eee;
    }

    .upload-header h4 {
        margin: 0;
        color: #333;
        font-weight: 600;
    }

    .upload-zone {
        border: 2px dashed #ccc;
        border-radius: 10px;
        padding: 40px 20px;
        text-align: center;
        background: #f8f9fa;
        transition: all 0.3s ease;
        cursor: pointer;
    }

    .upload-zone:hover,
    .upload-zone.dragover {
        border-color: #0d6efd;
        background: #e8f4ff;
    }

    .upload-zone i {
        font-size: 48px;
        color: #6c757d;
        margin-bottom: 15px;
    }

    .upload-zone p {
        color: #6c757d;
        margin-bottom: 5px;
    }

    .upload-zone .supported-formats {
        font-size: 12px;
        color: #adb5bd;
    }

    .file-preview-container {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        margin-top: 20px;
    }

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

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

    .file-preview-item .pdf-icon {
        width: 100%;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f8f9fa;
    }

    .file-preview-item .pdf-icon i {
        font-size: 40px;
        color: #dc3545;
    }

    .file-preview-item .file-name {
        padding: 8px;
        font-size: 11px;
        color: #495057;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        border-top: 1px solid #eee;
    }

    .file-preview-item .remove-file {
        position: absolute;
        top: 5px;
        right: 5px;
        width: 22px;
        height: 22px;
        background: #dc3545;
        color: #fff;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        font-size: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.2s;
    }

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

    .btn-upload {
        padding: 12px 30px;
        font-weight: 500;
    }

    .upload-progress {
        display: none;
        margin-top: 15px;
    }

    .upload-progress.active {
        display: block;
    }

    .alert-info-custom {
        background: #e7f3ff;
        border: 1px solid #b6d4fe;
        border-radius: 8px;
        padding: 12px 15px;
        margin-bottom: 20px;
    }

    .alert-info-custom i {
        color: #0d6efd;
        margin-right: 8px;
    }
</style>
@endsection

@section('content')
<div class="row">
    <div class="page-title-box">
        <div class="page-title-left">
            <a href="{{ route('Dossier.show', $dossier->id) }}" class="btn btn-outline-dark">
                <i class="uil uil-arrow-left me-1"></i> Retour au Dossier
            </a>
        </div>
    </div>
</div>

<div class="upload-container">
    <div class="upload-header">
        <h4><i class="uil uil-cloud-upload me-2"></i> Télécharger des Documents</h4>
        <span class="badge bg-info">{{ $dossier->ref }}</span>
    </div>

    <div class="alert-info-custom">
        <i class="uil uil-info-circle"></i>
        <strong>Formats acceptés:</strong> JPG, JPEG, PNG, GIF, PDF (max 10MB par fichier)
    </div>

    <form action="{{ route('Document.store') }}" id="uploadForm" method="post" enctype="multipart/form-data">
        @csrf
        <input type="hidden" name="dossier" value="{{ $id }}">
        <input type="hidden" name="pdfs" id="pdfData" value="">

        <div class="row">
            <div class="col-md-4 mb-3">
                <label for="type" class="form-label fw-bold">Type de Document <span class="text-danger">*</span></label>
                <select name="type" id="type" class="form-select @error('type') is-invalid @enderror" required>
                    <option value="">-- Sélectionner --</option>
                    @foreach ($types as $type)
                        <option value="{{ $type->id }}">{{ $type->type }}</option>
                    @endforeach
                </select>
                @error('type')
                    <span class="invalid-feedback"><strong>{{ $message }}</strong></span>
                @enderror
            </div>
        </div>

        <div class="upload-zone" id="uploadZone">
            <i class="uil uil-cloud-upload"></i>
            <p class="mb-1"><strong>Glissez vos fichiers ici</strong></p>
            <p class="mb-2">ou cliquez pour parcourir</p>
            <span class="supported-formats">JPG, JPEG, PNG, GIF, PDF</span>
            <input type="file" name="files[]" id="fileInput" class="d-none" accept="image/*,.pdf" multiple>
        </div>

        <div class="file-preview-container" id="previewContainer"></div>

        @if ($errors->any())
            <div class="alert alert-danger mt-3">
                <ul class="mb-0">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <div class="upload-progress" id="uploadProgress">
            <div class="progress">
                <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
            </div>
            <p class="text-center mt-2 text-muted">Traitement en cours...</p>
        </div>

        <div class="mt-4 d-flex gap-2">
            <button type="submit" id="submitBtn" class="btn btn-primary btn-upload" disabled>
                <i class="uil uil-upload me-1"></i> Télécharger
            </button>
            <button type="button" id="clearBtn" class="btn btn-outline-secondary" style="display: none;">
                <i class="uil uil-trash me-1"></i> Tout effacer
            </button>
        </div>
    </form>
</div>
@endsection

@section('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.228/pdf.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const uploadZone = document.getElementById('uploadZone');
    const fileInput = document.getElementById('fileInput');
    const previewContainer = document.getElementById('previewContainer');
    const submitBtn = document.getElementById('submitBtn');
    const clearBtn = document.getElementById('clearBtn');
    const uploadForm = document.getElementById('uploadForm');
    const pdfDataInput = document.getElementById('pdfData');
    
    let selectedFiles = [];
    let pdfImages = [];

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

    // Drag and drop
    uploadZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadZone.classList.add('dragover');
    });

    uploadZone.addEventListener('dragleave', () => {
        uploadZone.classList.remove('dragover');
    });

    uploadZone.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadZone.classList.remove('dragover');
        handleFiles(e.dataTransfer.files);
    });

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

    // Handle files
    function handleFiles(files) {
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'application/pdf'];
        
        for (let file of files) {
            // Check file type
            if (!allowedTypes.includes(file.type) && !file.name.toLowerCase().endsWith('.pdf')) {
                alert('Type de fichier non autorisé: ' + file.name);
                continue;
            }
            
            // Check file size (10MB max)
            if (file.size > 10 * 1024 * 1024) {
                alert('Fichier trop volumineux (max 10MB): ' + file.name);
                continue;
            }

            selectedFiles.push(file);
            
            if (file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf')) {
                processPDF(file, selectedFiles.length - 1);
            } else {
                createImagePreview(file, selectedFiles.length - 1);
            }
        }
        
        updateUI();
    }

    // Create image preview
    function createImagePreview(file, index) {
        const reader = new FileReader();
        reader.onload = (e) => {
            const preview = createPreviewElement(e.target.result, file.name, index, 'image');
            previewContainer.appendChild(preview);
        };
        reader.readAsDataURL(file);
    }

    // Process PDF
    async function processPDF(file, index) {
        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.height = viewport.height;
                    canvas.width = viewport.width;
                    
                    await page.render({ canvasContext: ctx, viewport }).promise;
                    const dataUrl = canvas.toDataURL('image/png');
                    pdfImages.push(dataUrl);
                }
                
                // Create preview for PDF
                const preview = createPreviewElement(null, file.name, index, 'pdf');
                previewContainer.appendChild(preview);
                
            } catch (err) {
                console.error('Erreur PDF:', err);
                alert('Erreur lors du traitement du PDF: ' + file.name);
            }
        };
        reader.readAsDataURL(file);
    }

    // Create preview element
    function createPreviewElement(src, name, index, type) {
        const div = document.createElement('div');
        div.className = 'file-preview-item';
        div.dataset.index = index;
        
        if (type === 'pdf') {
            div.innerHTML = `
                <div class="pdf-icon">
                    <i class="uil uil-file-alt"></i>
                </div>
                <div class="file-name" title="${name}">${name}</div>
                <button type="button" class="remove-file" data-index="${index}">&times;</button>
            `;
        } else {
            div.innerHTML = `
                <img src="${src}" alt="${name}">
                <div class="file-name" title="${name}">${name}</div>
                <button type="button" class="remove-file" data-index="${index}">&times;</button>
            `;
        }
        
        // Remove button click
        div.querySelector('.remove-file').addEventListener('click', (e) => {
            e.stopPropagation();
            removeFile(index);
        });
        
        return div;
    }

    // Remove file
    function removeFile(index) {
        selectedFiles[index] = null;
        document.querySelector(`.file-preview-item[data-index="${index}"]`)?.remove();
        updateUI();
    }

    // Update UI
    function updateUI() {
        const hasFiles = selectedFiles.some(f => f !== null);
        submitBtn.disabled = !hasFiles;
        clearBtn.style.display = hasFiles ? 'block' : 'none';
    }

    // Clear all
    clearBtn.addEventListener('click', () => {
        selectedFiles = [];
        pdfImages = [];
        previewContainer.innerHTML = '';
        fileInput.value = '';
        updateUI();
    });

    // Form submit
    uploadForm.addEventListener('submit', (e) => {
        e.preventDefault();
        
        // Set PDF data
        if (pdfImages.length > 0) {
            pdfDataInput.value = pdfImages.join(',');
        }
        
        // Create new FormData with only valid files
        const formData = new FormData(uploadForm);
        formData.delete('files[]');
        
        selectedFiles.forEach((file, i) => {
            if (file) {
                formData.append('files[]', file);
            }
        });
        
        // Show progress
        document.getElementById('uploadProgress').classList.add('active');
        submitBtn.disabled = true;
        
        // Submit form
        uploadForm.submit();
    });
});
</script>
@endsection