<?php
namespace SmartSlotAppointmentScheduler;

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use SmartSlotAppointmentScheduler\Get_Sub_Menu_fields;

if (! defined('ABSPATH')) {
	exit;
}

if (!class_exists('\SmartSlotAppointmentScheduler\Register_Custom_API')) {
	/**
	 * Class to register api for (get terms, setting fields value & )
	 */
	class Register_Custom_API {
		public static function init() {
			add_action('rest_api_init', [__CLASS__, 'register_all_routes']);
		}

		public static function register_all_routes() {
			self::register_term_routes();
			self::register_settings_fields_routes();
			self::schedule_post_routes();
		}

		/**
		 * Register Rest API routes.
		 *
		 * has a callback function returns response.
		 */
		public static function register_term_routes() {
			$routes = [
				// Canonical endpoints.
				'ssas_categories'   => 'ssas_categories',
				'ssas_services'     => 'ssas_services',
				// Deprecated endpoints kept for existing REST consumers.
				'ssas_specialities' => 'ssas_categories',
				'ssas_checkups'     => 'ssas_services',
			];

			foreach ($routes as $endpoint => $taxonomy) {
				register_rest_route('ssas/v1', "/$endpoint", [
					'methods'             => 'GET',
					'callback'            => function (WP_REST_Request $request) use ($taxonomy) {
						// ✅ Validate taxonomy exists
						if (!taxonomy_exists($taxonomy)) {
							return new \WP_Error('invalid_taxonomy', 'Invalid taxonomy', ['status' => 400]);
						}
						return self::get_terms_response($taxonomy);
					},
					'permission_callback' => '__return_true',
				]);
			}
		}

		/**
		 * @param string $taxonomy.
		 *
		 * return wp_rest_response|Wp_Error.
		 */

		private static function get_terms_response($taxonomy) {
			$terms = get_terms([
				'taxonomy'   => $taxonomy,
				'hide_empty' => false,
			]);

			if (is_wp_error($terms)) {
				return new WP_Error("rest_{$taxonomy}_error", 'Unable to fetch terms', ['status' => 500]);
			}

			if($taxonomy == 'ssas_categories') {
				return new WP_REST_Response(
					array_values(
						array_filter(
							array_map(function ($term) {
								if ($term->count >= 1) {
									return [
										'id'   => $term->term_id,
										'name' => esc_html($term->name),
										'slug' => $term->slug,
									];
								}
								return null; // filter will remove this
							}, $terms)
						)
					),
					200
				);
			}

			return new WP_REST_Response(array_map(function ($term) {
				return [
					'id'   => $term->term_id,
					'name' => esc_html($term->name),
					'slug' => $term->slug,
				];
			}, $terms), 200);
		}

		/**
		 * function to register settings fields route.
		 */
		public static function register_settings_fields_routes() {
			register_rest_route('ssas/v1', '/settings-fields', array(
				'methods'             => 'GET',
				'callback'            => [__CLASS__, 'get_settings_fields'],
				'permission_callback' => '__return_true',
			));
		}
		/**
		 * function to get fields from Get_Sub_Menu_fields::init().
		 */
		public static function get_settings_fields() {
			$settings = Get_Sub_Menu_fields::init();

			if (is_wp_error($settings)) {
				return new WP_Error("rest_fetching_error", 'Unable to fetch settings', ['status' => 500]);
			}

			return rest_ensure_response($settings);
		}

		/**
		 * get the post type schedule.
		 */
		public static function schedule_post_routes() {

			register_rest_route(
				'ssas/v1',
				'/schedule',
				[
					'methods'             => 'GET',
					'callback'            => [__CLASS__, 'get_schedule_posttype'],
					'permission_callback' => '__return_true',

					'args' => [
						'categories' => [
							'required' => false,
							'type'     => 'string',
						],

						'services' => [
							'required' => false,
							'type'     => 'string',
						],

						// Deprecated aliases, accepted for existing REST consumers.
						'specialities' => [
							'required' => false,
							'type'     => 'string',
						],

						'checkups' => [
							'required' => false,
							'type'     => 'string',
						],
					],
				]
			);
		}


		/**
		 * Get schedule posts with required custom fields,
		 * featured image and taxonomy terms.
		 */
		public static function get_schedule_posttype() {

			$schedule_posts = get_posts([
				'post_type'      => Schedule_Posttype::SLUG,
				'post_status'    => 'publish',
				'posts_per_page' => -1,
				'orderby'        => 'title',
				'order'          => 'ASC',
			]);

			$results = [];

			foreach ($schedule_posts as $post) {

				$post_id = $post->ID;

				/*
				* Custom fields.
				*/
				$organiser_name = get_post_meta(
					$post_id,
					'_organiser_name',
					true
				);

				$venue = get_post_meta(
					$post_id,
					'_venue',
					true
				);

				$famous_service = get_post_meta(
					$post_id,
					'_famous_service',
					true
				);

				if (!is_array($famous_service)) {
					$famous_service = [];
				}

				$famous_service = array_filter(
					array_map('absint', $famous_service)
				);

				/*
				* Schedule categories.
				*/
				$category_terms = wp_get_post_terms(
					$post_id,
					'ssas_categories'
				);

				$categories = [];

				if (!is_wp_error($category_terms)) {
					foreach ($category_terms as $term) {
						$categories[] = [
							'id'   => $term->term_id,
							'name' => $term->name,
							'slug' => $term->slug,
						];
					}
				}

				/*
				* Schedule services.
				*/
				$service_terms = wp_get_post_terms(
					$post_id,
					'ssas_services'
				);

				$services = [];

				if (!is_wp_error($service_terms)) {
					foreach ($service_terms as $term) {
						$services[] = [
							'id'   => $term->term_id,
							'name' => $term->name,
							'slug' => $term->slug,
						];
					}
				}

				/*
				* Famous service term details.
				*/
				$famous_services = [];

				foreach ($famous_service as $term_id) {

					$term = get_term(
						$term_id,
						'ssas_services'
					);

					if ($term && !is_wp_error($term)) {
						$famous_services[] = [
							'id'   => $term->term_id,
							'name' => $term->name,
							'slug' => $term->slug,
						];
					}
				}

				/*
				* Provider availability (unavailable dates).
				*/
				$provider_availability = get_post_meta(
					$post_id,
					'_provider_availability',
					true
				);

				if (!is_array($provider_availability)) {
					$provider_availability = [];
				}

				/*
				* Featured image.
				*/
				$featured_image = get_the_post_thumbnail_url(
					$post_id,
					'medium_large'
				);

				$results[] = [
					'id'             => $post_id,
					'title'          => get_the_title($post_id),

					'organiser_name' => sanitize_text_field(
						$organiser_name
					),

					'venue'          => sanitize_text_field(
						$venue
					),

					'famous_services' => $famous_services,

					'featured_image' => $featured_image
						? esc_url_raw($featured_image)
						: '',

					'provider_availability' => $provider_availability,

					'categories' => $categories,

					'services' => $services,

					// Deprecated aliases, kept for existing REST consumers.
					'specialities' => $categories,

					'checkups' => $services,
				];
			}

			return rest_ensure_response($results);
		}

	}

	add_action('init', ['\\SmartSlotAppointmentScheduler\\Register_Custom_API', 'init'], 11);
}
