<link rel="stylesheet" href="/SEAT/assets/css/organizer/message.css">

<div id="toast" class="toast"></div>

<div id="messageModal" class="modal">

    <div class="modalBox msgModal">

        <!-- HEADER -->
        <div class="msgHeader">

            <div class="headLeft">
                <div class="headIcon">📢</div>

                <div class="headText">
                    <h2>Event Message Center</h2>
                    <p>Send announcements, attachments and manage message history.</p>
                </div>
            </div>

            <button type="button"
                    class="closeBtn"
                    onclick="closeModal('messageModal')">
                ×
            </button>

        </div>

        <!-- CONTENT -->
        <div class="msgContent">

            <!-- LEFT : COMPOSE -->
            <div class="panel composePanel">

                <div class="panelHead">
                    <span class="tag green">COMPOSE</span>
                    <h3>Create New Message</h3>
                    <p>Write a clear announcement for participants.</p>
                </div>

                <div class="panelBody">

                    <textarea id="msgText"
                              placeholder="Write your message here..."></textarea>

                    <div class="uploadBox">
                        <label for="msgFile">Attachment (optional)</label>
                        <input type="file" id="msgFile">
                    </div>

                    <button type="button"
                            id="sendBtn"
                            class="sendBtn"
                            onclick="sendMsg()">

                        Send Message
                    </button>

                </div>

            </div>

            <!-- RIGHT : HISTORY -->
            <div class="panel historyPanel">

                <div class="panelHead stickyHead">
                    <span class="tag purple">HISTORY</span>
                    <h3>Previous Messages</h3>
                    <p>Latest announcements with files, images and actions.</p>
                </div>

                <div id="msgList" class="msgList">
                    Loading...
                </div>

            </div>

        </div>

    </div>

</div>

<!-- IMAGE VIEWER -->
<div id="imgViewer" class="imgViewer" onclick="closeViewer()">
    <img id="viewerImg">
</div>

<script>

window.currentEventId = null;
window.sendingNow = false;

/* OPEN MODAL */
window.openMessageModal = function(eventId){

    window.currentEventId = eventId;

    document.getElementById("messageModal").classList.add("show");

    loadMessages();
};

/* CLOSE MODAL */
window.closeModal = function(id){
    document.getElementById(id).classList.remove("show");
};

/* TOAST */
window.showToast = function(msg,type="success"){

    const t = document.getElementById("toast");
    t.innerHTML = msg;
    t.className = "toast show " + type;

    setTimeout(()=>{
        t.className = "toast " + type;
    },2400);
};

/* LOAD MESSAGES */
window.loadMessages = async function(){

    if(!window.currentEventId){
        showToast("No event selected","error");
        return;
    }

    const box = document.getElementById("msgList");
    box.innerHTML = `<div class="empty">Loading messages...</div>`;

    const form = new FormData();
    form.append("load_messages",1);
    form.append("event_id",window.currentEventId);

    try{

        const res = await fetch("/SEAT/modules/Event/organizer/event_action.php",{
            method:"POST",
            body:form
        });

        const data = await res.json();

        if(data.status !== "success"){
            box.innerHTML = `<div class="empty">Failed to load messages</div>`;
            return;
        }

        if(!data.messages || data.messages.length === 0){
            box.innerHTML = `<div class="empty">No messages yet</div>`;
            return;
        }

        box.innerHTML = data.messages.map((m,i)=>{

            let media = "";

            if(m.image){
                media = `
                <div class="msgMedia">
                    <img src="${encodeURI(m.image)}" class="msgImg"
                         onclick="openViewer('${encodeURI(m.image)}')">
                </div>`;
            }

            else if(m.file){
                media = `
                <div class="msgMedia">
                    <a href="${m.file}" target="_blank" class="fileBox">
                        📎 Download Attachment
                    </a>
                </div>`;
            }

            return `
            <div class="msgRow">

                <div class="msgTop">
                    <span class="msgIndex">#${i+1}</span>
                    <span class="msgDate">${m.created_at}</span>
                </div>

                ${media}

                <div class="msgText">${m.message}</div>

                <div class="msgFoot">
                    <button type="button"
                            class="deleteBtn"
                            onclick="deleteMsg(${m.id})">
                        Delete
                    </button>
                </div>

            </div>`;
        }).join("");

    }catch(e){
        box.innerHTML = `<div class="empty">Server error</div>`;
    }
};

/* SEND MESSAGE */
window.sendMsg = async function(){

    if(sendingNow) return;

    if(!window.currentEventId){
        showToast("No event selected","error");
        return;
    }

    const btn  = document.getElementById("sendBtn");
    const text = document.getElementById("msgText").value.trim();
    const file = document.getElementById("msgFile").files[0];

    if(!text && !file){
        showToast("Message cannot be empty","error");
        return;
    }

    sendingNow = true;
    btn.disabled = true;
    btn.innerHTML = "Sending...";

    const form = new FormData();
    form.append("send_message",1);
    form.append("event_id",window.currentEventId);
    form.append("message",text);

    if(file) form.append("attachment",file);

    try{

        const res = await fetch("/SEAT/modules/Event/organizer/event_action.php",{
            method:"POST",
            body:form
        });

        const data = await res.json();

        if(data.status === "success"){

            document.getElementById("msgText").value = "";
            document.getElementById("msgFile").value = "";

            showToast("Message sent","success");
            loadMessages();

        }else{
            showToast(data.msg || "Something went wrong","error");
        }

    }catch(e){
        showToast("Server error","error");
    }

    finally{
        btn.disabled = false;
        btn.innerHTML = "Send Message";
        sendingNow = false;
    }
};

/* DELETE MESSAGE */
window.deleteMsg = async function(id){

    if(!confirm("Delete this message?")) return;

    const form = new FormData();
    form.append("delete_message",1);
    form.append("message_id",id);

    try{

        const res = await fetch("/SEAT/modules/Event/organizer/event_action.php",{
            method:"POST",
            body:form
        });

        const data = await res.json();

        if(data.status === "success"){
            showToast("Message deleted","success");
            loadMessages();
        }else{
            showToast(data.msg || "Delete failed","error");
        }

    }catch(e){
        showToast("Server error","error");
    }
};

/* IMAGE VIEWER */
window.openViewer = function(src){
    document.getElementById("viewerImg").src = src;
    document.getElementById("imgViewer").classList.add("show");
};

window.closeViewer = function(){
    document.getElementById("imgViewer").classList.remove("show");
};

</script>