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

// Load results on page load
document.addEventListener('DOMContentLoaded', function() {
    loadResults();
    loadStats();
    setupSearchForm();
});

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

function resetSearch() {
    document.getElementById('searchForm').reset();
    // Reset selects to default
    document.getElementById('searchBadgeEcrit').value = '';
    document.getElementById('searchBadgeOrale').value = '';
    document.getElementById('searchBadgeFinale').value = '';
    currentPage = 1;
    loadResults();
}

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;
            }
        })
        .catch(error => console.error('Error loading stats:', error));
}

function loadResults() {
    showLoading(true);

    const searchData = {
        id: document.getElementById('searchId')?.value || '',
        libelle: document.getElementById('searchLibelle')?.value || '',
        code: document.getElementById('searchCode')?.value || '',
        description: document.getElementById('searchDescription')?.value || '',
        order_preparation_ecrit: document.getElementById('searchOrderEcrit')?.value || '',
        badge_preparation_ecrit: document.getElementById('searchBadgeEcrit')?.value || '',
        order_preparation_orale: document.getElementById('searchOrderOrale')?.value || '',
        badge_preparation_orale: document.getElementById('searchBadgeOrale')?.value || '',
        order_resultat_finale: document.getElementById('searchOrderFinale')?.value || '',
        badge_resultat_finale: document.getElementById('searchBadgeFinale')?.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(results) {
    const tbody = document.getElementById('tableBody');

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

    tbody.innerHTML = results.map(result => `
        <tr>
            <td>${result.id}</td>
            <td><strong>${escapeHtml(result.libelle)}</strong></td>
            <td><span class="badge badge-info">${escapeHtml(result.code)}</span></td>
            <td>${escapeHtml(result.description || '-')}</td>
            <td>${result.order_preparation_ecrit || '-'}</td>
            <td>${result.badge_preparation_ecrit ? `<span class="badge ${result.badge_preparation_ecrit}">${result.badge_preparation_ecrit.replace('badge-', '')}</span>` : '-'}</td>
            <td>${result.order_preparation_orale || '-'}</td>
            <td>${result.badge_preparation_orale ? `<span class="badge ${result.badge_preparation_orale}">${result.badge_preparation_orale.replace('badge-', '')}</span>` : '-'}</td>
            <td>${result.order_resultat_finale || '-'}</td>
            <td>${result.badge_resultat_finale ? `<span class="badge ${result.badge_resultat_finale}">${result.badge_resultat_finale.replace('badge-', '')}</span>` : '-'}</td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${result.id})" title="Voir les détails">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${result.id})" title="Modifier">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-danger btn-sm" onclick="deleteResult(${result.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} résultats`;

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

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

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouveau Résultat de Concours';
    document.getElementById('resultForm').reset();
    document.getElementById('resultId').value = '';
    document.querySelector('.modal-overlay').classList.add('active');
}

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Résultat de Concours';
    document.getElementById('resultId').value = id;

    // Close detail modal if open
    if (document.getElementById('detailModal').classList.contains('active')) {
        closeDetailModal();
    }

    // Show loading state
    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('description').value = 'Chargement...';
    document.getElementById('description').disabled = true;
    document.getElementById('order_preparation_ecrit').disabled = true;
    document.getElementById('badge_preparation_ecrit').disabled = true;
    document.getElementById('order_preparation_orale').disabled = true;
    document.getElementById('badge_preparation_orale').disabled = true;
    document.getElementById('order_resultat_finale').disabled = true;
    document.getElementById('badge_resultat_finale').disabled = true;

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            // Enable fields
            document.getElementById('libelle').disabled = false;
            document.getElementById('code').disabled = false;
            document.getElementById('description').disabled = false;
            document.getElementById('order_preparation_ecrit').disabled = false;
            document.getElementById('badge_preparation_ecrit').disabled = false;
            document.getElementById('order_preparation_orale').disabled = false;
            document.getElementById('badge_preparation_orale').disabled = false;
            document.getElementById('order_resultat_finale').disabled = false;
            document.getElementById('badge_resultat_finale').disabled = false;

            if (result.success) {
                const data = result.data;
                document.getElementById('libelle').value = data.libelle;
                document.getElementById('code').value = data.code;
                document.getElementById('description').value = data.description || '';
                document.getElementById('order_preparation_ecrit').value = data.order_preparation_ecrit || '';
                document.getElementById('badge_preparation_ecrit').value = data.badge_preparation_ecrit || '';
                document.getElementById('order_preparation_orale').value = data.order_preparation_orale || '';
                document.getElementById('badge_preparation_orale').value = data.badge_preparation_orale || '';
                document.getElementById('order_resultat_finale').value = data.order_resultat_finale || '';
                document.getElementById('badge_resultat_finale').value = data.badge_resultat_finale || '';
            } else {
                showToast('Erreur: ' + result.message, 'error');
                closeModal();
            }
        })
        .catch(error => {
            document.getElementById('libelle').disabled = false;
            document.getElementById('code').disabled = false;
            document.getElementById('description').disabled = false;
            document.getElementById('order_preparation_ecrit').disabled = false;
            document.getElementById('badge_preparation_ecrit').disabled = false;
            document.getElementById('order_preparation_orale').disabled = false;
            document.getElementById('badge_preparation_orale').disabled = false;
            document.getElementById('order_resultat_finale').disabled = false;
            document.getElementById('badge_resultat_finale').disabled = false;
            showToast('Erreur de connexion au serveur', 'error');
            closeModal();
            console.error('Error:', error);
        });
}

function viewDetail(id) {
    currentDetailId = id;

    // Show modal with loading state
    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>
    `;

    // Hide edit button initially
    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(data) {
    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <!-- Header with icon -->
            <div class="detail-header">
                <div class="detail-avatar">
                    <i class="fas fa-trophy"></i>
                </div>
                <div class="detail-title">
                    <h2>${escapeHtml(data.libelle)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">
                            <i class="fas fa-tag"></i> ${escapeHtml(data.code)}
                        </span>
                        <span class="meta-text">
                            <i class="fas fa-calendar-alt"></i> 
                            ID: ${data.id}
                        </span>
                    </div>
                </div>
            </div>
            
            <!-- Information Grid -->
            <h3><i class="fas fa-info-circle"></i> Informations du Résultat</h3>
            <div class="detail-grid">
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-align-left"></i> Libellé</span>
                    <span class="value">${escapeHtml(data.libelle)}</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(data.code)}</span>
                    </span>
                </div>
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-file-alt"></i> Description</span>
                    <span class="value ${!data.description ? 'empty' : ''}">
                        ${data.description ? escapeHtml(data.description) : 'Aucune description'}
                    </span>
                </div>
            </div>

            <!-- Ordres and Badges -->
            <h3><i class="fas fa-list-ol"></i> Ordres et Badges</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label"><i class="fas fa-pen"></i> Ordre Écrit</span>
                    <span class="value">${data.order_preparation_ecrit || '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-tag"></i> Badge Écrit</span>
                    <span class="value">${data.badge_preparation_ecrit ? `<span class="badge ${data.badge_preparation_ecrit}">${data.badge_preparation_ecrit.replace('badge-', '')}</span>` : '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-comment"></i> Ordre Oral</span>
                    <span class="value">${data.order_preparation_orale || '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-tag"></i> Badge Oral</span>
                    <span class="value">${data.badge_preparation_orale ? `<span class="badge ${data.badge_preparation_orale}">${data.badge_preparation_orale.replace('badge-', '')}</span>` : '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-flag-checkered"></i> Ordre Final</span>
                    <span class="value">${data.order_resultat_finale || '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-tag"></i> Badge Final</span>
                    <span class="value">${data.badge_resultat_finale ? `<span class="badge ${data.badge_resultat_finale}">${data.badge_resultat_finale.replace('badge-', '')}</span>` : '-'}</span>
                </div>
            </div>
        </div>
    `;

    // Show the edit button
    document.getElementById('editFromDetailBtn').style.display = 'inline-flex';
}

function editFromDetail() {
    if (currentDetailId) {
        closeDetailModal();
        // Small delay to allow modal to close
        setTimeout(() => {
            openEditModal(currentDetailId);
        }, 300);
    }
}

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

function saveResult() {
    // Validation
    const libelle = document.getElementById('libelle').value.trim();
    const code = document.getElementById('code').value.trim();

    if (!libelle) {
        showToast('Veuillez saisir le libellé du résultat', 'warning');
        document.getElementById('libelle').focus();
        return;
    }

    if (!code) {
        showToast('Veuillez saisir le code du résultat', 'warning');
        document.getElementById('code').focus();
        return;
    }

    // Check code format (uppercase, underscores allowed)
    if (!/^[A-Z_]+$/.test(code)) {
        showToast('Le code doit être en majuscules et sans espaces (ex: EN_COURS, ADMIS_ORALE)', 'warning');
        return;
    }

    const id = document.getElementById('resultId').value;
    const data = {
        libelle: libelle,
        code: code,
        description: document.getElementById('description').value.trim() || null,
        order_preparation_ecrit: document.getElementById('order_preparation_ecrit').value || null,
        badge_preparation_ecrit: document.getElementById('badge_preparation_ecrit').value || null,
        order_preparation_orale: document.getElementById('order_preparation_orale').value || null,
        badge_preparation_orale: document.getElementById('badge_preparation_orale').value || null,
        order_resultat_finale: document.getElementById('order_resultat_finale').value || null,
        badge_resultat_finale: document.getElementById('badge_resultat_finale').value || null
    };

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

    // Show loading state on button
    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();
                loadResults();
                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 deleteResult(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer ce résultat de concours ?\n\nCette action est irréversible.')) return;

    // Show loading state on button
    const btn = document.querySelector(`button[onclick="deleteResult(${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');
                loadResults();
                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 exportResults() {
    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();
        }
    }
});
