<?php

require_once BASE_PATH . '/app/helpers/Authorization.php';
require_once BASE_PATH . '/app/models/Notification.php';
require_once BASE_PATH . '/app/models/ShopSetting.php';


/*
|--------------------------------------------------------------------------
| Trang Owner đang active
|--------------------------------------------------------------------------
*/

$activeOwnerPage = $activeOwnerPage ?? '';


/*
|--------------------------------------------------------------------------
| Thông báo chưa đọc của Owner
|--------------------------------------------------------------------------
*/

$ownerUnreadNotificationCount = 0;

try {
    $ownerUnreadNotificationCount =
        (new Notification())->countUnreadByUser(
            (int) ($_SESSION['user']['id'] ?? 0)
        );
} catch (Throwable $e) {
    $ownerUnreadNotificationCount = 0;
}


/*
|--------------------------------------------------------------------------
| Lấy thông tin Spa từ Owner → Cài đặt
|--------------------------------------------------------------------------
*/

$ownerShopName = 'PET SPA';
$ownerShopLogo = '';

try {

    $shopSettings = (new ShopSetting())->get();

    /*
     * Tên Spa
     */
    $ownerShopName = trim(
        (string) ($shopSettings['shop_name'] ?? '')
    );

    if ($ownerShopName === '') {
        $ownerShopName = 'PET SPA';
    }


    /*
     * Logo Spa
     */
    $ownerShopLogo = trim(
        (string) ($shopSettings['logo'] ?? '')
    );

} catch (Throwable $e) {

    $ownerShopName = 'PET SPA';
    $ownerShopLogo = '';
}


/*
|--------------------------------------------------------------------------
| Menu Owner
|--------------------------------------------------------------------------
*/

$ownerMenuItems = [

    [
        'key' => 'dashboard',
        'permission' => 'owner.dashboard',
        'route' => 'owner',
        'icon' => 'bi-speedometer2',
        'label' => 'Tổng quan'
    ],

    [
        'key' => 'bookings',
        'permission' => 'owner.booking.manage',
        'route' => 'owner/bookings',
        'icon' => 'bi-calendar-check',
        'label' => 'Lịch hẹn'
    ],

    [
        'key' => 'services',
        'permission' => 'owner.service.manage',
        'route' => 'owner/services',
        'icon' => 'bi-scissors',
        'label' => 'Dịch vụ'
    ],

    [
        'key' => 'service-categories',
        'permission' => 'owner.service_category.manage',
        'route' => 'owner/service-categories',
        'icon' => 'bi-tags',
        'label' => 'Danh mục dịch vụ'
    ],

    [
        'key' => 'schedule',
        'permission' => 'owner.business_hours.manage',
        'route' => 'owner/schedule',
        'icon' => 'bi-clock-history',
        'label' => 'Giờ phục vụ'
    ],

    [
        'key' => 'customers',
        'permission' => 'owner.customer.view',
        'route' => 'owner/customers',
        'icon' => 'bi-people',
        'label' => 'Khách hàng'
    ],

    [
        'key' => 'posts',
        'permission' => 'owner.post.manage',
        'route' => 'owner/posts',
        'icon' => 'bi-file-earmark-text',
        'label' => 'Bài viết'
    ],

    [
        'key' => 'post-categories',
        'permission' => 'owner.post_category.manage',
        'route' => 'owner/post-categories',
        'icon' => 'bi-folder',
        'label' => 'Danh mục bài viết'
    ],

    [
        'key' => 'gallery',
        'permission' => 'owner.gallery.manage',
        'route' => 'owner/gallery',
        'icon' => 'bi-images',
        'label' => 'Thư viện'
    ],

    [
        'key' => 'contacts',
        'permission' => 'owner.contact.manage',
        'route' => 'owner/contacts',
        'icon' => 'bi-chat-left-text',
        'label' => 'Liên hệ'
    ],

    [
        'key' => 'notifications',
        'permission' => 'owner.notification.view',
        'route' => 'owner/notifications',
        'icon' => 'bi-bell',
        'label' => 'Thông báo'
    ],

    [
        'key' => 'settings',
        'permission' => 'owner.settings.manage',
        'route' => 'owner/settings',
        'icon' => 'bi-gear',
        'label' => 'Cài đặt'
    ]

];

?>


<aside class="owner-sidebar">

    <!-- =====================================================
         THÔNG TIN SPA
    ====================================================== -->

    <div class="owner-sidebar-brand">

        <!-- Logo / Icon -->
        <div class="owner-shop-icon">

            <?php if ($ownerShopLogo !== ''): ?>

                <img
                    src="<?= BASE_URL ?>/<?= htmlspecialchars(
                        ltrim($ownerShopLogo, '/')
                    ) ?>"
                    alt="<?= htmlspecialchars($ownerShopName) ?>"
                >

            <?php else: ?>

                <i class="bi bi-heart-pulse"></i>

            <?php endif; ?>

        </div>


        <!-- Tên Spa -->
        <div class="owner-shop-info">

            <small>
                Quản lý
            </small>

            <strong title="<?= htmlspecialchars($ownerShopName) ?>">
                <?= htmlspecialchars($ownerShopName) ?>
            </strong>

        </div>


        <!-- Mobile menu button -->
        <button
            class="sidebar-toggle"
            type="button"
            aria-label="Mở menu quản lý"
            aria-expanded="false"
        >
            <i class="bi bi-list"></i>
        </button>

    </div>


    <!-- =====================================================
         MENU OWNER
    ====================================================== -->

    <nav
        class="owner-menu"
        aria-label="Menu quản lý Spa"
    >

        <?php foreach ($ownerMenuItems as $item): ?>

            <?php if (can($item['permission'])): ?>

                <a
                    class="<?= $activeOwnerPage === $item['key']
                        ? 'active'
                        : '' ?>"
                    href="<?= BASE_URL ?>/?url=<?= htmlspecialchars(
                        $item['route']
                    ) ?>"
                >

                    <i
                        class="bi <?= htmlspecialchars(
                            $item['icon']
                        ) ?>"
                    ></i>


                    <span>
                        <?= htmlspecialchars($item['label']) ?>
                    </span>


                    <!-- Badge thông báo -->
                    <?php if (
    $item['key'] === 'notifications'
): ?>

    <span
        id="ownerNotificationBadge"
        class="badge text-bg-danger ms-auto"
        style="<?= $ownerUnreadNotificationCount > 0
            ? ''
            : 'display:none;' ?>"
    >
        <?= (int) $ownerUnreadNotificationCount ?>
    </span>

<?php endif; ?>

                </a>

            <?php endif; ?>

        <?php endforeach; ?>


        <!-- =================================================
             ĐĂNG XUẤT
        ================================================== -->

        <form
            method="post"
            action="<?= BASE_URL ?>/?url=logout"
        >

            <input
                type="hidden"
                name="_token"
                value="<?= htmlspecialchars(
                    $_SESSION['csrf_token'] ?? ''
                ) ?>"
            >


            <button
                class="owner-menu-logout"
                type="submit"
            >

                <i class="bi bi-box-arrow-right"></i>

                <span>
                    Đăng xuất
                </span>

            </button>

        </form>

    </nav>
<script>
document.addEventListener('DOMContentLoaded', function () {

    const POLL_TIME = 5000; // 5 giây

    const popup =
        document.getElementById('ownerNotificationPopup');

    const popupTitle =
        document.getElementById('ownerPopupTitle');

    const popupMessage =
        document.getElementById('ownerPopupMessage');

    const popupLink =
        document.getElementById('ownerPopupLink');

    const popupClose =
        document.getElementById('ownerPopupClose');

    const badge =
        document.getElementById('ownerNotificationBadge');
    const navbarBadge =
    document.getElementById('ownerNavbarNotificationBadge');

    if (!popup) {
        return;
    }

const storageKey =
    'petSpaOwnerLastNotificationId';

const storedNotificationId =
    sessionStorage.getItem(storageKey);

let lastNotificationId =
    storedNotificationId === null
        ? null
        : parseInt(storedNotificationId, 10);

let popupTimer = null;


    /*
    |--------------------------------------------------------------------------
    | Hiện popup
    |--------------------------------------------------------------------------
    */

    function showPopup(notification) {

        popup.hidden = false;

        popupTitle.textContent =
            notification.title
            || 'Có thông báo mới';


        popupMessage.textContent =
            notification.message
            || 'Bạn có một thông báo mới.';


        let link =
            notification.link
            || '?url=owner/notifications';


        if (link.startsWith('?')) {

            link =
                <?= json_encode(BASE_URL) ?>
                + '/'
                + link;

        }


        popupLink.href = link;


        popup.classList.add('show');


        clearTimeout(popupTimer);


        /*
         * Tự tắt sau 10 giây
         */
        popupTimer =
            setTimeout(function () {

                popup.classList.remove('show');
                popup.hidden = true;

            }, 10000);

    }


    /*
    |--------------------------------------------------------------------------
    | Badge sidebar
    |--------------------------------------------------------------------------
    */

    function updateBadge(count) {

    count =
        parseInt(count || 0, 10);


    /* Badge sidebar */

    if (badge) {

        if (count > 0) {

            badge.textContent = count;
            badge.style.display = 'inline-flex';

        } else {

            badge.style.display = 'none';

        }

    }


    /* Badge chuông navbar */

    if (navbarBadge) {

        if (count > 0) {

            navbarBadge.textContent = count;
            navbarBadge.style.display = 'flex';

        } else {

            navbarBadge.style.display = 'none';

        }

    }
}

    /*
    |--------------------------------------------------------------------------
    | Kiểm tra thông báo
    |--------------------------------------------------------------------------
    */

    async function checkNotifications() {

        try {

            const response =
                await fetch(
                    <?= json_encode(
                        BASE_URL
                        . '/?url=owner/notifications/poll'
                    ) ?>,
                    {
                        method: 'GET',

                        headers: {
                            'Accept': 'application/json'
                        },

                        cache: 'no-store',

                        credentials: 'same-origin'
                    }
                );


            if (!response.ok) {
                return;
            }


            const data =
                await response.json();


            if (!data.success) {
                return;
            }


            /*
             * Update badge
             */
            updateBadge(
                data.unread_count
            );


            const notifications =
                Array.isArray(
                    data.notifications
                )
                    ? data.notifications
                    : [];


            if (
                notifications.length === 0
            ) {
                return;
            }


            /*
             * Notification mới nhất
             */
            const newest =
                notifications[0];


            const newestId =
                parseInt(
                    newest.id || 0,
                    10
                );


            /*
             * Lần đầu mở trang:
             *
             * chỉ ghi nhớ ID,
             * không popup notification cũ.
             */
            if (
                lastNotificationId === null
            ) {

                lastNotificationId = newestId;

                sessionStorage.setItem(
                    storageKey,
                    String(newestId)
                );

                return;
            }


            /*
             * Có notification mới
             */
           if (
    newestId > lastNotificationId
) {

    lastNotificationId =
        newestId;

    sessionStorage.setItem(
        storageKey,
        String(newestId)
    );

    showPopup(newest);
}


        } catch (error) {

            console.log(
                'Không thể kiểm tra thông báo.'
            );

        }

    }


    /*
    |--------------------------------------------------------------------------
    | Đóng popup
    |--------------------------------------------------------------------------
    */

    popupClose.addEventListener(
        'click',
        function () {

            popup.classList.remove(
                'show'
            );

            popup.hidden = true;

        }
    );


    /*
    |--------------------------------------------------------------------------
    | Chạy lần đầu
    |--------------------------------------------------------------------------
    */

    checkNotifications();


    /*
    |--------------------------------------------------------------------------
    | Sau đó kiểm tra mỗi 30 giây
    |--------------------------------------------------------------------------
    */

    setInterval(
        checkNotifications,
        POLL_TIME
    );

});
</script>
<!-- POPUP THÔNG BÁO OWNER -->
<div
    id="ownerNotificationPopup"
    class="owner-notification-popup"
    hidden
    aria-live="polite"
    aria-atomic="true"
>
    <div class="owner-notification-popup__icon">
        <i class="bi bi-bell-fill"></i>
    </div>

    <div class="owner-notification-popup__content">

        <small>Thông báo mới</small>

        <strong id="ownerPopupTitle">
            Có thông báo mới
        </strong>

        <p id="ownerPopupMessage"></p>

        <a
            id="ownerPopupLink"
            href="#"
        >
            Xem ngay
            <i class="bi bi-arrow-right"></i>
        </a>

    </div>

    <button
        type="button"
        id="ownerPopupClose"
        class="owner-notification-popup__close"
        aria-label="Đóng"
    >
        <i class="bi bi-x-lg"></i>
    </button>
</div>
</aside>