<?php

// If this file is called directly, abort.
if (!defined('WPINC')) {
	die;
}

class BrandsManufacturersController {

	public function getBrandsManufacturers() {
		$taxonomy = 'product_brand';

		if (!taxonomy_exists($taxonomy)) {
			return [];
		}

		$data = [];
		$terms = get_terms([
			'taxonomy' => $taxonomy,
			'hide_empty' => false,
		]);

		if (is_wp_error($terms) || empty($terms)) {
			return [];
		}

		foreach ($terms as $term) {
			$image_url = $this->getImage($term);

			$data[] = [
				'id' => (int) $term->term_id,
				'name' => $term->name ?? "",
				'url' => get_term_link($term),
				'image' => $image_url
			];
		}

		return $data;
	}

	private function getImage($term) {
		$image_url = '';
		$image_id = get_term_meta($term->term_id, 'thumbnail_id', true);

		if ($image_id) {
			$image_url = wp_get_attachment_url($image_id);
		}

		return $image_url ? (string) $image_url : "";
	}
}