// js/professeurs.js
const API_BASE_URL = '/est-concours/model/api/professeur.php';
let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;

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

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

function resetSearch() {
    document.getElementById('searchForm').reset();
    currentPage = 1;
    loadProfesseurs();
}

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('statActif').textContent = stats.actif || 0;
                document.getElementById('statInactif').textContent = stats.inactif || 0;
            }
        })
        .catch(error => console.error('Error loading stats:', error));
}

function loadProfesseurs() {
    showLoading(true);

    const searchData = {
        code: document.getElementById('searchCode').value,
        nom: document.getElementById('searchNom').value,
        prenom: document.getElementById('searchPrenom').value,
        email: document.getElementById('searchEmail').value,
        cin: document.getElementById('searchCIN').value,
        login: document.getElementById('searchLogin').value,
        specialite: document.getElementById('searchSpecialite').value,
        grade: document.getElementById('searchGrade').value,
        status: document.getElementById('searchStatus').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(professeurs) {
    const tbody = document.getElementById('tableBody');

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

    tbody.innerHTML = professeurs.map(prof => `
        <tr>
            <td>${prof.id}</td>
            <td><strong>${escapeHtml(prof.code)}</strong></td>
            <td>${escapeHtml(prof.nom)}</td>
            <td>${escapeHtml(prof.prenom)}</td>
            <td>${escapeHtml(prof.email)}</td>
            <td>${escapeHtml(prof.cin)}</td>
            <td>${escapeHtml(prof.login)}</td>
            <td>${escapeHtml(prof.specialite || '-')}</td>
            <td>${escapeHtml(prof.grade || '-')}</td>
            <td><span class="badge ${prof.status === 'active' ? 'badge-success' : 'badge-danger'}">
                ${prof.status === 'active' ? 'Actif' : 'Inactif'}
            </span></td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${prof.id})">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${prof.id})">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-danger btn-sm" onclick="deleteProfesseur(${prof.id})">
                    <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} professeurs`;

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

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

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouveau Professeur';
    document.getElementById('professeurForm').reset();
    document.getElementById('professeurId').value = '';
    document.getElementById('password').required = false;
    document.querySelector('.modal-overlay').classList.add('active');
}

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Professeur';
    document.getElementById('professeurId').value = id;
    document.getElementById('password').required = false;
    document.getElementById('password_confirm').required = false;

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const prof = result.data;
                document.getElementById('code').value = prof.code;
                document.getElementById('nom').value = prof.nom;
                document.getElementById('prenom').value = prof.prenom;
                document.getElementById('cin').value = prof.cin;
                document.getElementById('email').value = prof.email;
                document.getElementById('login').value = prof.login;
                document.getElementById('phone').value = prof.phone || '';
                document.getElementById('specialite').value = prof.specialite || '';
                document.getElementById('grade').value = prof.grade || '';
                document.getElementById('status').value = prof.status || 'active';
                document.getElementById('password').value = '';
                document.getElementById('password_confirm').value = '';

                document.querySelector('.modal-overlay').classList.add('active');
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function viewDetail(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>
    `;

    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 = `
                    <p style="color: var(--danger-color);">Erreur: ${result.message}</p>
                `;
            }
        })
        .catch(error => {
            document.getElementById('detailContent').innerHTML = `
                <p style="color: var(--danger-color);">Erreur de connexion au serveur</p>
            `;
            console.error('Error:', error);
        });
}

function renderDetail(prof) {
    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <div style="display: flex; align-items: center; gap: var(--spacing-lg); margin-bottom: var(--spacing-lg);">
                <div style="width: 100px; height: 100px; border-radius: 50%; background: var(--primary-bg); display: flex; align-items: center; justify-content: center; font-size: 48px; color: var(--primary-color);">
                    <i class="fas fa-user-tie"></i>
                </div>
                <div>
                    <h2 style="margin: 0;">${escapeHtml(prof.nom)} ${escapeHtml(prof.prenom)}</h2>
                    <p style="color: var(--text-muted); margin: var(--spacing-xs) 0;">
                        <i class="fas fa-envelope"></i> ${escapeHtml(prof.email)}
                    </p>
                    <p style="color: var(--text-muted); margin: 0;">
                        <span class="badge ${prof.status === 'active' ? 'badge-success' : 'badge-danger'}">
                            ${prof.status === 'active' ? 'Actif' : 'Inactif'}
                        </span>
                    </p>
                </div>
            </div>
            
            <h3>Informations Personnelles</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label">Code</span>
                    <span class="value">${escapeHtml(prof.code)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">CIN</span>
                    <span class="value">${escapeHtml(prof.cin)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Login</span>
                    <span class="value">${escapeHtml(prof.login)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Téléphone</span>
                    <span class="value">${escapeHtml(prof.phone || '-')}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Spécialité</span>
                    <span class="value">${escapeHtml(prof.specialite || '-')}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Grade</span>
                    <span class="value">${escapeHtml(prof.grade || '-')}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Dernière connexion</span>
                    <span class="value">${prof.last_login ? formatDate(prof.last_login) : 'Jamais'}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Date d'inscription</span>
                    <span class="value">${formatDate(prof.created_at)}</span>
                </div>
            </div>
        </div>
    `;
}

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

function saveProfesseur() {
    // Validation
    const code = document.getElementById('code').value;
    const nom = document.getElementById('nom').value;
    const prenom = document.getElementById('prenom').value;
    const cin = document.getElementById('cin').value;
    const email = document.getElementById('email').value;
    const login = document.getElementById('login').value;
    const password = document.getElementById('password').value;
    const passwordConfirm = document.getElementById('password_confirm').value;

    if (!nom || !prenom || !cin || !email || !login) {
        showToast('Veuillez remplir tous les champs obligatoires (*)', 'warning');
        return;
    }

    // Vérifier les mots de passe si un nouveau est fourni
    if (password && password !== passwordConfirm) {
        showToast('Les mots de passe ne correspondent pas', 'warning');
        return;
    }

    if (password && password.length < 6) {
        showToast('Le mot de passe doit contenir au moins 6 caractères', 'warning');
        return;
    }

    const id = document.getElementById('professeurId').value;

    const data = {
        code: code || null,
        nom: nom,
        prenom: prenom,
        cin: cin,
        email: email,
        login: login,
        phone: document.getElementById('phone').value || null,
        specialite: document.getElementById('specialite').value || null,
        grade: document.getElementById('grade').value || null,
        status: document.getElementById('status').value
    };

    if (password) {
        data.password = password;
    }

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

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                closeModal();
                loadProfesseurs();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function deleteProfesseur(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer ce professeur ?')) return;

    fetch(`${API_BASE_URL}?action=delete&id=${id}`, {
        method: 'DELETE'
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                loadProfesseurs();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function exportProfessors() {
    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 {
            closeModal();
        }
    }
});
