// js/main.js
// Define the base API URL based on your file structure
const API_BASE_URL = '/est-concours/model/api/candidat.php';
// Or if using relative path from the HTML location:
// const API_BASE_URL = '../../model/api/candidat.php';

let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;

// Load candidat on page load
document.addEventListener('DOMContentLoaded', function () {
    loadCandidats();
    setupSearchForm();
});

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

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

function loadCandidats() {
    showLoading(true);

    const searchData = {
        nom: document.getElementById('searchNom').value,
        prenom: document.getElementById('searchPrenom').value,
        email: document.getElementById('searchEmail').value,
        cin: document.getElementById('searchCIN').value,
        phone: document.getElementById('searchPhone').value,
        page: currentPage,
        per_page: perPage
    };

    const params = new URLSearchParams(searchData);

    // Use the API_BASE_URL constant defined above
    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(candidats) {
    const tbody = document.getElementById('tableBody');

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

    tbody.innerHTML = candidats.map(candidat => `
        <tr>
            <td>${candidat.id}</td>
            <td><strong>${escapeHtml(candidat.nom || '')}</strong></td>
            <td>${escapeHtml(candidat.prenom || '')}</td>
            <td>${escapeHtml(candidat.email || '')}</td>
            <td>${escapeHtml(candidat.cin || '')}</td>
            <td>${escapeHtml(candidat.phone || '')}</td>
            <td>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${candidat.id})"> ✏️</button>
                    <button class="btn btn-info btn-sm" onclick="viewDetail(${candidat.id})"> 👁️</button>
                <button class="btn btn-danger btn-sm" onclick="deleteCandidat(${candidat.id})"> 🗑️</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} candidats`;

    // Generate page numbers
    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;

    // Enable/disable navigation buttons
    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++;
    }
    loadCandidats();
}

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

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouvel Candidat';
    document.getElementById('candidatForm').reset();
    document.getElementById('candidatId').value = '';
    document.querySelector('.modal-overlay').classList.add('active');
}
function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Candidat';

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const candidat = result.data;
                document.getElementById('candidatId').value = candidat.id;
                document.getElementById('nom').value = candidat.nom || '';
                document.getElementById('prenom').value = candidat.prenom || '';
                document.getElementById('email').value = candidat.email || '';
                document.getElementById('cin').value = candidat.cin || '';
                document.getElementById('phone').value = candidat.phone || '';

                // تعديل هنا: تعبئة حقل كلمة السر الحالية
                // تأكدي أن الخاصية في الـ API تسمى 'password'
                document.getElementById('current_password').value = candidat.password || '';

                document.getElementById('new_password').value = '';
                document.getElementById('confirm_password').value = '';

                // إخفاء خانات كلمة السر الجديدة عند فتح المودال (حسب رغبتك)
                const passwordSection = document.getElementById('new-password-section');
                if (passwordSection) {
                    passwordSection.style.display = 'none';
                }

                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 closeModal() {
    document.querySelector('.modal-overlay').classList.remove('active');
}

function saveCandidat() {
    const id = document.getElementById('candidatId').value;
    const data = {
        nom: document.getElementById('nom').value,
        prenom: document.getElementById('prenom').value,
        email: document.getElementById('email').value,
        cin: document.getElementById('cin').value,
        phone: document.getElementById('phone').value,
        current_password: document.getElementById('current_password').value,
        new_password: document.getElementById('new_password').value,
        confirm_password: document.getElementById('confirm_password').value
    };

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

    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();
                loadCandidats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function deleteCandidat(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer cet candidat ?')) return;

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

// ========================================
// VIEW STUDENT DETAILS
// ========================================
// ========================================
// VIEW STUDENT DETAIL
// ========================================
function viewDetail(id) {
    // Show the modal
    document.getElementById('viewModal').classList.add('active');

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

    // Fetch candidat data
    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                renderDetail(result.data);
            } else {
                document.getElementById('viewContent').innerHTML = `
                    <p style="color: var(--danger-color);">Erreur: ${escapeHtml(result.message)}</p>
                `;
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            document.getElementById('viewContent').innerHTML = `
                <p style="color: var(--danger-color);">Erreur de connexion au serveur</p>
            `;
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function renderDetail(candidat) {
    document.getElementById('viewContent').innerHTML = `
        <div class="detail-section">
            <!-- Header with Avatar -->
            <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-graduate"></i>
                </div>
                <div>
                    <h2 style="margin: 0;">${escapeHtml(candidat.prenom)} ${escapeHtml(candidat.nom)}</h2>
                    <p style="color: var(--text-muted); margin: var(--spacing-xs) 0;">
                        <i class="fas fa-envelope"></i> ${escapeHtml(candidat.email)}
                    </p>
                    <p style="color: var(--text-muted); margin: 0;">
                        <span class="badge badge-success">Candidat</span>
                        <span class="badge ${candidat.active ? 'badge-success' : 'badge-danger'}" style="margin-left: 5px;">
                            ${candidat.active ? 'Actif' : 'Inactif'}
                        </span>
                    </p>
                </div>
            </div>
            
            <!-- Personal Information -->
            <h3>Informations Personnelles</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label">ID</span>
                    <span class="value">#${escapeHtml(candidat.id)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Nom</span>
                    <span class="value">${escapeHtml(candidat.nom)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Prénom</span>
                    <span class="value">${escapeHtml(candidat.prenom)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">CIN</span>
                    <span class="value">${escapeHtml(candidat.cin)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Email</span>
                    <span class="value">
                        <a href="mailto:${escapeHtml(candidat.email)}" style="color: var(--primary-color); text-decoration: none;">
                            ${escapeHtml(candidat.email)}
                        </a>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="label">Téléphone</span>
                    <span class="value">
                        ${candidat.phone ? `<a href="tel:${escapeHtml(candidat.phone)}" style="color: var(--primary-color); text-decoration: none;">${escapeHtml(candidat.phone)}</a>` : '-'}
                    </span>
                </div>
                <div class="detail-item">
                    <span class="label">Statut</span>
                    <span class="value">
                        <span class="badge ${candidat.active ? 'badge-success' : 'badge-danger'}">
                            ${candidat.active ? 'Actif' : 'Inactif'}
                        </span>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="label">Rôle</span>
                    <span class="value">
                        <span class="badge badge-primary">Candidat</span>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="label">Date d'inscription</span>
                    <span class="value">${candidat.created_at ? formatDate(candidat.created_at) : '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Dernière modification</span>
                    <span class="value">${candidat.updated_at ? formatDate(candidat.updated_at) : '-'}</span>
                </div>
            </div>

        </div>
    `;
}

function closeViewModal() {
    document.getElementById('viewModal').classList.remove('active');
}

function closeViewModal() {
    document.getElementById('viewModal').classList.remove('active');
}

// Format date helper function
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 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.textContent = message;
    container.appendChild(toast);

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

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

// Close modal on overlay click
document.querySelector('.modal-overlay').addEventListener('click', function (e) {
    if (e.target === this) {
        closeModal();
    }
});

document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') {
        closeModal();
    }
});
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const icon = input.nextElementSibling;

    if (input.type === "password") {
        input.type = "text";
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        input.type = "password";
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}
function updatePasswordOnly() {
    const id = document.getElementById('candidatId').value;
    const current_password = document.getElementById('current_password').value;
    const new_password = document.getElementById('new_password').value;
    const confirm_password = document.getElementById('confirm_password').value;

    if (!current_password || !new_password || !confirm_password) {
        showToast('Veuillez remplir tous les champs de mot de passe', 'warning');
        return;
    }

    const data = {
        current_password: current_password,
        new_password: new_password,
        confirm_password: confirm_password
    };

    fetch(`${API_BASE_URL}?action=update_password&id=${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                // تفريغ الحقول بعد النجاح
                document.getElementById('current_password').value = '';
                document.getElementById('new_password').value = '';
                document.getElementById('confirm_password').value = '';
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => showToast('Erreur de connexion', 'error'));
}
// فاش كيتفتح الـ Modal
document.getElementById('current_password').value = data.password; // هنا كتحطي كلمة السر ديال الطالب
function showPasswordFields() {
    document.getElementById('new-password-section').style.display = 'block';
}
// 1. دالة إظهار خانات التغيير
function enablePasswordChange() {
    document.getElementById('new-password-fields').style.display = 'block';
}
// دالة إظهار خانات كلمة السر الجديدة
function showPasswordFields() {
    const newPasswordSection = document.getElementById('new-password-section');
    if (newPasswordSection) {
        newPasswordSection.style.display = 'block';
    } else {
        alert("تأكدي من إضافة div بالـ id 'new-password-section' حول خانات كلمة السر الجديدة");
    }
}
function enablePasswordChange() {
    // إظهار حقول كلمة السر الجديدة إذا كانت مخفية
    const newPasswordSection = document.getElementById('new-password-section');
    if (newPasswordSection) {
        newPasswordSection.style.display = 'block';
    }
    document.getElementById('new_password').focus();

    showToast("Veuillez entrer votre nouveau mot de passe", "info");
}