/* =====================
   HELPER
===================== */
function setMsg(el, text, color){
    if(!el) return;
    el.innerText = text;
    el.style.color = color;
}

/* =====================
   AJAX LIVE CHECK
===================== */
function checkLive(field, value, callback){
fetch(BASE + "/modules/User/auth/check_live.php",{
    method:"POST",
    headers:{
        "Content-Type":"application/x-www-form-urlencoded"
    },
    body:`field=${field}&value=${encodeURIComponent(value)}`
})
.then(res=>res.json())
.then(data=>callback(data.exists));
}

/* =====================
   FULL NAME (FIXED ERROR LOCATION)
===================== */
function validateFullName(){
let input = document.getElementById("full_name");
let msg = document.getElementById("fullNameMsg");
if(!input) return;

let value = input.value
    .replace(/[^a-zA-Z.\s]/g,'')
    .toUpperCase();

input.value = value;

if(value.length < 6){
    setMsg(msg,"Name too short","red");
}else{
    setMsg(msg,"Valid name ✓ ","green");
}
}

/* =====================
   CLUB NAME
===================== */
function validateClubName(){
let input = document.getElementById("club_name");
let msg = document.getElementById("clubMsg");
if(!input) return;

let value = input.value
    .replace(/[^a-zA-Z\s]/g,'')
    .toUpperCase();

input.value = value;

if(value.length < 3){
    setMsg(msg,"Club name too short","red");
}else{
    setMsg(msg,"Valid club name ✓","green");
}
}


/* =====================
   ADVISOR NAME (REMOVE DUPLICATE)
===================== */
function validateAdvisorName(){
let input = document.getElementById("advisor_name");
let msg = document.getElementById("advisorNameMsg");
if(!input) return;

let value = input.value
    .replace(/[^a-zA-Z.\s]/g,'')
    .toUpperCase();

input.value = value;

if(value.length < 3){
    setMsg(msg,"Name too short","red");
}else{
    setMsg(msg,"Valid name ✓","green");
}
}

/* =====================
   ADVISOR PHONE
===================== */
function validateAdvisorPhone(){

let input = document.getElementById("advisor_phone");
let userInput = document.getElementById("phone"); // ðŸ”¥ add this
let msg = document.getElementById("advisorMsg");

if(!input) return;

let value = input.value.replace(/\D/g,'').slice(0,11);
input.value = value;

let userValue = userInput ? userInput.value.replace(/\D/g,'') : "";

let valid = /^01[0-9]{8,9}$/.test(value);

if(!value.startsWith("01")){
    setMsg(msg,"Must start with 01","red");
}
else if(value.length < 10){
    setMsg(msg,"Must be 10 - 11 digits","red");
}
else if(!valid){
    setMsg(msg,"Invalid phone format","red");
}
else if(value && userValue && value === userValue){ // ðŸ”¥ NEW CHECK
    setMsg(msg,"Phone already exist","red");
}
else{
    checkLive("advisor_phone", value, exists=>{
        setMsg(msg, exists ? "Phone already exists" : "Valid phone number ✓", exists ? "red":"green");
    });
}
}


/* =====================
   PHONE (USER)
===================== */
function validatePhone(){

let input = document.getElementById("phone");
let advisorInput = document.getElementById("advisor_phone"); // ðŸ”¥ add this
let msg = document.getElementById("phoneMsg");

if(!input) return;

let value = input.value.replace(/\D/g,'').slice(0,11);
input.value = value;

let advisorValue = advisorInput ? advisorInput.value.replace(/\D/g,'') : "";

let valid = /^01[0-9]{8,9}$/.test(value);

if(!value.startsWith("01")){
    setMsg(msg,"Must start with 01","red");
}
else if(value.length < 10){
    setMsg(msg,"Must be 10 - 11 digits","red");
}
else if(!valid){
    setMsg(msg,"Invalid phone format","red");
}
else if(value && advisorValue && value === advisorValue){  // ðŸ”¥ NEW CHECK
    setMsg(msg,"Cannot be same as advisor phone","red");
}
else{
    checkLive("phone", value, exists=>{
        setMsg(msg, exists ? "Phone already exists" : "Valid phone number ✓", exists ? "red":"green");
    });
}
}

/* =====================
   EMAIL
===================== */
function validateEmail(){

let input = document.getElementById("email"); // âœ… FIXED
let role = document.querySelector("input[name='role']").value;
let msg = document.getElementById("emailMsg");

if(!input) return;

let value = input.value.trim().toLowerCase();

let valid =
(role==="student" && value.endsWith("@student.usm.my")) ||
(role==="staff" && value.endsWith("@usm.my")) ||
(role==="organizer" && value.endsWith("@gmail.com"));

if(!valid){
    setMsg(msg,"Invalid email domain","red");
    input.setCustomValidity("Invalid");
    return;
}

clearTimeout(window.emailTimer);

window.emailTimer = setTimeout(()=>{
    checkLive("email", value, exists=>{
        if(exists){
            setMsg(msg,"Email already exists","red");
            input.setCustomValidity("exists");
        }else{
            setMsg(msg,"Valid email ✓","green");
            input.setCustomValidity("");
        }
    });
},300);
}

/* =====================
   PDF VALIDATION
===================== */
function validatePDF(){

let input = document.getElementById("supportFile");
let msg = document.getElementById("fileMsg");

if(!input.files.length){
    msg.innerText="";
    return;
}

let file = input.files[0];

let maxSize = 5 * 1024 * 1024; // 5MB
let isPDF = file.type === "application/pdf";

if(!isPDF){
    msg.innerText = "Only PDF file allowed";
    msg.style.color = "red";
    input.value="";
    return;
}

if(file.size > maxSize){
    msg.innerText = "File too large (Max 5MB)";
    msg.style.color = "red";
    input.value="";
    return;
}

msg.innerText = "Selected: " + file.name + " ✓ ";
msg.style.color = "green";

}

/* =====================
   MATRIC (STUDENT)
===================== */
function validateMatric(){

let input = document.getElementById("matric");
let msg = document.getElementById("matricMsg");
if(!input) return;

let value = input.value.replace(/\D/g,'').slice(0,6);
input.value = value;

if(value.length < 6){
    setMsg(msg,"Must be 6 digits","red");
}
else{
    checkLive("matric", value, exists=>{
        if(exists){
            setMsg(msg,"Matric already exists","red");
        }else{
            setMsg(msg,"Valid matric ID ✓","green");
        }
    });
}

}

/* =====================
   MATRIC (STAFF)
===================== */
function validateStaffMatric(){

let input = document.getElementById("staff_matric"); // âœ… FIXED
let msg = document.getElementById("matricMsg");

if(!input) return;

let value = input.value.toUpperCase()
    .replace(/[^A-Z0-9]/g,'')
    .slice(0,6);

input.value = value;

let valid = /^[A-Z]{2}[0-9]{4}$/.test(value);

if(value.length < 6){
    setMsg(msg,"Format: 2 letters + 4 digits","red");
}
else if(!valid){
    setMsg(msg,"Invalid format (e.g. ST1234)","red");
}
else{

    // realtime DB check
    checkLive("staff_matric", value, exists=>{

        if(exists){
            setMsg(msg,"Staff ID already exists","red");
        }else{
            setMsg(msg,"Valid staff ID ✓","green");
        }

    });

}

}

/* =====================
   PASSWORD
===================== */
function validatePassword(){

let pass = document.getElementById("password").value; // âœ… FIXED
let msg = document.getElementById("passMsg");

let rules = [
    pass.length >= 7,
    /[A-Z]/.test(pass),
    /[a-z]/.test(pass),
    /[0-9]/.test(pass),
    /[\W]/.test(pass)
];

if(rules.every(Boolean)){
    setMsg(msg,"Strong password ✓ ","green");
}else{
    setMsg(msg,"Weak password","red");
}
}

/* =====================
   CONFIRM PASSWORD
===================== */
function validateConfirm(){

let pass = document.getElementById("password").value; // âœ… FIXED
let confirm = document.getElementById("confirm").value;

let msg = document.getElementById("confirmMsg");

if(confirm===""){
    msg.innerText="";
}
else if(pass===confirm){
    setMsg(msg,"Password match ✓","green");
}else{
    setMsg(msg,"Password not match","red");
}
}


function validateBankHolder(){
    const input = document.getElementById("bank_holder"); 
    const msg = document.getElementById("bankHolderMsg");

    if(!input) return;

    let value = input.value;

    value = value.replace(/[^A-Za-z.\s]/g,'')
                 .replace(/\s+/g,' ')
                 .trimStart()
                 .toUpperCase();

    value = value.slice(0,50); // match SQL

    input.value = value;

    if(value.length < 3){
        setMsg(msg,"Too short","red");
    }
    else if(value.length > 50){
        setMsg(msg,"Max 150 characters","red");
    }
    else{
        setMsg(msg,"Valid account holder ✓","green");
    }
}

function validateBankAccount(){
    const input = document.getElementById("bank_account");
    const msg = document.getElementById("bankAccMsg");

    if(!input) return;

    let value = input.value.replace(/[^0-9]/g,''); // SQL = VARCHAR but numeric only

    input.value = value;

    if(value.length < 8){
        setMsg(msg,"Too short","red");
    }
    else if(value.length > 50){
        setMsg(msg,"Too long (max 50)","red");
    }
    else{
        setMsg(msg,"Valid bank account ✓","green");
    }
}

/* =====================
   FORM SUBMIT
===================== */
document.getElementById("regForm").addEventListener("submit", function(e){

e.preventDefault();

let invalid = document.querySelectorAll(":invalid");

if(invalid.length > 0){
    showToast("Please fix all errors first","error");
    return;
}

let formData = new FormData(this);

fetch(BASE + "/modules/User/auth/register_process.php",{
    method:"POST",
    body:formData
})
.then(res=>res.json())
.then(data=>{

showToast(data.message, data.status);

if(data.status==="success"){
    setTimeout(()=>{
        window.location = BASE + "/login.php";
    },2000);
}

})
.catch(()=>{
    showToast("Connection error","error");
});

});

/* =====================
   TOAST
===================== */
function showToast(msg,type){

let box = document.getElementById("toastBox");
box.innerHTML="";

let t=document.createElement("div");
t.className = "toast " + (type==="success" ? "toast-success" : "toast-error");
t.innerText = msg;

box.appendChild(t);

setTimeout(()=>t.remove(),5000);

}


document.getElementById("bank_account").addEventListener("input", function(){
    this.value = this.value.replace(/[^0-9-]/g,'');
});