<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly

/**
 * WooCommerce Wishlist Functions
 *
 * NOTE: Database operations (table creation, data storage) have been moved to
 * the Matcha Extra plugin per WordPress.org theme review requirements.
 * Themes should not create custom database tables or store user data.
 *
 * The theme provides UI helper functions that defer to the plugin when available.
 *
 * @package pawfect
 */

// Check if Matcha Extra wishlist functionality is available
function pawfect_wishlist_available() {
    return function_exists('matcha_get_wishlist_items');
}

// Get wishlist page URL - Use Matcha Extra if available
function pawfect_get_wishlist_url() {
    if (function_exists('matcha_get_wishlist_url')) {
        return matcha_get_wishlist_url();
    }

    // First try to get the actual page by path
    $wishlist_page = get_page_by_path('wishlist');
    if ($wishlist_page) {
        return get_permalink($wishlist_page->ID);
    }

    // Check if we have a page with title "My Wishlist" using WP_Query (get_page_by_title is deprecated)
    $query = new WP_Query(array(
        'post_type'      => 'page',
        'title'          => 'My Wishlist',
        'posts_per_page' => 1,
        'post_status'    => 'publish',
        'no_found_rows'  => true,
    ));
    
    if ($query->have_posts()) {
        $wishlist_page = $query->posts[0];
        wp_reset_postdata();
        return get_permalink($wishlist_page->ID);
    }
    wp_reset_postdata();

    // Try "Wishlist" title
    $query = new WP_Query(array(
        'post_type'      => 'page',
        'title'          => 'Wishlist',
        'posts_per_page' => 1,
        'post_status'    => 'publish',
        'no_found_rows'  => true,
    ));
    
    if ($query->have_posts()) {
        $wishlist_page = $query->posts[0];
        wp_reset_postdata();
        return get_permalink($wishlist_page->ID);
    }
    wp_reset_postdata();

    // Fallback to custom URL
    return home_url('/wishlist/');
}

// Flush rewrite rules on theme activation
add_action('after_switch_theme', 'pawfect_flush_wishlist_rules');
function pawfect_flush_wishlist_rules() {
    flush_rewrite_rules();
}

/**
 * WISHLIST DATABASE OPERATIONS MOVED TO MATCHA EXTRA PLUGIN
 *
 * Per WordPress.org theme review requirements, the following functionality
 * has been moved to the Matcha Extra plugin:
 * - Database table creation (pawfect_wishlist table)
 * - Direct database queries for add/remove/get wishlist items
 * - User data storage
 *
 * The theme now only provides UI helpers that defer to the plugin.
 * Install Matcha Extra for full wishlist functionality.
 */

// Get user's wishlist items - Use Matcha Extra if available
function pawfect_get_wishlist_items($user_id = null) {
    // Defer to Matcha Extra plugin for database operations
    if (function_exists('matcha_get_wishlist_items')) {
        return matcha_get_wishlist_items($user_id);
    }

    // If Matcha Extra is not available, only support guest wishlist via cookies
    // Database operations require the plugin
    if (!$user_id) {
        $user_id = get_current_user_id();
    }

    if (!$user_id) {
        // For non-logged-in users, use session/cookies
        return pawfect_get_guest_wishlist();
    }

    // For logged-in users without plugin, return empty (plugin required)
    return array();
}

// Get guest wishlist from session/cookies
function pawfect_get_guest_wishlist() {
    if (isset($_COOKIE['pawfect_wishlist'])) {
        $wishlist = json_decode(sanitize_text_field(wp_unslash($_COOKIE['pawfect_wishlist'])), true);
        return is_array($wishlist) ? array_map('absint', $wishlist) : array();
    }
    return array();
}

// Set guest wishlist cookie
function pawfect_set_guest_wishlist($wishlist) {
    $sanitized = array_map('absint', (array) $wishlist);
    setcookie('pawfect_wishlist', wp_json_encode($sanitized), time() + (86400 * 30), '/');
}

// Add product to wishlist
function pawfect_add_to_wishlist($product_id, $user_id = null) {
    // Defer to Matcha Extra plugin for database operations
    if (function_exists('matcha_add_to_wishlist')) {
        return matcha_add_to_wishlist($product_id, $user_id);
    }

    if (!$user_id) {
        $user_id = get_current_user_id();
    }
    
    if (!$user_id) {
        // Handle guest users with cookies
        $wishlist = pawfect_get_guest_wishlist();
        $product_id = absint($product_id);
        if (!in_array($product_id, $wishlist, true)) {
            $wishlist[] = $product_id;
            pawfect_set_guest_wishlist($wishlist);
        }
        return true;
    }
    
    // For logged-in users, plugin is required
    return false;
}

// Remove product from wishlist
function pawfect_remove_from_wishlist($product_id, $user_id = null) {
    // Defer to Matcha Extra plugin for database operations
    if (function_exists('matcha_remove_from_wishlist')) {
        return matcha_remove_from_wishlist($product_id, $user_id);
    }

    if (!$user_id) {
        $user_id = get_current_user_id();
    }
    
    if (!$user_id) {
        // Handle guest users with cookies
        $wishlist = pawfect_get_guest_wishlist();
        $product_id = absint($product_id);
        $wishlist = array_diff($wishlist, array($product_id));
        pawfect_set_guest_wishlist($wishlist);
        return true;
    }
    
    // For logged-in users, plugin is required
    return false;
}

// Check if product is in wishlist
function pawfect_is_in_wishlist($product_id, $user_id = null) {
    $wishlist_items = pawfect_get_wishlist_items($user_id);
    return in_array($product_id, $wishlist_items);
}

// Get wishlist count - Use Matcha Extra if available
function pawfect_get_wishlist_count($user_id = null) {
    if (function_exists('matcha_get_wishlist_count')) {
        return matcha_get_wishlist_count($user_id);
    }
    $wishlist_items = pawfect_get_wishlist_items($user_id);
    return count($wishlist_items);
}

// AJAX handler for adding/removing wishlist items - Disabled, using Matcha Extra handler
// add_action('wp_ajax_pawfect_toggle_wishlist', 'pawfect_toggle_wishlist_ajax');
// add_action('wp_ajax_nopriv_pawfect_toggle_wishlist', 'pawfect_toggle_wishlist_ajax');

function pawfect_toggle_wishlist_ajax() {
    // Check if WooCommerce is active
    if (!class_exists('WooCommerce')) {
        wp_send_json_error('WooCommerce not available');
        return;
    }

    check_ajax_referer('pawfect_wishlist_nonce', 'nonce');

    $product_id = intval( wp_unslash( $_POST['product_id'] ) );
    $action = sanitize_text_field( wp_unslash( $_POST['wishlist_action'] ) ); // 'add' or 'remove'
    
    if (!$product_id) {
        wp_send_json_error('Invalid product ID');
        return;
    }
    
    $success = false;
    $message = '';
    
    if ($action === 'add') {
        $success = pawfect_add_to_wishlist($product_id);
        $message = $success ? __('Added to wishlist', 'pawfect') : __('Failed to add to wishlist', 'pawfect');
    } elseif ($action === 'remove') {
        $success = pawfect_remove_from_wishlist($product_id);
        $message = $success ? __('Removed from wishlist', 'pawfect') : __('Failed to remove from wishlist', 'pawfect');
    }
    
    if ($success) {
        wp_send_json_success(array(
            'message' => $message,
            'wishlist_count' => pawfect_get_wishlist_count(),
            'is_in_wishlist' => pawfect_is_in_wishlist($product_id)
        ));
    } else {
        wp_send_json_error($message);
    }
}

// Generate wishlist button HTML
function pawfect_get_wishlist_button($product_id, $classes = '') {
    $is_in_wishlist = pawfect_is_in_wishlist($product_id);
    $heart_class = $is_in_wishlist ? 'pawfect-wishlist-active' : '';
    $title = $is_in_wishlist ? __('Remove from wishlist', 'pawfect') : __('Add to wishlist', 'pawfect');
    
    return sprintf(
        '<button class="pawfect-wishlist-btn %s %s" data-product-id="%d" title="%s" aria-label="%s">
            <svg class="pawfect-w-5 pawfect-h-5 pawfect-transition-all pawfect-duration-300" fill="%s" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
            </svg>
        </button>',
        esc_attr($classes),
        esc_attr($heart_class),
        esc_attr($product_id),
        esc_attr($title),
        esc_attr($title),
        $is_in_wishlist ? 'currentColor' : 'none'
    );
}

// Enqueue wishlist scripts
add_action('wp_enqueue_scripts', 'pawfect_enqueue_wishlist_scripts');

function pawfect_enqueue_wishlist_scripts() {
    wp_localize_script('pawfect-main', 'pawfect_wishlist', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('pawfect_wishlist_nonce'),
        'add_text' => __('Add to wishlist', 'pawfect'),
        'remove_text' => __('Remove from wishlist', 'pawfect'),
        'added_text' => __('Added to wishlist!', 'pawfect'),
        'removed_text' => __('Removed from wishlist!', 'pawfect')
    ));
}

// Add wishlist button to product loops (only for themes that don't have it in template)
// Commented out since we're adding it directly in the product template
// add_action('woocommerce_after_shop_loop_item', 'pawfect_add_wishlist_button_to_loop', 15);

function pawfect_add_wishlist_button_to_loop() {
    global $product;

    if (!$product) return;

    echo '<div class="pawfect-wishlist-wrapper pawfect-absolute pawfect-top-3 pawfect-right-3 pawfect-z-10">';
    echo wp_kses_post( pawfect_get_wishlist_button($product->get_id(), 'pawfect-bg-white pawfect-bg-opacity-90 pawfect-backdrop-blur-sm pawfect-rounded-full pawfect-p-2 pawfect-shadow-md hover:pawfect-bg-opacity-100 pawfect-text-gray-600 hover:pawfect-text-red-500') );
    echo '</div>';
}

// Add wishlist button to single product page
add_action('woocommerce_single_product_summary', 'pawfect_add_wishlist_button_single', 35);

function pawfect_add_wishlist_button_single() {
    global $product;
    
    if (!$product) return;
    
    echo '<div class="pawfect-single-wishlist pawfect-mt-4">';
    echo wp_kses_post( pawfect_get_wishlist_button($product->get_id(), 'pawfect-inline-flex pawfect-items-center pawfect-gap-2 pawfect-px-4 pawfect-py-2 pawfect-border pawfect-border-gray-300 pawfect-rounded-lg pawfect-text-gray-700 hover:pawfect-text-red-500 hover:pawfect-border-red-300 pawfect-transition-colors') );
    echo '<span class="pawfect-wishlist-text pawfect-text-sm pawfect-font-medium">' . esc_html( pawfect_is_in_wishlist($product->get_id()) ? __('Remove from wishlist', 'pawfect') : __('Add to wishlist', 'pawfect') ) . '</span>';
    echo '</div>';
}
