<!-- =====================================================
     EDIT EVENT MODAL (FINAL FIXED VERSION)
===================================================== -->

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

    <div class="modalBox">

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

            <div>
                <h3>Edit Event</h3>
                <p class="sub">Update event details</p>
            </div>

            <span class="closeBtn" onclick="closeModal('editModal')">
                ×
            </span>

        </div>

        <!-- FORM -->
        <form id="editForm" class="formGrid" enctype="multipart/form-data">

            <input type="hidden" name="event_id" id="edit_id">

            <!-- POSTER -->
            <div class="formGroup full">

                <img id="editPosterPreview"
                     class="posterPreview"
                     style="display:none;">

                <label>Change Poster</label>

                <input type="file"
                       name="poster"
                       accept="image/*"
                       onchange="previewEditPoster(event)">
            </div>

            <!-- TITLE -->
            <div class="formGroup full">

                <label>Event Title</label>

                <input type="text"
                       name="title"
                       id="edit_title"
                       required>
            </div>

            <!-- DATE -->
            <div class="formGroup">

                <label>Date</label>

                <input type="date"
                       name="event_date"
                       id="edit_date"
                       required>
            </div>

            <!-- MODE -->
            <div class="formGroup">

                <label>Mode</label>

                <select name="mode"
                        id="edit_mode"
                        onchange="toggleEditMode()">

                    <option value="Physical">Physical</option>
                    <option value="Online">Online</option>

                </select>
            </div>

            <!-- START -->
            <div class="formGroup">

                <label>Start Time</label>

                <input type="time"
                       name="start_time"
                       id="edit_start"
                       required>
            </div>

            <!-- END -->
            <div class="formGroup">

                <label>End Time</label>

                <input type="time"
                       name="end_time"
                       id="edit_end"
                       required>
            </div>

            <!-- VENUE -->
            <div class="formGroup full" id="edit_venue_box">

                <label>Venue</label>

                <input type="text"
                       name="venue"
                       id="edit_venue">
            </div>

            <!-- MEETING -->
            <div class="formGroup full"
                 id="edit_meeting_box"
                 style="display:none;">

                <label>Meeting Link</label>

                <input type="text"
                       name="meeting_link"
                       id="edit_meeting">
            </div>

            <!-- FEE -->
            <div class="formGroup full feeRow">

                <div class="feeCol">

                    <label>Fee Type</label>

                    <select name="fee_type"
                            id="edit_fee_type"
                            onchange="toggleEditFee()">

                        <option value="Free">Free</option>
                        <option value="Paid">Paid</option>

                    </select>

                </div>

                <div class="feeCol"
                     id="edit_fee_box"
                     style="display:none;">

                    <label>Amount (RM)</label>

                    <!-- FIXED INPUT -->
                    <input type="text"
                           name="fee_amount"
                           id="edit_fee"
                           inputmode="decimal"
                           placeholder="0.00">
                </div>

            </div>

            <!-- SLOT -->
            <div class="formGroup full">

                <label>Max Participants</label>

                <input type="number"
                       name="max_participant"
                       id="edit_max"
                       min="0">
            </div>

            <!-- BUTTON -->
            <div class="modalBtn full">

                <button type="button"
                        class="cancel"
                        onclick="closeModal('editModal')">

                    Cancel
                </button>

                <button type="submit"
                        class="create">

                    Save Changes
                </button>

            </div>

        </form>

    </div>

</div>

<script>
/* =====================================================
   EDIT EVENT MODAL FULL JS (FINAL VERSION)
===================================================== */

document.addEventListener("DOMContentLoaded", function () {

    /* =================================================
       ELEMENTS
    ================================================= */
    const form = document.getElementById("editForm");
    const feeInput = document.getElementById("edit_fee");

    /* =================================================
       2 DECIMAL VALIDATION (SAFE)
    ================================================= */
    if (feeInput) {

        feeInput.addEventListener("input", function () {

            let value = this.value;

            // allow only numbers + dot
            if (!/^\d*\.?\d*$/.test(value)) {
                this.value = value.slice(0, -1);
                return;
            }

            // limit to 2 decimal places
            if (value.includes(".")) {

                let parts = value.split(".");

                if (parts[1] && parts[1].length > 2) {
                    this.value = parts[0] + "." + parts[1].substring(0, 2);
                }
            }
        });
    }

    /* =================================================
       SUBMIT FORM
    ================================================= */
    if (form) {

        form.addEventListener("submit", async function (e) {

            e.preventDefault();

            let f = new FormData(form);
            f.append("edit_event", 1);

            try {

                let data = await postJSON("event_action.php", f);

                showToast(data.msg, data.status);

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

                    setTimeout(() => {
                        location.reload();
                    }, 1200);
                }

            } catch (err) {

                showToast("Request failed", "error");
                console.error(err);
            }
        });
    }

});

/* =====================================================
   OPEN EDIT MODAL
===================================================== */
function openEditModal(ev) {

    openModal("editModal");

    document.getElementById("edit_id").value = ev.id;
    document.getElementById("edit_title").value = ev.title;
    document.getElementById("edit_date").value = ev.event_date;
    document.getElementById("edit_start").value = ev.start_time;
    document.getElementById("edit_end").value = ev.end_time;
    document.getElementById("edit_mode").value = ev.mode;
    document.getElementById("edit_fee_type").value = ev.fee_type;
    document.getElementById("edit_fee").value = ev.fee_amount;
    document.getElementById("edit_max").value = ev.max_participant;

    if (ev.mode === "Online") {

        document.getElementById("edit_meeting").value = ev.meeting_link || "";
        document.getElementById("edit_venue").value = "";

    } else {

        document.getElementById("edit_venue").value = ev.venue || "";
        document.getElementById("edit_meeting").value = "";
    }

    const img = document.getElementById("editPosterPreview");

    if (ev.poster) {
        img.src = "/SEAT/uploads/event_posters/" + ev.poster;
        img.style.display = "block";
    } else {
        img.style.display = "none";
    }

    toggleEditMode();
    toggleEditFee();
}

/* =====================================================
   MODE TOGGLE
===================================================== */
function toggleEditMode() {

    const mode = document.getElementById("edit_mode").value;

    const venue = document.getElementById("edit_venue_box");
    const meeting = document.getElementById("edit_meeting_box");

    if (mode === "Online") {
        venue.style.display = "none";
        meeting.style.display = "block";
    } else {
        venue.style.display = "block";
        meeting.style.display = "none";
    }
}

/* =====================================================
   FEE TOGGLE
===================================================== */
function toggleEditFee() {

    const fee = document.getElementById("edit_fee_type").value;
    const box = document.getElementById("edit_fee_box");

    box.style.display = (fee === "Paid") ? "block" : "none";
}

/* =====================================================
   POSTER PREVIEW
===================================================== */
function previewEditPoster(event) {

    const file = event.target.files[0];
    const preview = document.getElementById("editPosterPreview");

    if (!file) return;

    const reader = new FileReader();

    reader.onload = function (e) {
        preview.src = e.target.result;
        preview.style.display = "block";
    };

    reader.readAsDataURL(file);
}
</script>