<?php

namespace SugarCalendarBookings\Support\Tags\Admin;

use SugarCalendarBookings\Support\Tags\TagModel;
use SugarCalendarBookings\Support\Ajax\AbstractController;

/**
 * Tags controller.
 *
 * @since 1.0.0
 */
class TagsController extends AbstractController {

	/**
	 * Get the allowed object types.
	 *
	 * @since 1.2.0
	 *
	 * @return array
	 */
	protected function get_allowed_object_types() {

		return [
			'service',
			'customer',
		];
	}

	/**
	 * Get the input data.
	 *
	 * @since 1.2.0
	 *
	 * @return array
	 */
	protected function get_input_data_rules() {

		$allowed_object_types = implode( ',', $this->get_allowed_object_types() );

		return [
			'name'        => 'required|string',
			'object_type' => 'required|string|in:' . $allowed_object_types,
		];
	}

	/**
	 * Create a tag.
	 *
	 * @since 1.0.0
	 * @since 1.2.0 Separate rules for input data.
	 */
	public function create() {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You are not allowed to create tags.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$data = $this->get_input_data( $this->get_input_data_rules() );

		$tag = TagModel::create(
			[
				'name'        => $data['name'],
				'object_type' => $data['object_type'],
			]
		);

		if ( empty( $tag->get_id() ) ) {
			wp_send_json_error( esc_html__( 'Failed to create tag.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		wp_send_json_success(
			[
				'id'          => $tag->id,
				'name'        => $tag->name,
				'slug'        => $tag->slug,
				'object_type' => $tag->object_type,
			]
		);
	}
}
