<?php
namespace SmartSlotAppointmentScheduler;

use WP_REST_Response;

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

if (!class_exists('\SmartSlotAppointmentScheduler\Time_updater')) {
	/**
	 * Class to update the booked time slots to frontend.
	 *
	 */
	class Time_updater {

		public static function init() {
			add_action('rest_api_init', [__CLASS__, 'register_time_getter']);
		}
		/**
		 * route to ge the category id.
		 */
		public static function register_time_getter() {
			register_rest_route('ssas/v1', '/categoryid', [
				'methods'             => 'POST',
				'callback'            => [__CLASS__, 'receive_booked_times'],
				'permission_callback' => '__return_true',
			]);
		}

		/**
		 * @param $request selectedDate(date) & category_id(array).
		 *
		 * @return WP_REST_Response with booked time Slots.
		 */

		public static function receive_booked_times( $request ) {
			$date        = sanitize_text_field($request->get_param('usedDate'));
			$category_id = $request->get_param('categoryid');

			// ✅ Validate date format
			if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
				return new \WP_Error('invalid_date', 'Invalid date format', ['status' => 400]);
			}

			// ✅ Validate category IDs
			if (!is_array($category_id)) {
				return new \WP_Error('invalid_category', 'Category must be an array', ['status' => 400]);
			}

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

			if (empty($category_id)) {
				return new \WP_Error('empty_category', 'No valid category IDs provided', ['status' => 400]);
			}

			$booked_time = self::get_booked_times_by_categories($date, $category_id);

			return rest_ensure_response([
				'message' => 'User information successfully saved.',
				'data'    => $booked_time,
			]);
		}

		/**
		 * Get booked appointment times for a given date and matching category term IDs.
		 *
		 * @param string $date     The appointment date (format: 'Y-m-d').
		 * @param array  $term_ids Array of category term IDs to match.
		 * @return array           Array of appointment times already booked.
		 */
		public static function get_booked_times_by_categories($date, $term_ids) {
			global $wpdb;

				// Create unique cache key
				$cache_group = 'ssas_booking';
				$cache_key   = 'booked_times_' . md5($date . '_' . implode(',', $term_ids));

			// Attempt to retrieve from cache
			$booked_times = wp_cache_get($cache_key, $cache_group);

			if ($booked_times !== false) {
				return $booked_times;
			}

				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom plugin table requires direct query.
				$results = $wpdb->get_results(
					$wpdb->prepare(
						"SELECT token_number, category_id, appointment_time FROM %i WHERE appointment_date = %s",
						'pkart_' . 'ssas_booking_appointment',
						$date
					)
				);


			$booked_times = [];

			foreach ($results as $row) {
				$category_ids = json_decode($row->category_id, true);

				if (is_array($category_ids)) {
					$matched = array_intersect($term_ids, $category_ids);
					if (!empty($matched)) {
						$booked_times[] = $row->appointment_time;
					}
				}
			}

			// Cache the result for 10 minutes
			wp_cache_set($cache_key, $booked_times, $cache_group, 10 * MINUTE_IN_SECONDS);

			return $booked_times;
		}

	}

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