<?php
/**
 * Route Configuration.
 *
 * @since 1.0.0
 */

namespace FleekDash\Libs\API;

use FleekDash\Libs\API\ApiRouteException;

/**
 * Class Config
 *
 * Handles API configuration for the FleekDash plugin.
 *
 * @package FleekDash\Libs\API
 */
class Config
{
	/**
	 * @var string The route file path
	 */
	private static $route_file;

	/**
	 * @var string The API namespace
	 */
	private static $namespace;

	/**
	 * @var bool Debug mode for API
	 */
	private static $debug_mode = false;

	/**
	 * @var bool API request/response logging
	 */
	private static $debug_log_api = false;

	/**
	 * @var bool Track if routes have been loaded to prevent duplicate loading
	 */
	private static $routes_loaded = false;

	/**
	 * Private constructor to protect making instance.
	 */
	private function __construct()
	{
	}

	/**
	 * Set the route file path
	 *
	 * @param string $file_path The path to the route file
	 * @return self
	 */
	public static function set_route_file($file_path)
	{
		self::$route_file = $file_path;
		return new static();
	}

	/**
	 * Set the API namespace
	 *
	 * @param string $namespace The API namespace
	 * @return self
	 */
	public static function set_namespace($namespace)
	{
		self::$namespace = $namespace;
		return new static();
	}

	/**
	 * Enable or disable debug mode for API
	 *
	 * @param bool $enable
	 * @return self
	 */
	public static function set_debug_mode($enable = true)
	{
		self::$debug_mode = $enable;
		return new static();
	}

	/**
	 * Enable or disable API request/response logging
	 *
	 * @param bool $enable
	 * @return self
	 */
	public static function set_debug_log($enable = true)
	{
		self::$debug_log_api = $enable;
		return new static();
	}

	/**
	 * Check if debug mode is enabled
	 *
	 * @return bool
	 */
	public static function is_debug_mode()
	{
		return self::$debug_mode || (defined('WP_DEBUG') && WP_DEBUG);
	}

	/**
	 * Check if API logging is enabled
	 *
	 * @return bool
	 */
	public static function is_debug_log_api()
	{
		return self::$debug_log_api || (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG);
	}

	/**
	 * Initialize the API configuration
	 *
	 * @return void
	 */
	public static function init()
	{
		// Set debug mode based on WP_DEBUG if not already set
		if (defined('WP_DEBUG') && WP_DEBUG) {
			self::set_debug_mode(true);

			if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
				self::set_debug_log(true);
			}
		}

		// Register REST API routes with better error handling
		add_action('rest_api_init', function () {
			// Prevent duplicate loading
			if (self::$routes_loaded) {
				return;
			}

			try {
				// Check if route file is set
				if (empty(self::$route_file)) {
					if (self::is_debug_mode()) {
						error_log('FleekDash: Route file path not set');
					}
					return;
				}

				// Check file existence with case-sensitivity handling for Linux servers
				$route_file = self::$route_file;
				$file_exists = file_exists($route_file);

				// If file doesn't exist, try to find it with case-insensitive search (for Linux)
				if (!$file_exists && DIRECTORY_SEPARATOR === '/') {
					$dir = dirname($route_file);
					$filename = basename($route_file);

					if (is_dir($dir)) {
						$files = scandir($dir);
						foreach ($files as $file) {
							if (strtolower($file) === strtolower($filename)) {
								$route_file = $dir . DIRECTORY_SEPARATOR . $file;
								$file_exists = true;
								break;
							}
						}
					}
				}

				if ($file_exists) {
					// Define the REST API namespace for routes to use
					if (!defined('FLEEKDASH_API_NAMESPACE')) {
						define('FLEEKDASH_API_NAMESPACE', self::$namespace);
					}

					// Load the route file with error handling
					$result = include_once $route_file;

					if ($result === false) {
						if (self::is_debug_mode()) {
							error_log('FleekDash: Failed to load route file: ' . $route_file);
						}
					} else {
						self::$routes_loaded = true;
					}
				} else {
					// Only log in debug mode to avoid noise in production
					if (self::is_debug_mode()) {
						error_log('FleekDash: Route file not found: ' . self::$route_file . ' (Plugin may need to be reinstalled)');
					}
				}
			} catch (\Exception $e) {
				if (self::is_debug_mode()) {
					error_log('FleekDash: Error loading routes: ' . $e->getMessage());
				}
			}
		}, 10); // Standard priority

		// Add CORS headers
		add_action('rest_api_init', function () {
			remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
			add_filter('rest_pre_serve_request', function ($value) {
				header('Access-Control-Allow-Origin: *');
				header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
				header('Access-Control-Allow-Credentials: true');
				header('Access-Control-Allow-Headers: Authorization, Content-Type, X-Requested-With, Cache-Control, X-WP-Nonce');
				return $value;
			});
		});
	}
}
