<!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 - Menu Shortcut-->
                        <div class="row g-5">

                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h4 class="fw-bold mb-0">Daftar Slides</h4>
                            </div>

                            <div class="col-12">

                                <div class="card shadow-sm border-0">
                                    <div class="card-body py-5">



                                        <div id="data_table"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!--end::Row - Menu Shortcut-->

                    </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_generateListErrorMessage } from './col_script/common/qol.js';
        import { fetch_helper } from "./col_script/common/fetch_helper.js";
        import { getDeviceInfo, getSafeLocalStorageItem, setSafeLocalStorageItem, removeSafeLocalStorageItem } from './col_script/common/device_info.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";
        import DataTable from './modules/DataTable.js';


        const alert_nolink = document.getElementById("alert_nolink");
        let pageName = "Slides";

        // 🧩 Kumpulan semua elemen dashboard
        const elDashboard = {

        };



        async function load(listU, listA) {

            let AksesNeeded = "Slides.View";
            const aksesNames = listA.map(a => a.AksesName);
            if (!aksesNames.includes(AksesNeeded)) {
                showUnauthorizedAlert(AksesNeeded);
                return;
            }

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

            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) {

                if (result.listPerusahaan && result.listPerusahaan.length > 0) {
                    const items = result.listPerusahaan;
                    items.forEach((item) => {

                        let URL_BASE = "attachments/perusahaan";
                        const nama = item.NamaPerusahaan || "Perusahaan Tanpa Nama";
                        const deskripsi = pageName;
                        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,
                        });

                    });
                }

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


        async function initDt() {
            // === Konfigurasi Display Columns ===
            const displayColumns = [
                { columnName: "IDSlides", displayedName: "ID", isShown: false, dataType: "numeric" },
                { columnName: "header", displayedName: "Header", dataType: "text" },
                { columnName: "description", displayedName: "Description", dataType: "text" },
                {
                    columnName: "StatusSlides",
                    displayedName: "Status",
                    dataType: "boolean",
                    booleanFormat: {
                        true: '<span class="badge text-bg-success">Aktif</span>',
                        false: '<span class="badge text-bg-danger">Non Aktif</span>'
                    }
                },
                {
                    columnName: "Image",
                    displayedName: "Image",
                    dataType: "image",
                    imageParameter: {
                        type: 'box',
                        height: 40,
                        width: 40,
                        urlPath: 'attachments/slides',
                        canZoom: true
                    }
                },
                {
                    columnName: "HideHeaderText",
                    displayedName: "Header Text",
                    dataType: "boolean",
                    booleanFormat: {
                        true: '<span class="badge text-bg-secondary">Hidden</span>',
                        false: '<span class="badge text-bg-primary">Shown</span>'
                    }
                },
                {
                    columnName: "HideDescriptionText",
                    displayedName: "Description Text",
                    dataType: "boolean",
                    booleanFormat: {
                        true: '<span class="badge text-bg-secondary">Hidden</span>',
                        false: '<span class="badge text-bg-primary">Shown</span>'
                    }
                },
                { columnName: "CreateBy", dataType: "text" },
                { columnName: "CreateAt", dataType: "datetime", dateFormat: "dd-MM-yyyy HH:mm:ss" },
                { columnName: "LastUpdateBy", dataType: "text" },
                { columnName: "LastUpdateAt", dataType: "datetime", dateFormat: "dd-MM-yyyy HH:mm:ss" },
            ];

            // === Konfigurasi Filter ===
            const filterConfigs = [
                {
                    key: "StatusSlides",
                    label: "Status Slides",
                    type: "options",
                    options: [
                        { display: "Semua", value: "" },
                        { display: "Active", value: "1" },
                        { display: "Non Active", value: "0" },
                    ]
                }
            ];

            // === Action Buttons ===
            const actionButtons = [
                {
                    buttonType: 'View',
                    actionType: 'Redirect',
                    URLPath: 'm_slides_add.php',
                    ColumnSendForURL: [
                        { columnName: 'IDSlides', paramName: 'id' },
                    ],
                    label: 'Detail'
                },
                {
                    key: 'delete',
                    buttonType: 'Delete',
                    actionType: 'Callback',
                    callbackFunction: async (row) => {
                        console.log("Delete callback for row:", row);
                        const result = await Swal.fire({
                            text: `Yakin ingin menghapus data ${row.header || row.description}?`,
                            icon: 'warning',
                            showCancelButton: true,
                            confirmButtonText: 'Ya, Hapus',
                            cancelButtonText: 'Batal',
                        });

                        if (result.isConfirmed) {
                            const formData = new URLSearchParams();
                            formData.append("p_type", "slides");
                            formData.append("p_action", "delete");
                            formData.append("IDSlides", row.IDSlides);

                            const { result: deleteResult } = await fetch_helper({
                                formData: formData,
                            });

                            await q_generateListErrorMessage(deleteResult, [
                                { display: "Nama Slides", value: "header" },
                                { display: "Keterangan", value: "Keterangan" },
                            ]);

                            if (deleteResult.Status === 1) {
                                dtInstance.loadData();
                            }
                        }
                    }
                }
            ];

            // === Bulk Actions ===
            const bulkActions = [
                {
                    key: 'delete_multiple',
                    label: 'Hapus Terpilih',
                    icon: 'fa-trash',
                    confirm: 'Yakin ingin menghapus data terpilih?',
                    callback: async (selectedData, selectedIds) => {
                        const formData = new URLSearchParams();
                        formData.append("p_type", "slides");
                        formData.append("p_action", "delete");
                        formData.append("IDSlides", selectedIds.join(','));

                        const { result: deleteResult } = await fetch_helper({ formData });

                        await q_generateListErrorMessage(deleteResult, [
                            { display: "Nama Slides", value: "header" },
                            { display: "Keterangan", value: "Keterangan" },
                        ]);

                        if (deleteResult.Status === 1) {
                            dtInstance.loadData();
                        }
                    }
                }
            ];

            // === Inisialisasi DataTable ===
            const formData = new URLSearchParams();
            formData.append("p_type", "slides");
            formData.append("p_action", "select");

            const dtInstance = new DataTable({
                containerId: 'data_table',
                formData: formData,
                displayColumns: displayColumns,
                filterConfigs: filterConfigs,
                actionButtons: actionButtons,
                bulkActions: bulkActions,
                orderColumnList: [
                    { display: 'Header', columnName: 'header' },
                    { display: 'Description', columnName: 'description' },
                    { display: 'Status', columnName: 'StatusSlides' },
                ],
                rowSelection: {
                    enabled: true,
                    rowKey: 'IDSlides',
                },
                fetchHelper: fetch_helper,
                onAddNew: () => {
                    window.location.href = 'm_slides_add.php';
                },
                addNewLabel: 'Tambah Slides',
                defaultRowsPerPage: 25,
                rowsPerPageOptions: [10, 25, 50, 100, 250, 500],
                exportOptions: {
                    copy: true,
                    csv: true,
                    excel: true,
                    pdf: false,
                },
                allowFilter: true,
                allowOrder: true,
                allowPaging: true,
                allowExport: true,
            });

            // === Render dan Load Data ===
            dtInstance.render();

            // Action dari row
            document.addEventListener('datatable:action', (e) => {
                const { action, rowId } = e.detail;
                console.log(`Action ${action} on row ${rowId}`);
            });
        }


        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");
                load(ses_res.listU || {}, ses_res.listA || {});
            }
        }






    </script>



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


</html>