<?php

add_action('wp_enqueue_scripts', 'enqueue_wishlist_ajax');
function enqueue_wishlist_ajax() {
    wp_enqueue_script('wishlist-ajax', get_template_directory_uri() . '/inoby-plugins/wishlist/assets/wishlist.js', array('jquery'), '1.0', true);

    wp_localize_script('wishlist-ajax', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
    ));
}

add_action('wp_ajax_add_to_wishlist', 'add_to_wishlist');
add_action('wp_ajax_nopriv_add_to_wishlist', 'add_to_wishlist');
add_action('wp_ajax_remove_from_wishlist', 'remove_from_wishlist');
add_action('wp_ajax_nopriv_remove_from_wishlist', 'remove_from_wishlist');

function add_to_wishlist() {
    $product_id = intval($_POST['product_id']);
    $current_user = wp_get_current_user();
    $wishlist = get_user_meta($current_user->ID, 'wishlist', true);

    if (!is_array($wishlist)) {
        $wishlist = array();
    }

    if (!in_array($product_id, $wishlist)) {
        $wishlist[] = $product_id;
        update_user_meta($current_user->ID, 'wishlist', $wishlist);
    }
    wp_send_json_success('Produkt bol pridaný do Wishlistu.');
}

function remove_from_wishlist() {
    $product_id = intval($_POST['product_id']);
    $current_user = wp_get_current_user();
    $wishlist = get_user_meta($current_user->ID, 'wishlist', true);

    if (($key = array_search($product_id, $wishlist)) !== false) {
        unset($wishlist[$key]);
        update_user_meta($current_user->ID, 'wishlist', $wishlist);
    }
    wp_send_json_success('Produkt bol odstránený z Wishlistu.');
}