// js/echellon.js
const API_BASE_URL = '/est-concours/model/api/echellon.php';
const API_ECHELLE_URL = '/est-concours/model/api/echelle.php';
const API_GRADE_URL = '/est-concours/model/api/grade.php';
const API_TYPE_GRADE_URL = '/est-concours/model/api/type_grade.php';
let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;
let currentDetailId = null;
let echellesMap = {};
let allTypeGrades = [];
let allGrades = [];

// Load echellons on page load
document.addEventListener('DOMContentLoaded', function() {
    loadEchellesForSelects();
    loadTypeGradesAndGradesForSearch();
    loadEchellons();
    loadStats();
    setupSearchForm();
});

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

function resetSearch() {
    document.getElementById('searchForm').reset();
    document.getElementById('searchTypeGrade').value = '';
    document.getElementById('searchGrade').innerHTML = '<option value="">Tous les grades</option>';
    allGrades.forEach(g => document.getElementById('searchGrade').innerHTML += `<option value="${g.id}">${escapeHtml(g.libelle)}</option>`);
    document.getElementById('searchEchelle').value = '';
    currentPage = 1;
    loadEchellons();
}

function loadStats() {
    // Load echellon stats
    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('statMaxEchellon').textContent = stats.max_echellons_per_echelle || 0;
            }
        })
        .catch(error => console.error('Error loading stats:', error));
}

function loadTypeGradesAndGradesForSearch() {
    fetch(`${API_TYPE_GRADE_URL}?action=all`)
        .then(response => response.json())
        .then(result => {
            if (!result.success) return;
            allTypeGrades = result.data;
            const sel = document.getElementById('searchTypeGrade');
            sel.innerHTML = '<option value="">Tous les types</option>';
            allTypeGrades.forEach(t => sel.innerHTML += `<option value="${t.id}">${escapeHtml(t.libelle)}</option>`);
        })
        .catch(error => console.error('Error loading type_grades:', error));

    fetch(`${API_GRADE_URL}?action=all`)
        .then(response => response.json())
        .then(result => {
            if (!result.success) return;
            allGrades = result.data;
            const sel = document.getElementById('searchGrade');
            sel.innerHTML = '<option value="">Tous les grades</option>';
            allGrades.forEach(g => sel.innerHTML += `<option value="${g.id}">${escapeHtml(g.libelle)}</option>`);
        })
        .catch(error => console.error('Error loading grades:', error));
}

function onSearchTypeGradeChange() {
    const typeId = document.getElementById('searchTypeGrade').value;
    const gradeSel = document.getElementById('searchGrade');

    gradeSel.innerHTML = '<option value="">Tous les grades</option>';
    const filteredGrades = typeId ? allGrades.filter(g => g.type_grade_id == typeId) : allGrades;
    filteredGrades.forEach(g => gradeSel.innerHTML += `<option value="${g.id}">${escapeHtml(g.libelle)}</option>`);

    currentPage = 1;
    loadEchellons();
}

function onSearchGradeChange() {
    currentPage = 1;
    loadEchellons();
}

function onSearchEchelleChange() {
    currentPage = 1;
    loadEchellons();
}

function loadEchellesForSelects() {
    fetch(`${API_ECHELLE_URL}?action=all`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const echelles = result.data;

                echellesMap = {};
                echelles.forEach(echelle => {
                    echellesMap[echelle.id] = echelle;
                });

                // Update search select
                const searchSelect = document.getElementById('searchEchelle');
                searchSelect.innerHTML = '<option value="">Toutes les échelles</option>';
                echelles.forEach(echelle => {
                    const option = document.createElement('option');
                    option.value = echelle.id;
                    option.textContent = `${echelle.libelle} (${echelle.code})`;
                    searchSelect.appendChild(option);
                });

                // Update form select
                const formSelect = document.getElementById('echelle_id');
                formSelect.innerHTML = '<option value="">Sélectionner une échelle</option>';
                echelles.forEach(echelle => {
                    const option = document.createElement('option');
                    option.value = echelle.id;
                    option.textContent = `${echelle.libelle} (${echelle.code})`;
                    formSelect.appendChild(option);
                });

                // Update echellon suivant select when echelle changes
                document.getElementById('echelle_id').addEventListener('change', function() {
                    loadEchellonsForSuivant(this.value);
                });
            }
        })
        .catch(error => console.error('Error loading echelles:', error));
}

function loadEchellonsForSuivant(echelleId) {
    const select = document.getElementById('echellon_suivant_id');
    select.innerHTML = '<option value="">Aucun (dernier échelon)</option>';

    // Exclude current echellon if in edit mode
    const currentId = document.getElementById('echellonId').value;

    if (!echelleId) return;

    fetch(`${API_BASE_URL}?action=by_echelle&echelle_id=${echelleId}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                result.data.forEach(echellon => {
                    // Exclude self in edit mode
                    if (currentId && parseInt(currentId) === parseInt(echellon.id)) {
                        return;
                    }
                    const option = document.createElement('option');
                    option.value = echellon.id;
                    option.textContent = `${echellon.libelle} (${echellon.code})`;
                    select.appendChild(option);
                });
            }
        })
        .catch(error => console.error('Error loading echellons for suivant:', error));
}

function loadEchellons() {
    showLoading(true);

    const searchData = {
        id: document.getElementById('searchId')?.value || '',
        libelle: document.getElementById('searchLibelle')?.value || '',
        code: document.getElementById('searchCode')?.value || '',
        echelle_id: document.getElementById('searchEchelle')?.value || '',
        type_grade_id: document.getElementById('searchTypeGrade')?.value || '',
        grade_id: document.getElementById('searchGrade')?.value || '',
        description: document.getElementById('searchDescription')?.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(echellons) {
    const tbody = document.getElementById('tableBody');

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

    tbody.innerHTML = echellons.map(echellon => `
        <tr>
            <td>${echellon.id}</td>
            <td><strong>${escapeHtml(echellon.libelle)}</strong></td>
            <td><span class="badge badge-info">${escapeHtml(echellon.code)}</span></td>
            <td>
                <span class="badge badge-success">
                    ${escapeHtml(echellon.echelle_libelle || echellon.echelle || '-')}
                </span>
            </td>
            <td>${escapeHtml(echellon.description || '-')}</td>
            <td>
                ${echellon.suivant_libelle ?
        `<span class="badge badge-primary">${escapeHtml(echellon.suivant_libelle)}</span>` :
        `<span class="badge badge-secondary">Fin</span>`
    }
            </td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${echellon.id})" title="Voir les détails">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${echellon.id})" title="Modifier">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-danger btn-sm" onclick="deleteEchellon(${echellon.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} échelons`;

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

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

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouvel Échelon';
    document.getElementById('echellonForm').reset();
    document.getElementById('echellonId').value = '';
    document.getElementById('echelle_id').value = '';
    document.getElementById('echellon_suivant_id').innerHTML = '<option value="">Aucun (dernier échelon)</option>';
    document.querySelector('.modal-overlay').classList.add('active');
}

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Échelon';
    document.getElementById('echellonId').value = id;

    if (document.getElementById('detailModal').classList.contains('active')) {
        closeDetailModal();
    }

    document.querySelector('.modal-overlay').classList.add('active');
    document.getElementById('libelle').value = 'Chargement...';
    document.getElementById('libelle').disabled = true;
    document.getElementById('code').value = 'Chargement...';
    document.getElementById('code').disabled = true;
    document.getElementById('echelle_id').disabled = true;
    document.getElementById('echellon_suivant_id').disabled = true;
    document.getElementById('description').value = 'Chargement...';
    document.getElementById('description').disabled = true;

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            document.getElementById('libelle').disabled = false;
            document.getElementById('code').disabled = false;
            document.getElementById('echelle_id').disabled = false;
            document.getElementById('echellon_suivant_id').disabled = false;
            document.getElementById('description').disabled = false;

            if (result.success) {
                const echellon = result.data;
                document.getElementById('libelle').value = echellon.libelle;
                document.getElementById('code').value = echellon.code;
                document.getElementById('echelle_id').value = echellon.echelle_id || '';
                document.getElementById('description').value = echellon.description || '';

                // Load suivant options after setting echelle
                loadEchellonsForSuivant(echellon.echelle_id);

                // Set suivant value after options are loaded
                setTimeout(() => {
                    document.getElementById('echellon_suivant_id').value = echellon.echellon_suivant_id || '';
                }, 200);
            } else {
                showToast('Erreur: ' + result.message, 'error');
                closeModal();
            }
        })
        .catch(error => {
            document.getElementById('libelle').disabled = false;
            document.getElementById('code').disabled = false;
            document.getElementById('echelle_id').disabled = false;
            document.getElementById('echellon_suivant_id').disabled = false;
            document.getElementById('description').disabled = false;
            showToast('Erreur de connexion au serveur', 'error');
            closeModal();
            console.error('Error:', error);
        });
}

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(echellon) {
    const echelleLibelle = echellon.echelle_libelle ||
        (echellesMap[echellon.echelle_id] ? echellesMap[echellon.echelle_id].libelle : echellon.echelle || '-');

    const suivantLibelle = echellon.suivant_libelle || 'Aucun (dernier échelon)';

    // Get chain if available
    let chainHtml = '';
    if (echellon.id) {
        fetch(`${API_BASE_URL}?action=chain&id=${echellon.id}`)
            .then(response => response.json())
            .then(result => {
                if (result.success && result.data.length > 0) {
                    const chainContainer = document.getElementById('echellonChain');
                    if (chainContainer) {
                        chainContainer.innerHTML = result.data.map((e, index) => `
                            <div class="chain-item ${e.id === echellon.id ? 'current' : ''}">
                                <span class="chain-number">${index + 1}</span>
                                <span class="chain-code">${escapeHtml(e.code)}</span>
                                <span class="chain-libelle">${escapeHtml(e.libelle)}</span>
                                ${e.id === echellon.id ? '<span class="badge badge-warning">Actuel</span>' : ''}
                                ${index < result.data.length - 1 ? '<span class="chain-arrow">→</span>' : ''}
                            </div>
                        `).join('');
                    }
                }
            })
            .catch(error => console.error('Error loading chain:', error));
    }

    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <div class="detail-header">
                <div class="detail-avatar">
                    <i class="fas fa-list-ol"></i>
                </div>
                <div class="detail-title">
                    <h2>${escapeHtml(echellon.libelle)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">
                            <i class="fas fa-tag"></i> ${escapeHtml(echellon.code)}
                        </span>
                        <span class="badge badge-success">
                            <i class="fas fa-layer-group"></i> ${escapeHtml(echelleLibelle)}
                        </span>
                        <span class="badge ${echellon.echellon_suivant_id ? 'badge-primary' : 'badge-secondary'}">
                            <i class="fas ${echellon.echellon_suivant_id ? 'fa-arrow-right' : 'fa-stop'}"></i> 
                            ${suivantLibelle}
                        </span>
                    </div>
                </div>
            </div>
            
            <h3><i class="fas fa-info-circle"></i> Informations de l'Échelon</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label"><i class="fas fa-hashtag"></i> ID</span>
                    <span class="value">${echellon.id}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-tag"></i> Code</span>
                    <span class="value">
                        <span class="badge badge-info">${escapeHtml(echellon.code)}</span>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-layer-group"></i> Échelle</span>
                    <span class="value">
                        <span class="badge badge-success">${escapeHtml(echelleLibelle)}</span>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-arrow-right"></i> Échelon Suivant</span>
                    <span class="value">
                        ${echellon.echellon_suivant_id ?
        `<span class="badge badge-primary">${escapeHtml(suivantLibelle)}</span>` :
        `<span class="badge badge-secondary">Fin de chaîne</span>`
    }
                    </span>
                </div>
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-align-left"></i> Libellé</span>
                    <span class="value">${escapeHtml(echellon.libelle)}</span>
                </div>
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-file-alt"></i> Description</span>
                    <span class="value ${!echellon.description ? 'empty' : ''}">
                        ${echellon.description ? escapeHtml(echellon.description) : 'Aucune description'}
                    </span>
                </div>
            </div>

            <!-- Chaîne des échelons -->
            <div class="detail-echellon-chain">
                <h4><i class="fas fa-link"></i> Chaîne des Échelons</h4>
                <div id="echellonChain" class="chain-container">
                    <div class="loading active" style="padding: 20px;">
                        <div class="spinner" style="width: 24px; height: 24px;"></div>
                        <p style="margin-top: 10px; font-size: 13px;">Chargement de la chaîne...</p>
                    </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 saveEchellon() {
    const libelle = document.getElementById('libelle').value.trim();
    const code = document.getElementById('code').value.trim();
    const echelle_id = document.getElementById('echelle_id').value;
    const echellon_suivant_id = document.getElementById('echellon_suivant_id').value || null;
    const description = document.getElementById('description').value.trim();

    if (!libelle) {
        showToast('Veuillez saisir le libellé de l\'échelon', 'warning');
        document.getElementById('libelle').focus();
        return;
    }

    if (!code) {
        showToast('Veuillez saisir le code de l\'échelon', 'warning');
        document.getElementById('code').focus();
        return;
    }

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

    // Code format validation
    if (!/^[A-Z0-9_-]+$/.test(code)) {
        showToast('Le code doit être en majuscules, chiffres, underscores et tirets uniquement (ex: ECH-10-1)', 'warning');
        return;
    }

    const id = document.getElementById('echellonId').value;
    const data = {
        libelle: libelle,
        code: code,
        echelle_id: parseInt(echelle_id),
        echellon_suivant_id: echellon_suivant_id ? parseInt(echellon_suivant_id) : null,
        description: description || 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();
                loadEchellons();
                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 deleteEchellon(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer cet échelon ?\n\nAttention: Si d\'autres échelons le référencent comme échelon suivant, la suppression sera bloquée.\nCette action est irréversible.')) return;

    const btn = document.querySelector(`button[onclick="deleteEchellon(${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');
                loadEchellons();
                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 exportEchellons() {
    window.location.href = `${API_BASE_URL}?action=export`;
}

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

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