window.BASE = "/SEAT";
window.payMethod = "Card";
window.paymentProcessing = false;

/* =====================================================
   GLOBAL UPDATE HOOK (NEW)
===================================================== */
function triggerGlobalUpdates(){

    if(typeof loadNotificationRealtime === "function"){
        loadNotificationRealtime();
    }

    if(typeof showToast === "function"){
        showToast("Updated successfully", "success");
    }
}

/* =====================================================
   START REGISTRATION
===================================================== */

window.submitRegisterFlow = function(event_id){

    const box = document.getElementById("regResult");
    const btn = document.getElementById("mainBtn");

    btn.disabled = true;
    btn.innerHTML = "Processing...";

    

    fetch(window.BASE + "/modules/Ticket/generateTicket.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({ event_id })
    })

    .then(r => r.json())

    .then(data => {

        if(!data || typeof data !== "object"){
            throw new Error("Invalid response");
        }

        if(data.error){

            box.innerHTML = `
                <div class="msg error">
                    ${String(data.error)}
                </div>
            `;

            btn.disabled = false;
            btn.innerHTML = "Try Again";
            return;
        }

        if(data.type === "free"){
            showTicket(data);
            triggerGlobalUpdates();
            return;
        }

        if(data.type === "paid"){
            showPayment(data);
            return;
        }

        box.innerHTML = `
            <div class="msg error">
                Invalid server response
            </div>
        `;

        btn.disabled = false;
        btn.innerHTML = "Try Again";
    })

    .catch(() => {

        box.innerHTML = `
            <div class="msg error">
                Something went wrong
            </div>
        `;

        btn.disabled = false;
        btn.innerHTML = "Try Again";
    });

};

/* =====================================================
   PAYMENT UI
===================================================== */

window.showPayment = function(data){

    document.getElementById("mainCard").innerHTML = `
    
    <div class="regClose" onclick="closeModal()">×</div>

    <div class="modalHeader">
        <h2 class="regTitle">Payment Required</h2>
        <p class="regClub">${data.club || ""}</p>
    </div>

    <div class="infoCard">

        <div class="infoGrid">

            <div class="infoRow">
                <span>Event</span>
                <b>${data.title || "-"}</b>
            </div>

            <div class="infoRow">
                <span>Amount</span>
                <b>RM ${data.amount || "0.00"}</b>
            </div>

            <div class="infoRow fullRow">
                <span>Account Holder</span>
                <b>${data.bank_holder || "-"}</b>
            </div>

            <div class="infoRow fullRow">
                <span>Bank</span>
                <b>${data.bank_name || "-"}</b>
            </div>

            <div class="infoRow fullRow">
                <span>Account Number</span>
                <b>${data.bank_account_number || "-"}</b>
            </div>

        </div>

    </div>

    <div id="payResult"></div>

    <div class="regActions">

        <button class="regBtn primary" id="payBtn"
            onclick="payNow(${Number(data.event_id)})">
            Pay Now
        </button>

        <button class="regBtn light" onclick="closeModal()">
            Cancel
        </button>

    </div>
    `;
};

/* =====================================================
   PROCESS PAYMENT
===================================================== */

window.payNow = function(event_id){

    if(window.paymentProcessing){
        return;
    }

    window.paymentProcessing = true;

    const box = document.getElementById("payResult");
    const btn = document.getElementById("payBtn");

    btn.disabled = true;
    btn.innerHTML = "Processing...";

    box.innerHTML = `
        <div class="msg loading">
    <div class="spin large"></div>
    <div class="loadingText">
        Processing Payment...
    </div>
</div>
    `;

    setTimeout(() => {

        fetch(window.BASE + "/modules/Payment/processPayment.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                event_id,
                payment_method: window.payMethod
            })
        })

        .then(r => r.json())

        .then(data => {

            if(!data || typeof data !== "object"){
                throw new Error("Invalid response");
            }

            if(data.error){

                box.innerHTML = `
                    <div class="msg error">
                        ${String(data.error)}
                    </div>
                `;

                btn.disabled = false;
                btn.innerHTML = "Pay Now";
                window.paymentProcessing = false;
                return;
            }

            /* ✅ SUCCESS UI (FIXED ICON ENCODING) */
            box.innerHTML = `
                <div class="paymentSuccess">
                    <div class="icon">✔</div>
                    <div class="title">Payment Successful</div>
                </div>
            `;

            setTimeout(() => {
                window.paymentProcessing = false;
                showTicket(data);
                triggerGlobalUpdates();
            }, 3000);

        })

        .catch(() => {

            box.innerHTML = `
                <div class="msg error">
                    Payment failed
                </div>
            `;

            btn.disabled = false;
            btn.innerHTML = "Pay Now";
            window.paymentProcessing = false;
        });

    }, 3000);
};

/* =====================================================
   SHOW TICKET
===================================================== */

window.showTicket = function(data){

    let qrSection = "";

    if((data.mode || "").toLowerCase() === "physical" && data.token){
        qrSection = `
            <img class="ticketQR"
            src="https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=${encodeURIComponent(data.token)}">
        `;
    }

    let onlineInfo = "";

    if((data.mode || "").toLowerCase() === "online" && data.meeting_link){
        onlineInfo = `
            <div class="ticketMeta" style="margin-top:10px;">
                <b>Meeting Link</b>
            </div>

            <div class="ticketMeta">
                <a href="${data.meeting_link}" target="_blank"
                style="color:#6c3bff;font-weight:700;">
                    ${data.meeting_link}
                </a>
            </div>
        `;
    }

    document.getElementById("mainCard").innerHTML = `
    
    <div class="regClose" onclick="closeModal()">×</div>

    <div class="ticketBox">

        <div class="ticketTitle">🎟 Your Ticket</div>

        ${qrSection}

        <div class="ticketMeta"><b>${data.title || "-"}</b></div>
        <div class="ticketMeta">${data.club || "-"}</div>
        <div class="ticketMeta">${data.date || "-"}</div>
        <div class="ticketMeta">${data.time || "-"}</div>
        <div class="ticketMeta">${(data.mode || "-").toUpperCase()}</div>

        ${onlineInfo}

        <hr class="ticketLine">

        <div class="ticketMeta">${data.name || "-"}</div>
        <div class="ticketMeta">${data.matric || "-"}</div>
        <div class="ticketMeta">${data.email || "-"}</div>
        <div class="ticketMeta">Token: ${data.token || "-"}</div>

        <button class="regBtn primary" style="margin-top:15px"
            onclick="location.reload()">
            Done
        </button>

    </div>
    `;
};

/* =====================================================
   CLOSE MODAL
===================================================== */

window.closeModal = function(){

    window.paymentProcessing = false;

    const main = document.getElementById("mainCard");
    if(main){
        main.style.display = "none";
    }
};