<?php

namespace CouponsPlus\App\Handlers;

use WP_REST_Response;
use WP_REST_Request;
use WP_Term;
use CouponsPlus\Original\Events\Handler\EventHandler;

Class RestTaxonomyAncestors extends EventHandler
{
    protected $numberOfArguments = 1;
    protected $priority = 100;

    /**
     * List of taxonomies to add ancestors for in the REST API responses
     *
     */
    protected $supportedTaxonomies = [
        'product_cat',
        'product_brand',
    ];

    public function execute()
    {
        // Hook into each supported taxonomy
        foreach ($this->supportedTaxonomies as $taxonomy) {
            add_filter(
                "rest_prepare_{$taxonomy}",
                [$this, 'add_ancestors_to_response'],
                100,
                3
            );
        }

        // Keep the original hook for backwards compatibility
        add_filter(
            'woocommerce_rest_prepare_product_cat',
            [$this, 'add_ancestors_to_response'],
            100,
            3
        );
    }

    /**
     * Adds ancestors array to taxonomy term REST response
     *
     * @param WP_REST_Response $response The REST response object
     * @param WP_Term $term The term object
     * @param WP_REST_Request $request The REST request object
     * @return WP_REST_Response Modified response with ancestors
     */
    public function add_ancestors_to_response(WP_REST_Response $response, WP_Term $term, WP_REST_Request $request): WP_REST_Response {
        $data = $response->get_data();

        // Use the extracted method to get ancestors
        $ancestors = $this->get_term_ancestors($term);

        // Add ancestors to the response
        $data['ancestors'] = $ancestors;

        $response->set_data($data);

        return $response;
    }

    /**
     * Gets ancestors array for a given term object
     *
     * @param WP_Term $term The term object
     * @return array Array of ancestor names in hierarchical order (top to bottom)
     */
    public function get_term_ancestors($term) {
        $ancestors = [];

        // Validate the term object
        if (!$term instanceof WP_Term) {
            return $ancestors;
        }

        $parent_id = $term->parent;

        while ($parent_id > 0) {
            $parent = get_term($parent_id, $term->taxonomy);
            if (!is_wp_error($parent) && $parent) {
                $ancestors[] = $parent->name;
                $parent_id = $parent->parent;
            } else {
                break;
            }
        }

        // Reverse the array to get the hierarchical order from top to bottom
        return array_reverse($ancestors);
    }

}