<?php

declare(strict_types=1);
defined('ABSPATH') || exit;

class DSProofwp_Product_Controller
{
    private const ROUTE_NAMESPACE = 'dsproofwp/v1';

    public function register_routes(): void
    {
        register_rest_route(
            self::ROUTE_NAMESPACE,
            '/products',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_products'],
                    'permission_callback' => '__return_true',
                ],
            ]
        );

        register_rest_route(
            self::ROUTE_NAMESPACE,
            '/products/(?P<id>\d+)',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_product'],
                    'permission_callback' => '__return_true',
                ],
            ]
        );
    }

    public function get_products(WP_REST_Request $request): WP_REST_Response
    {
        if (! function_exists('wc_get_products')) {
            return new WP_REST_Response(
                new WP_Error('dsproofwp_woocommerce_unavailable', 'WooCommerce is not active.', ['status' => 404]),
                404
            );
        }

        $search = $request->get_param('search');
        $products = wc_get_products([
            'status' => 'publish',
            'limit'  => -1,
            'return' => 'objects',
            's'      => is_string($search) ? $search : '',
        ]);

        $items = array_map([$this, 'prepare_product_response'], $products);

        return rest_ensure_response([
            'items' => array_values($items),
            'total' => count($items),
        ]);
    }

    public function get_product(WP_REST_Request $request)
    {
        if (! function_exists('wc_get_product')) {
            return new WP_Error('dsproofwp_woocommerce_unavailable', 'WooCommerce is not active.', ['status' => 404]);
        }

        $product = wc_get_product((int) $request['id']);

        if (! $product instanceof WC_Product) {
            return new WP_Error('dsproofwp_product_not_found', 'Product not found.', ['status' => 404]);
        }

        return rest_ensure_response($this->prepare_product_response($product));
    }

    private function prepare_product_response(WC_Product $product): array
    {
        $image_id = $product->get_image_id();
        $image_url = $image_id ? wp_get_attachment_image_url($image_id, 'woocommerce_thumbnail') : '';

        if (! $image_url && function_exists('wc_placeholder_img_src')) {
            $image_url = wc_placeholder_img_src('woocommerce_thumbnail');
        }

        return [
            'id'        => $product->get_id(),
            'title'     => $product->get_name(),
            'permalink' =>  get_permalink($product->get_id()),
            'thumbnail' => $image_url ?: '',
        ];
    }
}
