<?php
add_action('wp_ajax_rm_bookmark' , 'rm_bookmark');
add_action('wp_ajax_nopriv_rm_bookmark','rm_bookmark');

function rm_bookmark() {
    // تحقق من nonce
    if (!isset($_POST['_nonce']) || !wp_verify_nonce($_POST['_nonce'], 'ds1-nonce-v')) {
        wp_send_json_error('Invalid nonce');
        wp_die();
    }

    $id     = isset($_POST['pid']) ? intval($_POST['pid']) : 0;
    $action = sanitize_text_field($_POST['bookmark_action'] ?? '');

    if (!$id || !$action) {
        wp_send_json_error('Invalid request');
    }

    // المستخدم مسجل
    if (is_user_logged_in()) {
        $meta_key = 'rmbookmark';
        $bookmarks = get_user_meta(get_current_user_id(), $meta_key, true) ?: [];

        if ($action === 'add' && !in_array($id, $bookmarks)) {
            $bookmarks[] = $id;
        } elseif ($action === 'remove' && in_array($id, $bookmarks)) {
            $bookmarks = array_diff($bookmarks, [$id]);
        }

        update_user_meta(get_current_user_id(), $meta_key, array_values($bookmarks));
        wp_send_json_success(['message' => 'Bookmark saved for user']);
    } 
    // المستخدم غير مسجل – استخدم الكوكيز
    else {
        $cookie_key = 'rmbookmark';
        $bookmark_raw = $_COOKIE[$cookie_key] ?? '';
        $bookmarks = $bookmark_raw ? explode('-', sanitize_text_field($bookmark_raw)) : [];

        $bookmarks = array_map('intval', $bookmarks);

        if ($action === 'add' && !in_array($id, $bookmarks)) {
            $bookmarks[] = $id;
        } elseif ($action === 'remove' && in_array($id, $bookmarks)) {
            $bookmarks = array_diff($bookmarks, [$id]);
        }

        // حفظ في الكوكيز
        setcookie($cookie_key, implode('-', array_values($bookmarks)), time() + (86400 * 30), "/");
        wp_send_json_success(['message' => 'Bookmark saved in cookie']);
    }
}

// Get Bookmarks and save it in user cookies to use it by js
add_action('wp', function(){
    if( !get_current_user_id() ){
        setcookie("rmbookmark", 77777, time()+(86400 * 99), "/");
    }
    
    $bookmark = get_user_meta(get_current_user_id(), 'rmbookmark', true);
    $bookmark = ($bookmark) ? implode("-",$bookmark) : '';

    setcookie("rmbookmark", $bookmark, time()+(86400 * 99), "/"); 
});


function rm_custom_get_bookmark_items() {
    if (is_user_logged_in()) {
        $bookmark = get_user_meta(get_current_user_id(), 'rmbookmark', true);
    } elseif (isset($_COOKIE['rmbookmark'])) {
        $bookmark = explode("-", sanitize_text_field($_COOKIE['rmbookmark']));
    } else {
        return [];
    }

    return array_map('intval', (array)$bookmark);
}

