<?php

defined('ABSPATH') || exit;

class ShopCentral_API
{
    public function __construct()
    {
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes()
    {
        $version = '1';
        $namespace = 'shopcentral/v' . $version;

        // Products
        register_rest_route($namespace, '/api/all-products', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_all_products'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        register_rest_route($namespace, '/api/all-coupons', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_all_coupons'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        register_rest_route($namespace, '/api/products/(?P<id>\d+)/variations', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_product_variations'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        register_rest_route($namespace, '/api/recommendations', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_recommendations'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        register_rest_route($namespace, '/api/product-categories', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_product_categories'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        register_rest_route($namespace, '/api/product-tags', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_product_tags'],
            'permission_callback' => [$this, 'check_permission'],
        ]);


    }

    public function check_permission()
    {
        return current_user_can('manage_options');
    }


    // --- Product Callbacks ---

    public function get_all_products($request)
    {
        if (!function_exists('wc_get_products')) {
            return new WP_Error('wc_not_found', 'WooCommerce is not active', ['status' => 500]);
        }

        $search = $request->get_param('search');
        $page = $request->get_param('page') ?: 1;
        $per_page = $request->get_param('per_page') ?: 10;
        $status = $request->get_param('status');
        $type = $request->get_param('type');
        $stock_status = $request->get_param('stock_status');

        $args = [
            'limit' => $per_page,
            'page' => $page,
            'paginate' => true,
        ];

        if ($status && $status !== 'any') {
            $args['status'] = $status;
        } else {
            $args['status'] = 'publish';
        }

        if ($type) {
            $args['type'] = $type;
        }

        if ($stock_status) {
            $args['stock_status'] = $stock_status;
        }

        if ($search) {
            $args['s'] = $search;
        }

        if ($request->get_param('after')) {
            $args['date_after'] = $request->get_param('after');
        }
        if ($request->get_param('before')) {
            $args['date_before'] = $request->get_param('before');
        }

        $tax_query = [];

        $category = $request->get_param('category');
        if ($category) {
            $tax_query[] = [
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => explode(',', $category),
                'operator' => 'IN',
            ];
        }

        $tag = $request->get_param('tag');
        if ($tag) {
            $tax_query[] = [
                'taxonomy' => 'product_tag',
                'field' => 'term_id',
                'terms' => explode(',', $tag),
                'operator' => 'IN',
            ];
        }

        if (!empty($tax_query)) {
            $args['tax_query'] = $tax_query;
        }

        $results = wc_get_products($args);
        $products = [];

        if (isset($results->products)) {
            foreach ($results->products as $product) {
                $products[] = $this->format_product($product);
            }
        }

        return new WP_REST_Response([
            'data' => [
                'allProducts' => $products,
                'total' => isset($results->total) ? $results->total : 0,
                'max_num_pages' => isset($results->max_num_pages) ? $results->max_num_pages : 0,
            ],
            'meta' => [
                'total' => isset($results->total) ? $results->total : 0
            ]
        ], 200);
    }

    public function get_all_coupons($request)
    {
        if (!function_exists('wc_get_coupons')) {
            // Fallback for older WC or if wc_get_coupons is unavailable
            $args = [
                'post_type' => 'shop_coupon',
                'post_status' => 'publish',
                'posts_per_page' => $request->get_param('per_page') ?: 20,
                's' => $request->get_param('search')
            ];
            $posts = get_posts($args);
            $coupons = [];
            foreach ($posts as $post) {
                $coupon = new WC_Coupon($post->ID);
                $coupons[] = [
                    'id' => $coupon->get_id(),
                    'code' => $coupon->get_code(),
                    'amount' => $coupon->get_amount(),
                    'discount_type' => $coupon->get_discount_type(),
                ];
            }
        } else {
            $args = [
                'limit' => $request->get_param('per_page') ?: 20,
                'page' => $request->get_param('page') ?: 1,
            ];
            
            if ($request->get_param('after')) {
                $args['date_after'] = $request->get_param('after');
            }
            if ($request->get_param('before')) {
                $args['date_before'] = $request->get_param('before');
            }
            $search = $request->get_param('search');
            if ($search) {
                $args['code'] = $search;
            }
            $results = wc_get_coupons($args);
            $coupons = [];
            foreach ($results as $coupon) {
                $coupons[] = [
                    'id' => $coupon->get_id(),
                    'code' => $coupon->get_code(),
                    'amount' => $coupon->get_amount(),
                    'discount_type' => $coupon->get_discount_type(),
                ];
            }
        }

        return new WP_REST_Response([
            'data' => [
                'allCoupons' => $coupons
            ],
            'meta' => [
                'total' => count($coupons)
            ]
        ], 200);
    }

    public function get_product_variations($request)
    {
        $product_id = $request['id'];
        $product = wc_get_product($product_id);

        if (!$product || $product->get_type() !== 'variable') {
            return new WP_REST_Response(['variations' => []], 200);
        }

        $variations = [];
        foreach ($product->get_children() as $variation_id) {
            $variation = wc_get_product($variation_id);
            if ($variation) {
                $variations[] = $this->format_product($variation);
            }
        }

        return new WP_REST_Response(['variations' => $variations], 200);
    }

    public function get_recommendations($request)
    {
        if (!function_exists('wc_get_products')) {
            return new WP_Error('wc_not_found', 'WooCommerce is not active', ['status' => 500]);
        }

        $limit = $request->get_param('limit') ?: 4;

        $args = [
            'status' => 'publish',
            'limit' => $limit,
            'orderby' => 'popularity',
            'order' => 'DESC',
        ];

        $results = wc_get_products($args);
        $recommendations = [];

        foreach ($results as $product) {
            $image_id = $product->get_image_id();
            $image_url = wp_get_attachment_image_url($image_id, 'thumbnail');

            $recommendations[] = [
                'id' => $product->get_id(),
                'name' => $product->get_name(),
                'image' => $image_url,
                'price' => $product->get_price(),
            ];
        }

        return new WP_REST_Response([
            'data' => [
                'recommendations' => $recommendations
            ]
        ], 200);
    }

    public function get_product_categories()
    {
        $categories = get_terms([
            'taxonomy' => 'product_cat',
            'hide_empty' => false,
        ]);

        $formatted = [];
        foreach ($categories as $cat) {
            $formatted[] = [
                'id' => $cat->term_id,
                'name' => $cat->name,
                'slug' => $cat->slug,
            ];
        }

        return new WP_REST_Response(['categories' => $formatted], 200);
    }

    public function get_product_tags()
    {
        $tags = get_terms([
            'taxonomy' => 'product_tag',
            'hide_empty' => false,
        ]);

        $formatted = [];
        foreach ($tags as $tag) {
            $formatted[] = [
                'id' => $tag->term_id,
                'name' => $tag->name,
                'slug' => $tag->slug,
            ];
        }

        return new WP_REST_Response(['tags' => $formatted], 200);
    }

    private function format_product($product)
    {
        $image_id = $product->get_image_id();
        $image_url = wp_get_attachment_image_url($image_id, 'thumbnail');

        return [
            'id' => $product->get_id(),
            'name' => $product->get_name(),
            'type' => $product->get_type(),
            'status' => $product->get_status(),
            'date_created' => $product->get_date_created() ? $product->get_date_created()->date('Y-m-d H:i:s') : null,
            'price' => $product->get_price(),
            'price_html' => $product->get_price_html(),
            'stock_status' => $product->get_stock_status(),
            'stock_quantity' => $product->get_stock_quantity(),
            'total_sales' => (int) $product->get_total_sales(),
            'images' => [
                ['thumbnail' => $image_url, 'src' => $image_url]
            ],
        ];
    }

}
