<!DOCTYPE html>
<html lang="en" style="height: auto;" class="">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="{{ asset('templates/dist/img/logo.ico') }}">
    <link rel="shortcut icon" type="image/x-icon" href="{{ asset('templates/dist/img/logo.ico') }}">
    <title>{{ config('app.app_name') }} - @yield('title')</title>
    @include('layouts.partials.styles')
    @yield('styles')
</head>

<body>

    <body class="sidebar-mini layout-fixed layout-navbar-fixed" style="height: auto;">
        <div class="wrapper">

            <div class="preloader flex-column justify-content-center align-items-center" style="height: 0px;">
                <img class="animation__shake" src="{{ asset('templates/dist/img/small-logo.png') }}" alt="Logo"
                    height="60" width="60" style="display: none;">
            </div>

            <nav class="main-header navbar navbar-expand navbar-dark bg-primary">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
                    </li>
                     <li class="nav-item">
                       {{-- periode --}}
                        <a class="nav-link" href="{{ route('dashboard.index') }}" role="button">
                            <span class="ml-2 text-white">Periode: <span id="periode"></span></span>
                        </a>
                    </li>
                </ul>

                <div class="navbar-center text-white m-auto">
                    {{-- <span id="date-time" class="font-weight-bold"></span> --}}
                </div>

                <ul class="navbar-nav" style="margin-top: 0px;">
                    <li class="nav-item dropdown" style="margin-top: 0px;">
                        <a class="nav-link" data-toggle="dropdown" href="#" role="button" data-widget="notification" style="margin-top: 0px;">
                            <i class="fas fa-bell"></i>
                            <span id="notification-dot" class="badge badge-danger" style="display: none; position: absolute; top: 8px; right: 10px; font-size: 0.6rem;"></span>
                        </a>
                        <div class="dropdown-menu dropdown-menu-xl dropdown-menu-right">
                            <div id="notification">
                                <span class="dropdown-item dropdown-header" id="notification_title">Notifications</span>
                                <div id="loading-bar" style="text-align: center; padding: 10px; display: none;">
                                    <div class="spinner-border text-primary" style="width: 2rem; height: 2rem;" role="status">
                                        <span class="sr-only">Loading...</span>
                                    </div>
                                </div>
                                <div id="notification-list"></div>
                                <div class="dropdown-divider"></div>
                                <form action="{{ route('dashboard.mark_all_read') }}" method="POST">
                                    @csrf
                                    @include('backend.layouts.partials.messages')
                                    <button type="submit" class="dropdown-item dropdown-footer" id="notification_mark">Mark all as read</button>
                                </form>
                            </div>
                        </div>
                    </li>

                    <!-- Profile Section -->
                    <li class="nav-item dropdown" title="Account Profile">
                        <a class="nav-link" data-toggle="dropdown" href="#">
                            {{ Auth::guard('admin')->user()->name }} <i class="far fa-user"></i>
                        </a>
                        @include('layouts.partials.logout')
                    </li>
                </ul>
            </nav>

            <aside class="main-sidebar elevation-1 sidebar-light-danger">

                <a href="#" class="brand-link bg-light">
                    <img src="{{ asset('templates/dist/img/logo-app.png') }}" alt="App Logo Text" class="brand-text brand-image">
                </a>

                <div
                    class="sidebar os-host os-host-overflow os-host-overflow-y os-host-resize-disabled os-host-scrollbar-horizontal-hidden os-host-transition os-theme-dark">
                    <div class="os-resize-observer-host observed">
                        <div class="os-resize-observer" style="left: 0px; right: auto;"></div>
                    </div>
                    <div class="os-size-auto-observer observed" style="height: calc(100% + 1px); float: left;">
                        <div class="os-resize-observer"></div>
                    </div>
                    <div class="os-content-glue" style="margin: 0px -8px; width: 249px; height: 676px;"></div>
                    <div class="os-padding">
                        <div class="os-viewport os-viewport-native-scrollbars-invisible" style="overflow-y: scroll;">
                            <div class="os-content" style="padding: 0px 8px; height: 100%; width: 100%;">
                                <div class="user-panel mt-3 pb-3 mb-3 d-flex align-items-center">
                                    <div class="image">
                                        <img src="{{ Avatar::create(Auth::guard('admin')->user()->name)->toBase64() }}" 
                                            class="img-circle" alt="User Image">
                                    </div>
                                    <div class="info">
                                        <a class="d-block">{{ Auth::guard('admin')->user()->name }}</a>
                                        <a class="d-block font-weight-bold" style="font-size: 11px;">
                                            {{ Auth::guard('admin')->user()->getRoleNames()[0] }}
                                        </a>
                                        @if(
                                            auth()->user()->getMyCabangAndRegion()['cabang'] != '-' &&
                                            in_array(Auth::guard('admin')->user()->getRoleNames()[0], ['Medical Representatif', 'Area Manager Cabang'])
                                        )
                                            <a class="d-block" style="font-size: 14px;">
                                                <span class="badge badge-primary">
                                                    {{ auth()->user()->getMyCabangAndRegion()['cabang'] }}
                                                </span>
                                            </a>
                                        @elseif(Auth::guard('admin')->user()->getRoleNames()[0] != 'Superadmin')
                                            <a class="d-block" style="font-size: 14px;">
                                                <span class="badge badge-primary">
                                                    Head Office
                                                </span>
                                            </a>
                                        @endif
                                        <span id="date-time" class="font-weight-bold" style="font-size: 12px;"></span>
                                    </div>
                                </div>
                                @include('layouts.partials.sidebar')
                            </div>
                        </div>
                    </div>
                    <div class="os-scrollbar os-scrollbar-horizontal os-scrollbar-unusable os-scrollbar-auto-hidden">
                        <div class="os-scrollbar-track">
                            <div class="os-scrollbar-handle" style="width: 100%; transform: translate(0px, 0px);"></div>
                        </div>
                    </div>
                    <div class="os-scrollbar os-scrollbar-vertical os-scrollbar-auto-hidden">
                        <div class="os-scrollbar-track">
                            <div class="os-scrollbar-handle" style="height: 57.5686%; transform: translate(0px, 0px);">
                            </div>
                        </div>
                    </div>
                    <div class="os-scrollbar-corner"></div>
                </div>

            </aside>

            <div class="content-wrapper" style="min-height: 677.4px;">
                @yield('admin-content')
            </div>

            @include('layouts.partials.footer')
            @include('layouts.partials.scripts')
            @yield('scripts')
    </body>
</html>

<script>
    function updateDateTime() {
        const dateTimeElement = document.getElementById('date-time');
        const now = new Date();

        const options = {
            timeZone: 'Asia/Jakarta',
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false // Use 24-hour format
        };

        dateTimeElement.textContent = new Intl.DateTimeFormat('en-US', options).format(now) + ' WIB';
    }

    // Update the clock every second
    setInterval(updateDateTime, 1000);

    // Initialize the clock on page load
    updateDateTime();

    document.querySelector('[data-widget="notification"]').addEventListener('click', function (e) {
        e.preventDefault();

        const loadingBar = document.getElementById('loading-bar');
        const notificationList = document.getElementById('notification-list');

        // Show loading bar and hide notification list
        loadingBar.style.display = 'block';
        notificationList.classList.add('d-none');

        
        fetch('/api/notifications')
            .then(response => response.json())
            .then(data => {
                notificationList.innerHTML = ''; // Clear existing notifications

                data.data.forEach(notification => {
                    const item = document.createElement('a');
                    item.href = notification.link || '#';
                    item.classList.add('dropdown-item');
                    item.dataset.notificationId = notification.id; // Store notification ID for later use

                    const notifLink = `/forms/${notification.expense_type}/view/${notification.expense_id}`;
                    item.innerHTML = `
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div style="display: flex; align-items: center;">
                                <i class="fas fa-bell" style="font-size: 16px; margin-right: 5px;"></i>
                                <strong style="font-size: 12px;">${notification.title}</strong>
                            </div>
                            <span class="text-muted text-sm" style="font-size: 12px !important;">
                                ${new Date(notification.created_at).toLocaleDateString('en-US', {
                                    year: 'numeric',
                                    month: 'short',
                                    day: 'numeric',
                                    hour: '2-digit',
                                    minute: '2-digit',
                                })}
                            </span>
                        </div>
                        <span class="text-muted text-sm" style="font-size: 12px !important;">${notification.content || ''}</span>
                    `;

                    // Add click event listener
                    item.addEventListener('click', (e) => {
                        e.preventDefault(); // Prevent default navigation
                        
                        // Call the mark_read API
                        fetch(`/api/mark_read/${notification.id}`)
                            .then(markReadResponse => {
                                if (!markReadResponse.ok) {
                                    throw new Error('Failed to mark notification as read');
                                }
                                // Optionally handle UI changes here (e.g., mark notification visually as read)
                                console.log(`Notification ${notification.id} marked as read`);
                                // Redirect to the notification link
                                window.location.href = notifLink;
                            })
                            .catch(error => {
                                console.error('Error marking notification as read:', error);
                            });
                    });

                    notificationList.appendChild(item);
                });

                // Hide loading bar and show notification list
                loadingBar.style.display = 'none';
                notificationList.classList.remove('d-none');
            })
            .catch(error => {
                console.error('Error fetching notifications:', error);
                loadingBar.style.display = 'none';
                notificationList.innerHTML = '<span class="dropdown-item text-danger">Failed to load notifications.</span>';
                notificationList.classList.remove('d-none');
            });

    });

    fetch('/api/notifications')
        .then(response => response.json())
        .then(data => {
            const notificationDot = document.getElementById('notification-dot');

            if (data.count > 0) {
                // Show red dot if there are notifications
                // show the number of notifications
                notificationDot.textContent = data.count;
                notificationDot.style.display = 'block';
            } else {
                // Hide red dot if there are no notifications
                notificationDot.style.display = 'none';
            }
        })
        .catch(error => {
            console.error('Error checking notifications:', error);
        });

    const periode = document.getElementById('periode');
    const date = new Date();

    const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    const month = months[date.getMonth()];  // Get the current month's short name
    const nextMonth = months[(date.getMonth() + 1) % 12]; // Get the next month's short name, wrapping around if necessary
    const year = date.getFullYear();

    periode.textContent = `${month} (12 ${month} - 10 ${nextMonth} ${year})`;
</script>
