// js/document-dossier-administratif.js
const API_BASE_URL = '/est-concours/model/api/document_dossier_administratif.php';
let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;
let currentDetailId = null;

// Cache for dropdown data
let employees = [];
let categories = [];
let etats = [];
let mimeTypes = [];
let employeesMap = {};

// Load data on page load
document.addEventListener('DOMContentLoaded', function() {
    loadDropdownData();
    loadDocuments();
    loadStats();
    setupSearchForm();
});

function setupSearchForm() {
    document.getElementById('searchForm').addEventListener('submit', function(e) {
        e.preventDefault();
        currentPage = 1;
        loadDocuments();
    });
}

function resetSearch() {
    document.getElementById('searchForm').reset();
    document.getElementById('searchCategory').value = '';
    document.getElementById('searchEtat').value = '';
    document.getElementById('searchIsVerified').value = '';
    currentPage = 1;
    loadDocuments();
}

function loadDropdownData() {
    // Load employees
    /*fetch('/est-concours/model/api/employee.php?action=all')
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                employees = result.data;
                employeesMap = {};
                employees.forEach(emp => {
                    employeesMap[emp.id] = `${emp.nom} ${emp.prenom}`;
                });
                populateEmployeeSelects(employees);
            }
        })
        .catch(error => console.error('Error loading employees:', error));
     */
    // Load categories
    fetch('/est-concours/model/api/category-document-dossier-admin.php?action=all')
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                categories = result.data;
                populateCategorySelects(categories);
            }
        })
        .catch(error => console.error('Error loading categories:', error));

    // Load etats
    fetch('/est-concours/model/api/etat_document_dossier_administratif.php?action=all')
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                etats = result.data;
                populateEtatSelects(etats);
            }
        })
        .catch(error => console.error('Error loading etats:', error));

    // Load mime types
    fetch('/est-concours/model/api/mime-document-dossier-admin.php?action=all')
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                mimeTypes = result.data;
                populateMimeTypeSelects(mimeTypes);
            }
        })
        .catch(error => console.error('Error loading mime types:', error));
}

function populateEmployeeSelects(data) {
    const selects = ['employee_id', 'uploaded_by', 'verified_by'];
    selects.forEach(id => {
        const select = document.getElementById(id);
        if (select) {
            const currentValue = select.value;
            select.innerHTML = '<option value="">Sélectionner un employé</option>';
            data.forEach(emp => {
                const option = document.createElement('option');
                option.value = emp.id;
                option.textContent = `${emp.nom} ${emp.prenom} (${emp.email})`;
                select.appendChild(option);
            });
            if (currentValue) select.value = currentValue;
        }
    });
}

function populateCategorySelects(data) {
    const selects = ['category_id', 'searchCategory'];
    selects.forEach(id => {
        const select = document.getElementById(id);
        if (select) {
            const currentValue = select.value;
            select.innerHTML = id === 'searchCategory' ? '<option value="">Toutes les catégories</option>' : '<option value="">Sélectionner une catégorie</option>';
            data.forEach(cat => {
                const option = document.createElement('option');
                option.value = cat.id;
                option.textContent = cat.libelle;
                select.appendChild(option);
            });
            if (currentValue) select.value = currentValue;
        }
    });
}

function populateEtatSelects(data) {
    const selects = ['etat_document_dossier_administratif_id', 'searchEtat'];
    selects.forEach(id => {
        const select = document.getElementById(id);
        if (select) {
            const currentValue = select.value;
            select.innerHTML = id === 'searchEtat' ? '<option value="">Tous les états</option>' : '<option value="">Sélectionner un état</option>';
            data.forEach(etat => {
                const option = document.createElement('option');
                option.value = etat.id;
                option.textContent = etat.libelle;
                select.appendChild(option);
            });
            if (currentValue) select.value = currentValue;
        }
    });
}

function populateMimeTypeSelects(data) {
    const select = document.getElementById('mime_type_id');
    if (select) {
        const currentValue = select.value;
        select.innerHTML = '<option value="">Sélectionner un type</option>';
        data.forEach(mime => {
            const option = document.createElement('option');
            option.value = mime.id;
            option.textContent = mime.libelle;
            select.appendChild(option);
        });
        if (currentValue) select.value = currentValue;
    }
}

function loadStats() {
    fetch(`${API_BASE_URL}?action=stats`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const stats = result.data;
                document.getElementById('statTotal').textContent = stats.total || 0;
                document.getElementById('statVerified').textContent = stats.verified || 0;
                document.getElementById('statPending').textContent = stats.pending || 0;
            }
        })
        .catch(error => console.error('Error loading stats:', error));

    // Load categories count
    fetch('/est-concours/model/api/category-document-dossier-admin.php?action=stats')
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                document.getElementById('statCategories').textContent = result.data.total || 0;
            }
        })
        .catch(error => console.error('Error loading categories stats:', error));
}

function loadDocuments() {
    showLoading(true);

    const searchData = {
        id: document.getElementById('searchId')?.value || '',
        original_name: document.getElementById('searchOriginalName')?.value || '',
        employee: document.getElementById('searchEmployee')?.value || '',
        category_id: document.getElementById('searchCategory')?.value || '',
        etat_id: document.getElementById('searchEtat')?.value || '',
        is_verified: document.getElementById('searchIsVerified')?.value || '',
        page: currentPage,
        per_page: perPage
    };

    const params = new URLSearchParams(searchData);

    fetch(`${API_BASE_URL}?action=search&${params.toString()}`)
        .then(response => response.json())
        .then(result => {
            showLoading(false);
            if (result.success) {
                renderTable(result.data.data);
                renderPagination(result.data);
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showLoading(false);
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function renderTable(documents) {
    const tbody = document.getElementById('tableBody');

    if (documents.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="8" style="text-align: center; padding: 40px; color: #666;">
                    <p style="font-size: 18px;">📭 Aucun document trouvé</p>
                    <p style="font-size: 14px; margin-top: 5px;">Essayez de modifier vos critères de recherche</p>
                </td>
            </tr>
        `;
        return;
    }

    const badgeColors = {
        'primary': '#007bff',
        'secondary': '#6c757d',
        'success': '#28a745',
        'danger': '#dc3545',
        'warning': '#ffc107',
        'info': '#17a2b8',
        'dark': '#343a40'
    };

    tbody.innerHTML = documents.map(doc => {
        const employeeName = employeesMap[doc.employee_id] || `ID: ${doc.employee_id}`;
        const categoryName = categories.find(c => c.id == doc.category_id)?.libelle || `ID: ${doc.category_id}`;
        const etatName = etats.find(e => e.id == doc.etat_document_dossier_administratif_id)?.libelle || `ID: ${doc.etat_document_dossier_administratif_id}`;
        const verifiedBadge = doc.is_verified == 1
            ? '<span class="badge badge-success">✅ Vérifié</span>'
            : '<span class="badge badge-warning">⏳ En attente</span>';
        const sizeFormatted = formatFileSize(doc.size);

        return `
            <tr>
                <td>${doc.id}</td>
                <td><strong>${escapeHtml(doc.original_name)}</strong></td>
                <td>${escapeHtml(employeeName)}</td>
                <td><span class="badge badge-info">${escapeHtml(categoryName)}</span></td>
                <td>${escapeHtml(etatName)}</td>
                <td>${sizeFormatted}</td>
                <td>${verifiedBadge}</td>
                <td>
                    <button class="btn btn-info btn-sm" onclick="viewDetail(${doc.id})" title="Voir les détails">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-warning btn-sm" onclick="openEditModal(${doc.id})" title="Modifier">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-danger btn-sm" onclick="deleteDocument(${doc.id})" title="Supprimer">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `;
    }).join('');
}

function renderPagination(data) {
    const { total, page, totalPages: pages } = data;
    totalPages = pages;

    const start = (page - 1) * perPage + 1;
    const end = Math.min(page * perPage, total);
    document.getElementById('paginationInfo').textContent =
        `Affichage de ${start} à ${end} sur ${total} documents`;

    const pageNumbers = document.getElementById('pageNumbers');
    let html = '';
    for (let i = 1; i <= pages; i++) {
        html += `<button onclick="goToPage(${i})" ${i === page ? 'class="active"' : ''}>${i}</button>`;
    }
    pageNumbers.innerHTML = html;

    document.getElementById('prevBtn').disabled = page <= 1;
    document.getElementById('nextBtn').disabled = page >= pages;
}

function changePage(direction) {
    if (direction === 'prev' && currentPage > 1) {
        currentPage--;
    } else if (direction === 'next' && currentPage < totalPages) {
        currentPage++;
    }
    loadDocuments();
}

function goToPage(page) {
    currentPage = page;
    loadDocuments();
}

function openCreateModal() {
    editMode = false;
    var modalTitle = document.getElementById('modalTitle');
    var employeeForm = document.getElementById('employeeForm');
    var employeeId = document.getElementById('employeeId');
    var modalOverlay = document.querySelector('.modal-overlay');

    // Afficher le message pour nouveau employé
    var passwordMessage = document.getElementById('passwordMessage');
    var passwordRequired = document.getElementById('passwordRequired');
    var confirmRequired = document.getElementById('confirmRequired');
    var passwordEditHint = document.getElementById('passwordEditHint');

    if (passwordMessage) passwordMessage.textContent = 'Pour un nouvel employé, veuillez définir un mot de passe.';
    if (passwordRequired) passwordRequired.style.display = 'inline';
    if (confirmRequired) confirmRequired.style.display = 'inline';
    if (passwordEditHint) passwordEditHint.style.display = 'none';

    if (modalTitle) modalTitle.textContent = 'Nouvel Employé';
    if (employeeForm) employeeForm.reset();
    if (employeeId) employeeId.value = '';
    if (modalOverlay) modalOverlay.classList.add('active');

    // Reset password fields
    var newPassword = document.getElementById('new_password');
    var confirmPassword = document.getElementById('confirm_password');
    if (newPassword) {
        newPassword.value = '';
        newPassword.required = true;
    }
    if (confirmPassword) {
        confirmPassword.value = '';
        confirmPassword.required = true;
    }

    // Reset password strength
    var strengthBar = document.getElementById('passwordStrengthBar');
    var strengthText = document.getElementById('passwordStrengthText');
    if (strengthBar) {
        strengthBar.className = 'bar';
        strengthBar.style.width = '0%';
    }
    if (strengthText) {
        strengthText.textContent = 'Entrez un mot de passe';
        strengthText.style.color = '#888';
    }

    // Set default tab
    document.querySelectorAll('.tab-btn').forEach(function(b) { b.classList.remove('active'); });
    document.querySelectorAll('.tab-content').forEach(function(c) { c.classList.remove('active'); });
    var firstTab = document.querySelector('.tab-btn[data-tab="personal"]');
    if (firstTab) firstTab.classList.add('active');
    var firstContent = document.getElementById('tab-personal');
    if (firstContent) firstContent.classList.add('active');
}
function openEditModal(id) {
    editMode = true;
    var modalTitle = document.getElementById('modalTitle');
    var employeeId = document.getElementById('employeeId');
    var modalOverlay = document.querySelector('.modal-overlay');

    // Afficher le message pour modification
    var passwordMessage = document.getElementById('passwordMessage');
    var passwordRequired = document.getElementById('passwordRequired');
    var confirmRequired = document.getElementById('confirmRequired');
    var passwordEditHint = document.getElementById('passwordEditHint');

    if (passwordMessage) passwordMessage.textContent = 'Pour modifier le mot de passe, remplissez les champs ci-dessous.';
    if (passwordRequired) passwordRequired.style.display = 'none';
    if (confirmRequired) confirmRequired.style.display = 'none';
    if (passwordEditHint) passwordEditHint.style.display = 'inline';

    if (modalTitle) modalTitle.textContent = 'Modifier Employé';
    if (employeeId) employeeId.value = id;
    if (modalOverlay) modalOverlay.classList.add('active');

    // Reset password fields
    var newPassword = document.getElementById('new_password');
    var confirmPassword = document.getElementById('confirm_password');
    if (newPassword) {
        newPassword.value = '';
        newPassword.required = false;
        newPassword.placeholder = 'Laissez vide pour garder le mot de passe actuel';
    }
    if (confirmPassword) {
        confirmPassword.value = '';
        confirmPassword.required = false;
        confirmPassword.placeholder = 'Confirmer le nouveau mot de passe';
    }

    // Reset password strength
    var strengthBar = document.getElementById('passwordStrengthBar');
    var strengthText = document.getElementById('passwordStrengthText');
    if (strengthBar) {
        strengthBar.className = 'bar';
        strengthBar.style.width = '0%';
    }
    if (strengthText) {
        strengthText.textContent = 'Entrez un mot de passe (optionnel)';
        strengthText.style.color = '#888';
    }

    // Set default tab
    document.querySelectorAll('.tab-btn').forEach(function(b) { b.classList.remove('active'); });
    document.querySelectorAll('.tab-content').forEach(function(c) { c.classList.remove('active'); });
    var firstTab = document.querySelector('.tab-btn[data-tab="personal"]');
    if (firstTab) firstTab.classList.add('active');
    var firstContent = document.getElementById('tab-personal');
    if (firstContent) firstContent.classList.add('active');

    // Show loading state
    document.querySelectorAll('#employeeForm input, #employeeForm select, #employeeForm textarea').forEach(function(el) {
        if (el.id !== 'employeeId' && el.id !== 'confirm_password' && el.id !== 'new_password') {
            el.disabled = true;
        }
    });

    fetch(API_BASE_URL + '?action=get&id=' + id)
        .then(function(response) { return response.json(); })
        .then(function(result) {
            document.querySelectorAll('#employeeForm input, #employeeForm select, #employeeForm textarea').forEach(function(el) {
                if (el.id !== 'employeeId' && el.id !== 'confirm_password' && el.id !== 'new_password') {
                    el.disabled = false;
                }
            });

            if (result.success) {
                var emp = result.data;
                // Personal info
                setElementValue('nom', emp.nom);
                setElementValue('nom_arab', emp.nom_arab);
                setElementValue('prenom', emp.prenom);
                setElementValue('prenom_arab', emp.prenom_arab);
                setElementValue('cin', emp.cin);
                setElementValue('email', emp.email);
                setElementValue('phone', emp.phone);
                setElementValue('genre', emp.genre);
                setElementValue('lieu_naissance', emp.lieu_naissance);
                setElementValue('date_naissance', emp.date_naissance);

                // Professional info
                setElementValue('code', emp.code);
                setElementValue('login', emp.login);
                setElementValue('specialite', emp.specialite);
                setElementValue('diplome', emp.diplome);
                setElementValue('etablissement_diplome', emp.etablissement_diplome);
                setElementValue('fonctionnaire', emp.fonctionnaire || '0');
                setElementValue('nombre_annee_fonctionnaire', emp.nombre_annee_fonctionnaire);
                setElementValue('date_recrutement', emp.date_recrutement);
                setElementValue('date_affectation_enseignement', emp.date_affectation_enseignement);
                setElementValue('status', emp.status || 'active');
                setElementValue('grade_id', emp.grade_id);
                setElementValue('type_grade_id', emp.type_grade_id);
                setElementValue('echellon_id', emp.echellon_id);
            } else {
                showToast('Erreur: ' + result.message, 'error');
                closeModal();
            }
        })
        .catch(function(error) {
            document.querySelectorAll('#employeeForm input, #employeeForm select, #employeeForm textarea').forEach(function(el) {
                if (el.id !== 'employeeId' && el.id !== 'confirm_password' && el.id !== 'new_password') {
                    el.disabled = false;
                }
            });
            showToast('Erreur de connexion au serveur', 'error');
            closeModal();
            console.error('Error:', error);
        });
}

function disableFormFields(disabled) {
    const fields = document.querySelectorAll('#documentForm input, #documentForm select, #documentForm textarea');
    fields.forEach(field => {
        field.disabled = disabled;
    });
}

function viewDetail(id) {
    currentDetailId = id;

    document.getElementById('detailModal').classList.add('active');
    document.getElementById('detailContent').innerHTML = `
        <div class="loading active">
            <div class="spinner"></div>
            <p style="margin-top: 10px;">Chargement des détails...</p>
        </div>
    `;

    document.getElementById('editFromDetailBtn').style.display = 'none';

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                renderDetail(result.data);
            } else {
                document.getElementById('detailContent').innerHTML = `
                    <div class="error-state">
                        <i class="fas fa-exclamation-circle"></i>
                        <p>Erreur: ${result.message}</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('detailContent').innerHTML = `
                <div class="error-state">
                    <i class="fas fa-exclamation-circle"></i>
                    <p>Erreur de connexion au serveur</p>
                </div>
            `;
            console.error('Error:', error);
        });
}

function renderDetail(doc) {
    const employeeName = employeesMap[doc.employee_id] || `ID: ${doc.employee_id}`;
    const categoryName = categories.find(c => c.id == doc.category_id)?.libelle || `ID: ${doc.category_id}`;
    const etatName = etats.find(e => e.id == doc.etat_document_dossier_administratif_id)?.libelle || `ID: ${doc.etat_document_dossier_administratif_id}`;
    const mimeName = mimeTypes.find(m => m.id == doc.mime_type_id)?.libelle || `ID: ${doc.mime_type_id}`;
    const uploadedByName = employeesMap[doc.uploaded_by] || `ID: ${doc.uploaded_by}`;
    const verifiedByName = doc.verified_by ? (employeesMap[doc.verified_by] || `ID: ${doc.verified_by}`) : 'Non vérifié';

    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <div class="detail-header">
                <div class="detail-avatar" style="background: #17a2b833;">
                    <i class="fas fa-file" style="color: #17a2b8;"></i>
                </div>
                <div class="detail-title">
                    <h2>${escapeHtml(doc.original_name)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">
                            <i class="fas fa-tag"></i> ID: ${doc.id}
                        </span>
                        <span class="badge badge-${doc.is_verified == 1 ? 'success' : 'warning'}">
                            ${doc.is_verified == 1 ? '✅ Vérifié' : '⏳ En attente'}
                        </span>
                        <span class="meta-text">
                            <i class="fas fa-calendar-alt"></i> 
                            Uploadé le ${formatDate(doc.uploaded_at)}
                        </span>
                    </div>
                </div>
            </div>

            <h3><i class="fas fa-info-circle"></i> Informations du Document</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label"><i class="fas fa-hashtag"></i> ID</span>
                    <span class="value">${doc.id}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-user"></i> Employé</span>
                    <span class="value">${escapeHtml(employeeName)}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-folder"></i> Catégorie</span>
                    <span class="value"><span class="badge badge-info">${escapeHtml(categoryName)}</span></span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-file-alt"></i> État</span>
                    <span class="value">${escapeHtml(etatName)}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-file"></i> Type MIME</span>
                    <span class="value">${escapeHtml(mimeName)}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-weight-hanging"></i> Taille</span>
                    <span class="value">${formatFileSize(doc.size)}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-user-check"></i> Uploadé par</span>
                    <span class="value">${escapeHtml(uploadedByName)}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-user-check"></i> Vérifié par</span>
                    <span class="value">${escapeHtml(verifiedByName)}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-calendar-alt"></i> Date d'expiration</span>
                    <span class="value">${doc.expiry_date ? formatDate(doc.expiry_date) : 'Aucune'}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-calendar"></i> Année universitaire</span>
                    <span class="value">${doc.annee_univ || 'Non spécifiée'}</span>
                </div>
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-file-alt"></i> Nom stocké</span>
                    <span class="value"><code>${escapeHtml(doc.stored_name)}</code></span>
                </div>
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-sticky-note"></i> Note</span>
                    <span class="value ${!doc.note ? 'empty' : ''}">
                        ${doc.note ? escapeHtml(doc.note) : 'Aucune note'}
                    </span>
                </div>
            </div>

            <div class="detail-metadata">
                <h4><i class="fas fa-clock"></i> Métadonnées</h4>
                <div class="metadata-grid">
                    <div class="meta-item">
                        <span class="meta-label">Date d'upload:</span>
                        <span class="meta-value">${formatDate(doc.uploaded_at)}</span>
                    </div>
                    ${doc.verified_at ? `
                    <div class="meta-item">
                        <span class="meta-label">Date de vérification:</span>
                        <span class="meta-value">${formatDate(doc.verified_at)}</span>
                    </div>
                    ` : ''}
                </div>
            </div>
        </div>
    `;

    document.getElementById('editFromDetailBtn').style.display = 'inline-flex';
}

function editFromDetail() {
    if (currentDetailId) {
        closeDetailModal();
        setTimeout(() => {
            openEditModal(currentDetailId);
        }, 300);
    }
}

function closeDetailModal() {
    document.getElementById('detailModal').classList.remove('active');
    currentDetailId = null;
}

function saveDocument() {
    // Validation
    const employee_id = document.getElementById('employee_id').value;
    const category_id = document.getElementById('category_id').value;
    const mime_type_id = document.getElementById('mime_type_id').value;
    const etat_id = document.getElementById('etat_document_dossier_administratif_id').value;
    const original_name = document.getElementById('original_name').value.trim();
    const stored_name = document.getElementById('stored_name').value.trim();
    const size = document.getElementById('size').value;
    const uploaded_by = document.getElementById('uploaded_by').value;

    if (!employee_id) {
        showToast('Veuillez sélectionner un employé', 'warning');
        document.getElementById('employee_id').focus();
        return;
    }

    if (!category_id) {
        showToast('Veuillez sélectionner une catégorie', 'warning');
        document.getElementById('category_id').focus();
        return;
    }

    if (!mime_type_id) {
        showToast('Veuillez sélectionner un type MIME', 'warning');
        document.getElementById('mime_type_id').focus();
        return;
    }

    if (!etat_id) {
        showToast('Veuillez sélectionner un état', 'warning');
        document.getElementById('etat_document_dossier_administratif_id').focus();
        return;
    }

    if (!original_name) {
        showToast('Veuillez saisir le nom original du document', 'warning');
        document.getElementById('original_name').focus();
        return;
    }

    if (!stored_name) {
        showToast('Veuillez saisir le nom de stockage du document', 'warning');
        document.getElementById('stored_name').focus();
        return;
    }

    if (!size || size < 0) {
        showToast('Veuillez saisir une taille valide', 'warning');
        document.getElementById('size').focus();
        return;
    }

    if (!uploaded_by) {
        showToast('Veuillez sélectionner la personne qui upload le document', 'warning');
        document.getElementById('uploaded_by').focus();
        return;
    }

    const id = document.getElementById('documentId').value;
    const data = {
        employee_id: employee_id,
        category_id: category_id,
        mime_type_id: mime_type_id,
        etat_document_dossier_administratif_id: etat_id,
        original_name: original_name,
        stored_name: stored_name,
        size: parseInt(size),
        expiry_date: document.getElementById('expiry_date').value || null,
        annee_univ: document.getElementById('annee_univ').value || null,
        uploaded_by: uploaded_by,
        is_verified: document.getElementById('is_verified').value || 0,
        verified_by: document.getElementById('verified_by').value || null,
        note: document.getElementById('note').value.trim() || null
    };

    const url = id ? `${API_BASE_URL}?action=update&id=${id}` : API_BASE_URL;
    const method = id ? 'PUT' : 'POST';

    const saveBtn = document.querySelector('.modal-content .btn-primary');
    const originalText = saveBtn.innerHTML;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Enregistrement...';
    saveBtn.disabled = true;

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(result => {
            saveBtn.innerHTML = originalText;
            saveBtn.disabled = false;

            if (result.success) {
                showToast(result.message, 'success');
                closeModal();
                loadDocuments();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            saveBtn.innerHTML = originalText;
            saveBtn.disabled = false;
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function deleteDocument(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer ce document ?\n\nCette action est irréversible.')) return;

    const btn = document.querySelector(`button[onclick="deleteDocument(${id})"]`);
    if (btn) {
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;
    }

    fetch(`${API_BASE_URL}?action=delete&id=${id}`, {
        method: 'DELETE'
    })
        .then(response => response.json())
        .then(result => {
            if (btn) {
                btn.innerHTML = '<i class="fas fa-trash"></i>';
                btn.disabled = false;
            }

            if (result.success) {
                showToast(result.message, 'success');
                loadDocuments();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            if (btn) {
                btn.innerHTML = '<i class="fas fa-trash"></i>';
                btn.disabled = false;
            }
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function exportDocuments() {
    window.location.href = `${API_BASE_URL}?action=export`;
}

function closeModal() {
    document.querySelector('.modal-overlay').classList.remove('active');
    disableFormFields(false);
}

function showLoading(show) {
    const loading = document.querySelector('.loading');
    if (loading) {
        if (show) {
            loading.classList.add('active');
        } else {
            loading.classList.remove('active');
        }
    }
}

function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        <span class="toast-icon">${getToastIcon(type)}</span>
        <span class="toast-message">${message}</span>
        <button class="toast-close" onclick="this.parentElement.remove()">&times;</button>
    `;
    container.appendChild(toast);

    setTimeout(() => {
        if (toast.parentElement) {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            toast.style.transition = 'all 0.3s ease';
            setTimeout(() => {
                if (toast.parentElement) {
                    toast.remove();
                }
            }, 300);
        }
    }, 4000);
}

function getToastIcon(type) {
    const icons = {
        success: '✅',
        error: '❌',
        warning: '⚠️',
        info: 'ℹ️'
    };
    return icons[type] || 'ℹ️';
}

function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function formatFileSize(bytes) {
    if (!bytes) return '0 B';
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i];
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Close modal on overlay click
document.querySelectorAll('.modal-overlay').forEach(modal => {
    modal.addEventListener('click', function(e) {
        if (e.target === this) {
            if (this.id === 'detailModal') {
                closeDetailModal();
            } else {
                closeModal();
            }
        }
    });
});

// Close modal on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        if (document.getElementById('detailModal').classList.contains('active')) {
            closeDetailModal();
        } else if (document.querySelector('.modal-overlay.active')) {
            closeModal();
        }
    }
});