<?php
namespace WooNooW\Frontend;

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use WooNooW\Core\ModuleRegistry;

class WishlistController {
    
    /**
     * Register REST API routes
     */
    public static function register_routes() {
        $namespace = 'woonoow/v1';
        
        // Get wishlist
        register_rest_route($namespace, '/account/wishlist', [
            'methods'             => 'GET',
            'callback'            => [__CLASS__, 'get_wishlist'],
            'permission_callback' => [__CLASS__, 'check_permission'],
        ]);
        
        // Add to wishlist
        register_rest_route($namespace, '/account/wishlist', [
            'methods'             => 'POST',
            'callback'            => [__CLASS__, 'add_to_wishlist'],
            'permission_callback' => [__CLASS__, 'check_permission'],
            'args'                => [
                'product_id' => [
                    'required'          => true,
                    'type'              => 'integer',
                    'sanitize_callback' => 'absint',
                ],
            ],
        ]);
        
        // Remove from wishlist
        register_rest_route($namespace, '/account/wishlist/(?P<product_id>\d+)', [
            'methods'             => 'DELETE',
            'callback'            => [__CLASS__, 'remove_from_wishlist'],
            'permission_callback' => [__CLASS__, 'check_permission'],
        ]);
        
        // Clear wishlist
        register_rest_route($namespace, '/account/wishlist/clear', [
            'methods'             => 'POST',
            'callback'            => [__CLASS__, 'clear_wishlist'],
            'permission_callback' => [__CLASS__, 'check_permission'],
        ]);
    }
    
    /**
     * Check if user is logged in OR guest wishlist is enabled
     */
    public static function check_permission() {
        // Allow if logged in
        if (is_user_logged_in()) {
            return true;
        }
        
        // Check if guest wishlist is enabled
        $settings = get_option('woonoow_module_wishlist_settings', []);
        $enable_guest = $settings['enable_guest_wishlist'] ?? true;
        
        return $enable_guest;
    }
    
    /**
     * Get wishlist items with product details
     */
    public static function get_wishlist(WP_REST_Request $request) {
        if (!ModuleRegistry::is_enabled('wishlist')) {
            return new WP_Error('module_disabled', __('Wishlist module is disabled', 'woonoow'), ['status' => 403]);
        }
        
        $user_id = get_current_user_id();
        $wishlist = get_user_meta($user_id, 'woonoow_wishlist', true);
        
        if (!$wishlist || !is_array($wishlist)) {
            return new WP_REST_Response([], 200);
        }
        
        $items = [];
        foreach ($wishlist as $item) {
            $product_id = $item['product_id'];
            $product = wc_get_product($product_id);
            
            if (!$product) {
                continue; // Skip if product doesn't exist
            }
            
            $items[] = [
                'product_id'   => $product_id,
                'name'         => $product->get_name(),
                'slug'         => $product->get_slug(),
                'price'        => $product->get_price(),
                'regular_price'=> $product->get_regular_price(),
                'sale_price'   => $product->get_sale_price(),
                'image'        => wp_get_attachment_url($product->get_image_id()),
                'on_sale'      => $product->is_on_sale(),
                'stock_status' => $product->get_stock_status(),
                'type'         => $product->get_type(),
                'added_at'     => $item['added_at'],
            ];
        }
        
        return new WP_REST_Response($items, 200);
    }
    
    /**
     * Add product to wishlist
     */
    public static function add_to_wishlist(WP_REST_Request $request) {
        if (!ModuleRegistry::is_enabled('wishlist')) {
            return new WP_Error('module_disabled', __('Wishlist module is disabled', 'woonoow'), ['status' => 403]);
        }
        
        // Get settings
        $settings = get_option('woonoow_module_wishlist_settings', []);
        $max_items = (int) ($settings['max_items_per_wishlist'] ?? 0);
        
        $user_id = get_current_user_id();
        $product_id = $request->get_param('product_id');
        
        // Validate product exists
        $product = wc_get_product($product_id);
        if (!$product) {
            return new WP_Error('invalid_product', 'Product not found', ['status' => 404]);
        }
        
        $wishlist = get_user_meta($user_id, 'woonoow_wishlist', true);
        if (!is_array($wishlist)) {
            $wishlist = [];
        }
        
        // Check max items limit
        if ($max_items > 0 && count($wishlist) >= $max_items) {
            return new WP_Error(
                'wishlist_limit_reached',
                sprintf(__('Wishlist limit reached. Maximum %d items allowed.', 'woonoow'), $max_items),
                ['status' => 400]
            );
        }
        
        // Check if already in wishlist
        foreach ($wishlist as $item) {
            if ($item['product_id'] === $product_id) {
                return new WP_Error('already_in_wishlist', 'Product already in wishlist', ['status' => 400]);
            }
        }
        
        // Add to wishlist
        $wishlist[] = [
            'product_id' => $product_id,
            'added_at'   => current_time('mysql'),
        ];
        
        update_user_meta($user_id, 'woonoow_wishlist', $wishlist);
        
        return new WP_REST_Response([
            'message' => 'Product added to wishlist',
            'count'   => count($wishlist),
        ], 200);
    }
    
    /**
     * Remove product from wishlist
     */
    public static function remove_from_wishlist(WP_REST_Request $request) {
        if (!ModuleRegistry::is_enabled('wishlist')) {
            return new WP_Error('module_disabled', __('Wishlist module is disabled', 'woonoow'), ['status' => 403]);
        }
        
        $user_id = get_current_user_id();
        $product_id = (int) $request->get_param('product_id');
        
        $wishlist = get_user_meta($user_id, 'woonoow_wishlist', true);
        if (!is_array($wishlist)) {
            return new WP_Error('empty_wishlist', 'Wishlist is empty', ['status' => 400]);
        }
        
        // Remove product from wishlist
        $wishlist = array_filter($wishlist, function($item) use ($product_id) {
            return $item['product_id'] !== $product_id;
        });
        
        // Re-index array
        $wishlist = array_values($wishlist);
        
        update_user_meta($user_id, 'woonoow_wishlist', $wishlist);
        
        return new WP_REST_Response([
            'message' => 'Product removed from wishlist',
            'count'   => count($wishlist),
        ], 200);
    }
    
    /**
     * Clear entire wishlist
     */
    public static function clear_wishlist(WP_REST_Request $request) {
        if (!ModuleRegistry::is_enabled('wishlist')) {
            return new WP_Error('module_disabled', __('Wishlist module is disabled', 'woonoow'), ['status' => 403]);
        }
        
        $user_id = get_current_user_id();
        delete_user_meta($user_id, 'woonoow_wishlist');
        
        return new WP_REST_Response([
            'message' => 'Wishlist cleared',
            'count'   => 0,
        ], 200);
    }
}
