<!DOCTYPE html>
<html lang="id">
<!--begin::Head-->

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <!-- Default values (akan diubah JS) -->
    <title>Loading...</title>
    <meta name="description" content="Memuat data toko..." />

    <!-- Favicon default -->
    <link id="dynamic-favicon" rel="icon" href="icons/logo_placeholder.png" type="image/png" />

    <!-- OG Meta default -->
    <meta property="og:title" content="Loading..." />
    <meta property="og:description" content="Memuat data toko..." />
    <meta property="og:type" content="website" />
    <meta property="og:url" content="" />
    <meta property="og:image" content="icons/logo_placeholder.png" />
    <meta property="og:site_name" content="Aplikasi Toko" />

    <!-- Twitter Meta -->
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="Loading..." />
    <meta name="twitter:description" content="Memuat data toko..." />
    <meta name="twitter:image" content="icons/logo_placeholder.png" />

    <?php include_once("assets/addon/icon_css.php"); ?>
</head>
<!--end::Head-->
<!--begin::Custom Style-->
<style>
    .hover-elevate:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
        transition: all 0.2s ease-in-out;
    }
</style>
<!--end::Custom Style-->
<!--begin::Body-->

<body id="kt_body" class="header-extended header-fixed header-tablet-and-mobile-fixed">

    <!--begin::Main-->
    <!--begin::Root-->
    <div class="d-flex flex-column flex-root">
        <!--begin::Page-->
        <div class="page d-flex flex-row flex-column-fluid">
            <!--begin::Wrapper-->
            <div class="wrapper d-flex flex-column flex-row-fluid" id="kt_wrapper">
                <!--begin::Header-->
                <?php include_once("assets/addon/header.php"); ?>
                <!--end::Header-->




                <!--begin::Container-->
                <div id="kt_content_container" class="d-flex flex-column-fluid align-items-start container-xxl">
                    <!--begin::Post-->
                    <div class="content flex-row-fluid" id="kt_content">

                        <!--begin::Breadcrumb-->
                        <div id="breadcrumb_container"></div>
                        <!--end::Breadcrumb-->

                        <!--begin::Row-->
                        <div class="row g-5 mb-5" id="formSection">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h4 class="fw-bold mb-0">Ubah Password</h4>
                            </div>

                            <div class="col-12">
                                <div class="card shadow-sm border-0">
                                    <div class="card-body p-8">

                                        <form id="form_data" enctype="multipart/form-data">

                                            <!-- Hidden -->
                                            <input type="hidden" name="IDUser" />

                                            <div class="row g-5">

                                                <!-- Username -->
                                                <div class="col-md-6">
                                                    <label class="form-label fw-semibold required">
                                                        Username
                                                    </label>

                                                    <input type="text" class="form-control form-control-solid"
                                                        name="Username" readonly required />
                                                </div>

                                                <!-- NamaLengkap -->
                                                <div class="col-12">
                                                    <label class="form-label fw-semibold required">
                                                        Nama Lengkap
                                                    </label>

                                                    <input type="text" class="form-control" name="NamaLengkap"
                                                        required />
                                                </div>

                                                <!-- Email -->
                                                <div class="col-12">
                                                    <label class="form-label fw-semibold">
                                                        Email
                                                    </label>

                                                    <input type="email" class="form-control" name="Email" />
                                                </div>

                                                <!-- NoHP -->
                                                <div class="col-12">
                                                    <label class="form-label fw-semibold">
                                                        Nomor HP
                                                    </label>

                                                    <input type="text" class="form-control" name="NoHP" />
                                                </div>

                                                <!-- Avatar -->
                                                <div class="row mb-3">
                                                    <div class="col-md-6">
                                                        <label class="form-label fw-semibold">Avatar</label>
                                                        <input type="file" class="form-control" id="Avatar"
                                                            name="Avatar" accept="image/*" />
                                                        <div class="mt-2">
                                                            <img id="AvatarPreview" src="#" alt="Preview"
                                                                style="display:none; max-width: 150px;" />
                                                        </div>
                                                    </div>
                                                </div>

                                            </div>

                                            <!-- Action -->
                                            <div class="d-flex justify-content-end gap-3 mt-8">

                                                <button type="button"
                                                    class="btn btn-light btn-active-light-primary btn-cancel">
                                                    Batal
                                                </button>

                                                <button type="submit" class="btn btn-primary">
                                                    <i class="fa-solid fa-floppy-disk me-1"></i>
                                                    Simpan
                                                </button>

                                            </div>

                                        </form>

                                    </div>
                                </div>
                            </div>
                        </div>
                        <!--end::Row-->



                        <!--begin::Row-->
                        <div class="row g-5 mb-5 d-none" id="detail_section">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h4 class="fw-bold mb-0">Detail Data</h4>
                            </div>

                            <div class="col-12">
                                <div id="data_detail"></div>
                            </div>
                        </div>
                        <!--end::Row-->





                    </div>
                    <!--end::Post-->
                </div>
                <!--end::Container-->

                <!--begin::Footer-->
                <?php include_once("assets/addon/footer.php"); ?>
                <!--end::Footer-->

            </div>
            <!--end::Wrapper-->
        </div>
        <!--end::Page-->


    </div>
    <!--end::Root-->

    <!--end::Main-->


    <!--begin::Javascript-->
    <!--begin::Global Javascript Bundle(mandatory for all pages)-->
    <?php include_once 'assets/addon/scripts.php'; ?>
    <?php
    $active_namespaces = ['login', 'header', 'generic'];
    include_once 'locales/init.php';
    ?>

    <!--begin::Global Javascript Bundle(mandatory for all pages)-->
    <!--end::Global Javascript Bundle-->

    <!--begin::Vendors Javascript(used for this page only)-->
    <script src="assets/plugins/custom/datatables/datatables.bundle.js"></script>
    <!--end::Vendors Javascript-->

    <!--begin::Custom Javascript(used for this page only)-->
    <script type="module">
        import { checkSession, toggleContentOverlay, updateHeaderUser } from './modules/session.js';
        import { getActiveUser } from './col_script/essential/user_helper.js';
        import { setLocales_textContent, initDynamicLanguageHandler } from './col_script/common/locales_helper.js';
        import {
            q_setVisibility, q_setText, q_isValidDatetime, q_setDateTimeToFormat, q_updateMetaData, q_setOptionData,
            q_initFormSubmit, q_getURLParameter, q_fillFormData, q_generateViewContent
        } from './col_script/common/qol.js';
        import { fetch_helper } from "./col_script/common/fetch_helper.js";
        import { generateDatatableHTML } from "./col_script/common/datatable_html.js";
        import { initDatatable } from "./col_script/common/datatable_helper.js";
        import { setBreadcrumb } from "./col_script/common/router_helper.js";


        let AksesUtama = "User";
        let main_pk = "user";
        let DetailSection = document.getElementById(`detail_section`);
        let sumberPath = "m_change_password.php";

        const alert_nolink = document.getElementById("alert_nolink");

        // --- Image Preview ---
        const imageInput = document.getElementById("Avatar");
        const preview = document.getElementById("AvatarPreview");


        if (imageInput && preview) {
            imageInput.addEventListener("change", () => {
                const file = imageInput.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        preview.src = e.target.result;
                        preview.style.display = "block";
                    };
                    reader.readAsDataURL(file);
                } else {
                    preview.src = "";
                    preview.style.display = "none";
                }
            });
        }

        // 🧩 Kumpulan semua elemen dashboard
        const elDashboard = {

        };


        async function init(listU, listA) {

            const aksesNames = listA.map(a => a.AksesName);


            setBreadcrumb("#breadcrumb_container", ["Dashboard", "User"]);


            load(listU.IDUser, listA);
        }

        async function load(id, listA) {

            try {
                const formData = new URLSearchParams();
                formData.append("p_type", main_pk);
                formData.append("p_action", "select");

                const currentFilters = [];
                currentFilters.push(["IDUser", id, 1]);
                formData.append("filters", JSON.stringify(currentFilters));


                const { result } = await fetch_helper({
                    i18nKey: "", // ganti jika key i18next-nya berbeda
                    fetchFile: "",
                    formData: formData,
                });


                if (result.Status == 1) {

                    console.log(result);

                    if (result.list_data && result.list_data.length > 0) {
                        launcher(listA, result.list_data[0]);
                    } else {
                        throw new Error("Data Kosong");
                    }

                } else {
                    throw new Error(result.Keterangan);
                }

            } catch (error) {
                Swal.fire({
                    title: i18next.t(error.message),
                    icon: "error",
                    allowEscapeKey: false,
                    allowOutsideClick: false,
                    showCancelButton: false,
                    confirmButtonText: "OK",
                    didOpen: function () {
                        Swal.getPopup().style.zIndex = "10000";
                    },
                    didClose: function () {
                        window.location.href = "index.php";
                    },
                });
            }


        }


        async function launcher(listA, listData = null) {



            const formData = new URLSearchParams();
            formData.append("p_type", "launcher");
            formData.append("p_action", "select");

            formData.append("getPerusahaan", "1");


            const { result } = await fetch_helper({
                i18nKey: "", // ganti jika key i18next-nya berbeda
                fetchFile: "",
                formData: formData,
            });


            if (result.Status == 1) {

                let URL_BASE = "attachments/perusahaan/";
                if (result.listPerusahaan && result.listPerusahaan.length > 0) {
                    let listData = result.listPerusahaan[0];
                    const items = result.listPerusahaan;
                    items.forEach((item) => {


                        const nama = item.NamaPerusahaan || "Perusahaan Tanpa Nama";
                        const deskripsi = "Input " + AksesUtama;
                        const logo = item.Logo ? `${URL_BASE}${item.Logo}` : "icons/logo_palceholder.png";

                        const elLogo = document.querySelector('[data-header-element="logo"]');
                        if (elLogo) {
                            elLogo.src = logo; // ganti path logo di sini
                        }

                        q_updateMetaData({
                            title: `${deskripsi} – ${nama}`,
                            description: deskripsi,
                            image: logo,
                            favicon: logo,
                            url: window.location.href,
                        });

                    });

                    const aksesNames = listA.map(a => a.AksesName);

                }

                if (listData != null) {
                    let basePath = "attachments/user/" + listData.IDUser + "/";
                    const aksesNames = listA.map(a => a.AksesName);
                    let formDataSection = document.getElementById(`formSection`);
                    q_setVisibility(formDataSection, true);
                    q_fillFormData("#form_data", listData, basePath);


                    q_setVisibility(DetailSection, true);
                    const shownData = [
                        {
                            columnName: "Avatar",
                            displayedName: "Avatar",
                            dataType: "image",
                            displayedValue: { path: basePath, width: 80, height: 80 },
                        },
                        {
                            columnName: "Username",
                            dataType: "string",
                            displayedValue: (v) => `<span class="fw-bold text-primary">${v}</span>`,
                        },
                        {
                            columnName: "NamaLengkap",
                            displayedName: "Nama Lengkap",
                        },
                        {
                            columnName: "Email",
                        },
                        {
                            columnName: "NoHP",
                            displayedName: "Nomor HP",
                        },
                        {
                            columnName: "LastPasswordUpdateBy",
                        },
                        {
                            columnName: "LastPasswordUpdateAt",
                            dataType: "datetime",
                            displayedValue: { format: "dd/MM/yyyy HH:mm" },
                        },
                        {
                            columnName: "LastUpdateBy",
                        },
                        {
                            columnName: "LastUpdateAt",
                            dataType: "datetime",
                            displayedValue: { format: "dd/MM/yyyy HH:mm" },
                        },
                    ];

                    q_generateViewContent("#data_detail", listData, shownData);

                }



            } else {
                Swal.fire({
                    text: i18next.t(result.Keterangan),
                    icon: "error",
                    buttonsStyling: false,
                    confirmButtonText: "Ok, got it!",
                    customClass: { confirmButton: "btn btn-primary" },
                });
            }
        }

        // ----------------------
        // START INSERT
        // ----------------------
        const callback = async () => {
            // Contoh redirect setelah sukses
            window.location.reload();
        };
        q_initFormSubmit("#form_data", main_pk, "update_profile", callback, sumberPath);
        // ----------------------
        // END INSERT
        // ----------------------

        KTUtil.onDOMContentLoaded(function () {
            window.onI18nReadyCallbacks = window.onI18nReadyCallbacks || [];
            if (window.i18nReady) {
                starting();
            } else {
                window.onI18nReadyCallbacks.push(starting());
            }
        });

        async function starting() {
            console.log("dashboard - i18n ready");


            let ses_res = null;

            try {
                const res = await checkSession(true);
                if (res?.Status === 1) {
                    ses_res = res;
                }
            } catch (err) {
                console.warn("checkSession failed:", err);
            }

            // === Jika session valid ===
            if (ses_res) {
                console.log("Session valid:", ses_res);
                updateHeaderUser(ses_res.listU || {}, ses_res.listA || {});
                // === Bagian inisialisasi umum ===
                initDynamicLanguageHandler(["header", "generic"]);
                toggleContentOverlay("off");
                init(ses_res.listU || {}, ses_res.listA || {});
            }
        }




    </script>



    <!--end::Custom Javascript-->
    <!--end::Javascript-->
</body>
<!--end::Body-->


</html>