const API_PROF_URL = "http://localhost/est-concours/model/api/professors.php";
console.log("main.js تم تحميله بنجاح!"); // هذا للتأكد أن الملف يعمل

document.addEventListener("DOMContentLoaded", function() {
    const btn = document.querySelector('button[onclick="createProf()"]'); 
    // أو إذا استعملت الـ ID الذي اقترحته سابقاً (أفضل):
    // const btn = document.getElementById('create-btn');

    if (btn) {
        console.log("تم العثور على الزر!");
        btn.addEventListener('click', function(e) {
            console.log("تم الضغط على الزر!");
            createProf(); // استدعاء الفانكشن
        });
    } else {
        console.warn("لم يتم العثور على الزر. تأكد من الـ ID أو الـ onclick!");
    }
});

function createProf() {
    alert("الفانكشن تعمل!");
    // هنا ضع الكود الخاص بك
}
function redirectToLogin() {
    window.location.href = '/est-concours/app/cnx/prof/login'
}

function testData() {
    document.getElementById('cin').value = "EE334455";
    document.getElementById('email').value = "anas@uca.ma";
    document.getElementById('nom').value = "Jarane";
    document.getElementById('prenom').value = "Anas";
    document.getElementById('Password').value = "EE334455";
    document.getElementById('login').value = "y.akrami";
    document.getElementById('status').value = "status";
    document.getElementById('phone').value = "06XXXXXXXX";
   

    
}
function createProfesseur() {
    // Get form values
    const cin = document.getElementById('cin').value.trim();
    const email = document.getElementById('email').value.trim();
    const nom = document.getElementById('nom').value.trim();
    const prenom = document.getElementById('prenom').value.trim();
    const password = document.getElementById('Password').value.trim();
    const login = document.getElementById('login').value.trim();
    const phone = document.getElementById('Phone').value.trim();

    // Validate all fields
    let isValid = true;

    // Clear previous errors
    document.querySelectorAll('.error-message').forEach(el => el.classList.remove('show'));
    document.querySelectorAll('.form-control').forEach(el => el.classList.remove('is-invalid'));

    // Validate each field
    if (!cin) {
        document.getElementById('cin').classList.add('is-invalid');
        document.getElementById('cin-error').classList.add('show');
        isValid = false;
    }

    if (!email) {
        document.getElementById('email').classList.add('is-invalid');
        document.getElementById('email-error').classList.add('show');
        isValid = false;
    } else if (!validateEmail(email)) {
        document.getElementById('email').classList.add('is-invalid');
        document.getElementById('email-error').textContent = 'Veuillez entrer un email valide';
        document.getElementById('email-error').classList.add('show');
        isValid = false;
    }

    if (!nom) {
        document.getElementById('nom').classList.add('is-invalid');
        document.getElementById('nom-error').classList.add('show');
        isValid = false;
    }

    if (!prenom) {
        document.getElementById('prenom').classList.add('is-invalid');
        document.getElementById('prenom-error').classList.add('show');
        isValid = false;
    }

    if (!password) {
        document.getElementById('Password').classList.add('is-invalid');
        document.getElementById('Password-error').classList.add('show');
        isValid = false;
    } else if (password.length < 6) {
        document.getElementById('Password').classList.add('is-invalid');
        document.getElementById('Password-error').textContent = 'Le mot de passe doit contenir au moins 6 caractères';
        document.getElementById('Password-error').classList.add('show');
        isValid = false;
    }
     if (!login) {
        document.getElementById('login').classList.add('is-invalid');
        document.getElementById('login-error').classList.add('show');
        isValid = false;
    } 
    
     if (!phone) {
        document.getElementById('Phone').classList.add('is-invalid');
        document.getElementById('Phone-error').classList.add('show');
        isValid = false;
    }
    if (!isValid) {
        return;
    }

    // Prepare data for API
    const professeurData = {
        cin: cin,
        email: email,
        nom: nom,
        prenom: prenom,
        Password: password,
        login: login,
        phone : phone,
       
    };

    // Show loading state
        const createBtn = document.querySelector('button[onclick="createProfesseur()"]');
    const originalText = createBtn.innerHTML;
    createBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Création...';
    createBtn.disabled = true;

    // Call the API
    fetch(`${API_BASE_URL}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify(professeurData)
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            // Reset button state
            createBtn.innerHTML = originalText;
            createBtn.disabled = false;

            if (data.success) {
                // Success - redirect to login page
                window.location.href = 'http://localhost/est-concours/app/cnx/prof/login/';
            } else {
                // Handle API error
                alert('Une erreur est survenue lors de la création du compte.');
            }
        })
        .catch(error => {
            // Reset button state
            createBtn.innerHTML = originalText;
            createBtn.disabled = false;

            console.error('Error:', error);
            Swal.fire({
                icon: 'error',
                title: 'Erreur de connexion',
                text: 'Impossible de contacter le serveur. Veuillez réessayer.'
            });
        });
}


// Helper function to validate email format
function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

// Add Enter key support for form submission
document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('loginForm');
    form.addEventListener('keypress', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            // Check if it's the create button or login button
            // Default to create if fields are filled, otherwise login
            const createBtn = document.querySelector('button[onclick="creatProfesseur()"]');
            const loginBtn = document.getElementById('loginBtn');

            // If all fields are filled, create, else login
            const cin = document.getElementById('cin').value.trim();
            const email = document.getElementById('email').value.trim();
            const nom = document.getElementById('nom').value.trim();
            const prenom = document.getElementById('prenom').value.trim();
            const password = document.getElementById('Password').value.trim();
            const login = document.getElementById('login').value.trim();
            const  	phone = document.getElementById('phone').value.trim();


            if (cin && email && nom && prenom && password && login && phone ) {
                createProfesseur();
            } else {
                // Trigger login validation
                if (validateForm()) {
                    form.submit();
                }
            }
        }
    });
});
