<?php
namespace GPLoker\Inc;

class Bookmark {

	private static $cookie_name = 'GPLokerBookmark';

	public static function init() {
		add_action('generate_after_footer', ['GPLoker\Inc\Bookmark', 'setCookieJs']);
	}

	public static function setCookieJs() {
		?>
		<script>
			const cookie_name = "<?php echo self::$cookie_name;?>";

            function addToCookie(id) {
                let cookieData = {};
                if (document.cookie.indexOf(cookie_name+'=') !== -1) {
                    cookieData = JSON.parse(getCookie(cookie_name));
                }
                cookieData[id] = true;
                document.cookie = `${cookie_name}=${JSON.stringify(cookieData)}; path=/`;
            }

            function removeFromCookie(id) {
                let cookieData = {};
                if (document.cookie.indexOf(cookie_name + '=') !== -1) {
                    cookieData = JSON.parse(getCookie(cookie_name));
                }

                // Hapus data ID dari cookie jika ada
                if (cookieData[id]) {
                    delete cookieData[id];
                    document.cookie = `${cookie_name}=${JSON.stringify(cookieData)}; path=/`;
                }
            }

            function getCookie(name) {
                const value = `; ${document.cookie}`;
                const parts = value.split(`; ${name}=`);
                if (parts.length === 2) return parts.pop().split(';').shift();
            }

            const bookmarkElements = document.querySelectorAll('.gploker-bookmark');

            bookmarkElements.forEach((element) => {
                element.addEventListener('click', function () {
                    const id = element.getAttribute('data-id');
                    const parentWithBmark = element.closest('.bmark');
                    if (id) {
                        
                        if (getCookie(cookie_name) && JSON.parse(getCookie(cookie_name))[id]) {
                            removeFromCookie(id);
                            parentWithBmark.classList.remove('has-bookmark');
                        } else {
                            addToCookie(id);
                            parentWithBmark.classList.add('has-bookmark');
                        }
                    }
                });
            });

		</script>
		<?php
	}

	public static function get() {

		$bookmark_ids = [];
		if ( ! empty( $_COOKIE[self::$cookie_name]) ) {
			$clean = str_replace(['\\', ':true'], '', $_COOKIE[self::$cookie_name]);
			$clean = str_replace('{', '[', $clean);
			$clean = str_replace('}', ']', $clean);
			$bookmark_ids = json_decode($clean, true);
		}

		return $bookmark_ids;
	}
}

Bookmark::init();