<?php
session_start();

if (!isset($_SESSION['session_email']) && !isset($_SESSION['session_username'])) {
    header("Location: login.php");
    exit();
}
?>


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="apple-touch-icon" sizes="76x76" href="assets/img/apple-icon.png">
    <link rel="icon" type="image/png" href="img/logo.png">
    <title>
        KAS REMBAS
    </title>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet" />
    <link href="https://demos.creative-tim.com/argon-dashboard-pro/assets/css/nucleo-icons.css" rel="stylesheet" />
    <link href="https://demos.creative-tim.com/argon-dashboard-pro/assets/css/nucleo-svg.css" rel="stylesheet" />
    <script src="https://kit.fontawesome.com/42d5adcbca.js" crossorigin="anonymous"></script>
    <link id="pagestyle" href="assets/css/argon-dashboard.css?v=2.1.0" rel="stylesheet" />
    <link id="pagestyle" href="assets/css/styletable.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/2.0.8/css/dataTables.dataTables.min.css">

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/3.0.2/css/buttons.dataTables.min.css">


</head>

<body class="g-sidenav-show bg-gray-100">
    <div class="min-height-300 bg-purple position-absolute w-100"></div>
    <?php require 'pages/navbar.php'; ?>
    <?php require 'pages/sidebar.php'; ?>
    <?php include 'controller.php'; ?>

    <div class="fixed-plugin">
        <div class="card shadow-lg">
            <div class="card-header pb-0 pt-3 ">
                <div class="float-start">
                    <h5 class="mt-3 mb-0">SETTING TAMPILAN </h5>
                </div>
                <div class="float-end mt-4">
                    <button class="btn btn-link text-dark p-0 fixed-plugin-close-button">
                        <i class="fa fa-close"></i>
                    </button>
                </div>
            </div>
            <hr class="horizontal dark my-1">
            <div class="card-body pt-sm-3 pt-0 overflow-auto">
                <div>
                    <h6 class="mb-0">Warna Menu</h6>
                </div>
                <a href="javascript:void(0)" class="switch-trigger background-color">
                    <div class="badge-colors my-2 text-start">
                        <span class="badge filter bg-gradient-primary" data-color="primary" onclick="sidebarColor(this)" id="color-primary"></span>
                        <span class="badge filter bg-gradient-dark" data-color="dark" onclick="sidebarColor(this)" id="color-dark"></span>
                        <span class="badge filter bg-gradient-info" data-color="info" onclick="sidebarColor(this)" id="color-info"></span>
                        <span class="badge filter bg-gradient-success" data-color="success" onclick="sidebarColor(this)" id="color-success"></span>
                        <span class="badge filter bg-gradient-warning" data-color="warning" onclick="sidebarColor(this)" id="color-warning"></span>
                        <span class="badge filter bg-gradient-danger" data-color="danger" onclick="sidebarColor(this)" id="color-danger"></span>
                    </div>
                </a>
                <div class="mt-3">
                    <h6 class="mb-0">Pilih Warna Kotak Menu</h6>
                </div>
                <div class="d-flex">
                    <button class="btn bg-gradient-primary w-100 px-3 mb-2 me-2" data-class="bg-white" onclick="sidebarType(this)" id="type-white">White</button>
                    <button class="btn bg-gradient-primary w-100 px-3 mb-2" data-class="bg-default" onclick="sidebarType(this)" id="type-dark">Dark</button>
                </div>
                <p class="text-sm d-xl-none d-block mt-2">You can change the sidenav type just on desktop view.</p>
                <div class="d-flex my-3">
                    <h6 class="mb-0">Navbar Fixed</h6>
                    <div class="form-check form-switch ps-0 ms-auto my-auto">
                        <input class="form-check-input mt-1 ms-auto" type="checkbox" id="navbarFixedToggle" onclick="navbarFixed(this)">
                    </div>
                </div>
                <hr class="horizontal dark my-sm-4">
                <div class="mt-2 mb-5 d-flex">
                    <h6 class="mb-0">Light / Dark</h6>
                    <div class="form-check form-switch ps-0 ms-auto my-auto">
                        <input class="form-check-input mt-1 ms-auto" type="checkbox" id="darkModeToggle" onclick="darkMode(this)">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="assets/js/core/popper.min.js"></script>
    <script src="assets/js/core/bootstrap.min.js"></script>
    <script src="assets/js/plugins/perfect-scrollbar.min.js"></script>
    <script src="assets/js/plugins/smooth-scrollbar.min.js"></script>
    <script src="assets/js/plugins/chartjs.min.js"></script>
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <script src="assets/js/argon-dashboard.min.js?v=2.1.0"></script>


    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/2.0.8/js/dataTables.min.js"></script>

    <script type="text/javascript" src="https://cdn.datatables.net/buttons/3.0.2/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/buttons/3.0.2/js/buttons.html5.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/buttons/3.0.2/js/buttons.print.min.js"></script>
    <script>
        $(document).ready(function() {
            var pageTitle = $('h5.page-title').clone().find('.page-title-icon').remove().end().text().trim() || "Data Tabel";

            // Deteksi kolom
            var totalColumns = $('#DataTable thead th').length;
            var lastTh = $('#DataTable thead th').last();
            var excludeLast = lastTh.hasClass('aksi');
            var exportCols = [];
            for (var i = 0; i < totalColumns - (excludeLast ? 1 : 0); i++) {
                exportCols.push(i);
            }

            $('#DataTable').DataTable({
                language: {
                    url: "assets/js/i18n/id.json"
                },
                layout: {
                    topStart: {
                        buttons: [{
                                extend: 'copyHtml5',
                                text: '<i class="bi bi-clipboard-fill"></i> Salin',
                                className: 'btn btn-outline-secondary btn-sm',
                                filename: pageTitle,
                                exportOptions: {
                                    columns: exportCols
                                }
                            },
                            {
                                extend: 'excelHtml5',
                                text: '<i class="bi bi-file-earmark-excel-fill"></i> Excel',
                                className: 'btn btn-outline-success btn-sm',
                                filename: pageTitle,
                                exportOptions: {
                                    columns: exportCols
                                }
                            },
                            {
                                extend: 'pdfHtml5',
                                text: '<i class="bi bi-file-earmark-pdf-fill"></i> PDF',
                                className: 'btn btn-outline-danger btn-sm',
                                orientation: 'portrait',
                                pageSize: 'A4',
                                filename: pageTitle,
                                exportOptions: {
                                    columns: exportCols
                                }
                            },
                            {
                                extend: 'print',
                                text: '<i class="bi bi-printer-fill"></i> Cetak',
                                className: 'btn btn-outline-info btn-sm',
                                filename: pageTitle,
                                exportOptions: {
                                    columns: exportCols
                                }
                            }
                        ]
                    }
                },
                columnDefs: [{
                        orderable: false,
                        targets: excludeLast ? [totalColumns - 1] : []
                    },
                    {
                        searchable: false,
                        targets: excludeLast ? [totalColumns - 1] : []
                    }
                ]
            });
        });
    </script>

    <style>
        /* CSS untuk memperbesar ikon di tombol DataTables */
        .dataTables_wrapper .dt-buttons .btn .icon-big {
            font-size: 1.2em;
            vertical-align: middle;
            margin-right: 5px;
        }

        /* Opsional: Styling tambahan jika Anda ingin tombolnya terlihat lebih "keren" secara keseluruhan */
        .dataTables_wrapper .dt-buttons .btn {
            transition: all 0.3s ease;
        }

        .dataTables_wrapper .dt-buttons .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
    </style>
    <script>
        // Fungsi untuk menandai menu aktif berdasarkan URL
        function setMenuActive() {
            console.log("setMenuActive is running");
            document.querySelectorAll('.nav-link').forEach(link => {
                link.classList.remove('active');
                let parentCollapse = link.closest('.collapse');
                if (parentCollapse) {
                    parentCollapse.classList.remove('show');
                    let parentNavLink = parentCollapse.previousElementSibling;
                    if (parentNavLink && parentNavLink.classList.contains('nav-link')) {
                        parentNavLink.setAttribute('aria-expanded', 'false');
                    }
                }
            });

            const currentPathSegment = window.location.pathname.split('/').pop();

            document.querySelectorAll('.nav-link').forEach(link => {
                const linkHref = link.getAttribute('href');
                const linkHrefSegment = linkHref.split('/').pop();

                if (currentPathSegment === linkHrefSegment ||
                    (currentPathSegment === '' && linkHrefSegment === 'dashboard_perbulan') ||
                    (currentPathSegment === 'index.php' && linkHrefSegment === 'dashboard_perbulan')) {
                    link.classList.add('active');

                    let parentCollapse = link.closest('.collapse');
                    if (parentCollapse) {
                        parentCollapse.classList.add('show');
                        let parentNavLink = parentCollapse.previousElementSibling;
                        if (parentNavLink && parentNavLink.classList.contains('nav-link')) {
                            parentNavLink.classList.add('active');
                            parentNavLink.setAttribute('aria-expanded', 'true');
                        }
                    }
                }
            });
        }

        // --- Fungsi untuk mengelola persisten tema ---

        // Fungsi sidebarColor: Hanya simpan ke localStorage dan atur active class pada tombol pengaturan
        window.sidebarColor = function(el) {
            const selectedColor = el.getAttribute('data-color');
            localStorage.setItem('sidebarColor', selectedColor);
            console.log("sidebarColor set in localStorage:", selectedColor);

            // Perbarui tampilan di panel pengaturan
            document.querySelectorAll('.badge-colors .badge.filter').forEach(span => {
                span.classList.remove('active');
            });
            el.classList.add('active');

            // Penerapan warna sidebar secara visual akan dilakukan oleh applySavedTheme()
            // Kita bisa memanggilnya di sini untuk update instan tanpa menunggu reload.
            applySavedTheme();
            setTimeout(setMenuActive, 150); // Panggil setMenuActive setelah update tema
        };

        // Fungsi sidebarType: Hanya simpan ke localStorage dan atur active class pada tombol pengaturan
        window.sidebarType = function(el) {
            const selectedType = el.getAttribute('data-class');
            localStorage.setItem('sidebarType', selectedType);
            console.log("sidebarType set in localStorage:", selectedType);

            // Perbarui tampilan di panel pengaturan
            document.querySelectorAll('.d-flex .btn[onclick="sidebarType(this)"]').forEach(btn => {
                btn.classList.remove('active');
            });
            el.classList.add('active');

            // Penerapan jenis sidebar secara visual akan dilakukan oleh applySavedTheme()
            // Kita bisa memanggilnya di sini untuk update instan tanpa menunggu reload.
            applySavedTheme();
            setTimeout(setMenuActive, 150); // Panggil setMenuActive setelah update tema
        };

        // Fungsi darkMode: Simpan ke localStorage dan langsung terapkan class pada body
        window.darkMode = function(el) {
            if (el.checked) {
                localStorage.setItem('themeMode', 'dark');
                document.body.classList.add('dark-version');
                console.log("Dark Mode set to: dark");
            } else {
                localStorage.setItem('themeMode', 'light');
                document.body.classList.remove('dark-version');
                console.log("Dark Mode set to: light");
            }
            // Optional: call setMenuActive if dark mode changes anything related to menu visibility (unlikely for Argon)
        };

        // Fungsi navbarFixed: Simpan ke localStorage dan langsung terapkan class pada body
        window.navbarFixed = function(el) {
            if (el.checked) {
                localStorage.setItem('navbarFixed', 'true');
                document.body.classList.add('navbar-fixed');
                console.log("Navbar Fixed set to: true");
            } else {
                localStorage.setItem('navbarFixed', 'false');
                document.body.classList.remove('navbar-fixed');
                console.log("Navbar Fixed set to: false");
            }
        };

        // --- FUNGSI UNTUK MENGATUR TINGGI SIDEBAR ---
        function setSidenavHeight() {
            console.log("setSidenavHeight is running");
            const sidenavMain = document.getElementById('sidenav-main');
            if (sidenavMain) {
                const sidenavHeader = sidenavMain.querySelector('.sidenav-header');
                const sidenavHeaderHeight = sidenavHeader ? sidenavHeader.offsetHeight : 0;

                const sidenavHr = sidenavMain.querySelector('hr.horizontal.dark');
                const sidenavHrHeight = sidenavHr ? sidenavHr.offsetHeight : 0;
                const sidenavHrMargin = sidenavHr ? parseFloat(getComputedStyle(sidenavHr).marginTop) + parseFloat(getComputedStyle(sidenavHr).marginBottom) : 0;


                const sidenavFooter = sidenavMain.querySelector('.sidenav-footer');
                const sidenavFooterHeight = sidenavFooter ? sidenavFooter.offsetHeight : 0;
                const sidenavFooterMargin = sidenavFooter ? parseFloat(getComputedStyle(sidenavFooter).marginTop) + parseFloat(getComputedStyle(sidenavFooter).marginBottom) : 0;

                const topOffset = 16; // Margin-top from aside.sidenav (my-3)
                const bottomOffset = 16; // Margin-bottom from aside.sidenav (my-3)
                const totalVerticalPadding = topOffset + bottomOffset;

                const availableHeight = window.innerHeight - totalVerticalPadding;

                const collapseMain = document.getElementById('sidenav-collapse-main');
                if (collapseMain) {
                    const calculatedHeight = availableHeight - sidenavHeaderHeight - sidenavHrHeight - sidenavHrMargin - sidenavFooterHeight - sidenavFooterMargin;
                    collapseMain.style.maxHeight = `${Math.max(0, calculatedHeight)}px`;
                    collapseMain.style.overflowY = 'auto';
                    collapseMain.style.overflowX = 'hidden';
                }

                // Perbarui perfect-scrollbar jika digunakan
                if (window.PerfectScrollbar) {
                    const scrollbarElement = document.getElementById('sidenav-scrollbar');
                    if (scrollbarElement) {
                        // Check if PerfectScrollbar or SmoothScrollbar is initialized
                        if (scrollbarElement._ps_) { // For PerfectScrollbar
                            PerfectScrollbar.update(scrollbarElement);
                        } else if (typeof Scrollbar !== 'undefined' && Scrollbar.get(scrollbarElement)) { // For SmoothScrollbar
                            Scrollbar.get(scrollbarElement).update();
                        }
                    }
                }
            }
        }


        // Fungsi untuk menerapkan pengaturan yang tersimpan saat halaman dimuat
        function applySavedTheme() {
            console.log("applySavedTheme is running");
            const savedColor = localStorage.getItem('sidebarColor'); // e.g., 'primary', 'dark'
            const savedType = localStorage.getItem('sidebarType'); // e.g., 'bg-white', 'bg-default'
            const savedThemeMode = localStorage.getItem('themeMode'); // 'dark', 'light'
            const savedNavbarFixed = localStorage.getItem('navbarFixed'); // 'true', 'false'

            const sidenav = document.querySelector(".sidenav");
            const body = document.body;

            // --- Apply sidebar color (Primary, Dark, Info, etc.) ---
            if (savedColor && sidenav) {
                sidenav.setAttribute("data-color", savedColor);
                console.log("Applying sidebarColor:", savedColor);
                document.querySelectorAll('.badge-colors .badge.filter').forEach(span => {
                    span.classList.remove('active');
                });
                const targetColorSpan = document.querySelector(`.badge-colors .badge.filter[data-color="${savedColor}"]`);
                if (targetColorSpan) {
                    targetColorSpan.classList.add('active');
                }
            } else if (sidenav) {
                // Default to 'primary' if no saved color, and set active button
                sidenav.setAttribute("data-color", "primary");
                console.log("Defaulting sidebarColor to: primary");
                const defaultColorSpan = document.getElementById('color-primary');
                if (defaultColorSpan) {
                    defaultColorSpan.classList.add('active');
                }
            }


            // --- Apply sidebar type (White/Dark background of the sidebar) ---
            if (savedType && sidenav) {
                sidenav.classList.remove('bg-white', 'bg-default'); // Remove all possible sidebar type classes
                sidenav.classList.add(savedType); // Add the saved sidebar type class
                console.log("Applying sidebarType:", savedType);

                // Ensure the correct button in the settings panel is active
                document.querySelectorAll('.d-flex .btn[onclick="sidebarType(this)"]').forEach(btn => {
                    btn.classList.remove('active');
                });
                const targetTypeButton = document.querySelector(`.d-flex .btn[data-class="${savedType}"]`);
                if (targetTypeButton) {
                    targetTypeButton.classList.add('active');
                }
            } else if (sidenav) {
                // Default to 'bg-white' if no saved type, and set active button
                sidenav.classList.remove('bg-default'); // Ensure default is not bg-default
                sidenav.classList.add('bg-white');
                console.log("Defaulting sidebarType to: bg-white");
                const defaultTypeButton = document.getElementById('type-white');
                if (defaultTypeButton) {
                    defaultTypeButton.classList.add('active');
                }
            }

            // --- Apply overall Dark/Light Mode ---
            const darkModeToggle = document.getElementById('darkModeToggle');
            if (darkModeToggle && body) {
                if (savedThemeMode === 'dark') {
                    body.classList.add('dark-version');
                    darkModeToggle.checked = true;
                    console.log("applySavedTheme: Setting Dark Mode");
                } else {
                    body.classList.remove('dark-version');
                    darkModeToggle.checked = false;
                    console.log("applySavedTheme: Setting Light Mode");
                }
            }

            // --- Apply Navbar Fixed ---
            const navbarFixedToggle = document.getElementById('navbarFixedToggle');
            if (navbarFixedToggle && body) {
                if (savedNavbarFixed === 'true') {
                    body.classList.add('navbar-fixed');
                    navbarFixedToggle.checked = true;
                    console.log("applySavedTheme: Setting Navbar Fixed");
                } else {
                    body.classList.remove('navbar-fixed');
                    navbarFixedToggle.checked = false;
                    console.log("applySavedTheme: Setting Navbar Not Fixed");
                }
            }

            // Trigger PerfectScrollbar update after all DOM manipulations
            if (window.PerfectScrollbar) {
                const scrollbarElement = document.getElementById('sidenav-scrollbar');
                if (scrollbarElement && (scrollbarElement._ps_ || (typeof Scrollbar !== 'undefined' && Scrollbar.get(scrollbarElement)))) {
                    console.log("Updating PerfectScrollbar");
                    if (scrollbarElement._ps_) {
                        PerfectScrollbar.update(scrollbarElement);
                    } else if (typeof Scrollbar !== 'undefined' && Scrollbar.get(scrollbarElement)) {
                        Scrollbar.get(scrollbarElement).update();
                    }
                }
            }
        }


        // ** Initial setup on DOMContentLoaded **
        document.addEventListener('DOMContentLoaded', function() {
            setMenuActive(); // Set active menu links early
            // Apply saved theme settings shortly after DOM content is loaded
            // This allows basic Argon Dashboard scripts to run, then we override.
            // A short delay gives it a chance to initialize.
            setTimeout(function() {
                applySavedTheme();
                setSidenavHeight(); // Ensure height is calculated after theme is applied
                console.log("applySavedTheme called from DOMContentLoaded setTimeout");
            }, 200); // Increased delay slightly
        });

        // ** Final override on window.onload **
        // This will run AFTER all scripts (including argon-dashboard.min.js) are loaded and executed,
        // ensuring our theme settings are applied last and persist.
        window.addEventListener('load', function() {
            applySavedTheme();
            setSidenavHeight(); // Re-calculate height after final theme application
            console.log("applySavedTheme called from window.load");
        });


        // Panggil juga setSidenavHeight saat ukuran window berubah
        window.addEventListener('resize', setSidenavHeight);
    </script>
</body>

</html>