<?php

namespace GemBoards\Ajax;

use GemBoards\Classes\AbstractAjaxHandler;

class Taxonomy extends AbstractAjaxHandler {

	public function __construct() {
		$this->actions = [
			'set_task_priority' => [
				'callback'   => [ $this, 'set_task_priority' ],
				'permission' => 'manage_tasks',
				'fields'     => [
					'task_id'  => 'integer',
					'priority' => 'string',
				],
			],
			'set_task_labels'   => [
				'callback'   => [ $this, 'set_task_labels' ],
				'permission' => 'manage_tasks',
				'fields'     => [
					'task_id'  => 'integer',
					'board_id' => 'integer',
					'labels'   => 'array|string',
				],
			],
		];
	}


	public function set_task_priority( $request ) {
		$task_id  = intval($request['task_id']);
		$priority = sanitize_text_field($request['priority']);

		wp_set_object_terms($task_id, [ $priority ], GEMBOARDS_PLUGIN_SLUG . '_priority');

		wp_send_json_success([ 'message' => 'Priority assigned.' ]);
	}

	public function set_task_labels( $request ) {
		$task_id = intval($request['task_id'] ?? $request['card_id']);
		$labels  = $request['labels'] ?? [];

		if ( ! $task_id || ! is_array($labels) ) {
			wp_send_json_error([ 'message' => 'Missing task_id or labels.' ], 400);
		}

		$term_ids = [];

		foreach ( $labels as $label ) {
			$id         = intval($label['id']);
			$title      = sanitize_text_field($label['title']);
			$bg_color   = sanitize_hex_color($label['bg_color']) ?: '#cccccc';
			$text_color = sanitize_hex_color($label['text_color']) ?: '#000000';
			$board_id   = intval($request['board_id']);

			if ( 0 === $id ) {
				$result = wp_insert_term($title, GEMBOARDS_PLUGIN_SLUG . '_label');
				if ( is_wp_error($result) ) {
					continue;
				}
				$id = $result['term_id'];
			}

			update_term_meta($id, 'bg_color', $bg_color);
			update_term_meta($id, 'text_color', $text_color);
			update_term_meta($id, 'board_id', $board_id);

			$term_ids[] = $id;
		}

		wp_set_object_terms($task_id, $term_ids, GEMBOARDS_PLUGIN_SLUG . '_label');

		wp_send_json_success([
			'message'  => __('Labels assigned and updated.', 'gemboards'),
			'term_ids' => $term_ids,
		]);
	}
}
