<?php

namespace ShopManagerPro\System;

use ShopManagerPro\Filters\FilterAPI;
use ShopManagerPro\Jobs\JobAPI;
use ShopManagerPro\Products\Fields\ProductFieldAPI;
use ShopManagerPro\Products\ProductAPI;
use ShopManagerPro\TaxClasses\TaxClassAPI;

class SystemInfoAPI {
	private const SCHEMA = ['title' => 'apiInfo', 'type' => 'object', 'required' => ['adminUrl', 'ajaxUrl', 'apiUrl', 'currencyCode', 'locale', 'nonce', 'pluginUrl', 'plugins', 'shopUrl', 'system', 'uploadsUrl'], 'additionalProperties' => false, 'properties' => ['adminUrl' => ['type' => 'string'], 'ajaxUrl' => ['type' => 'string'], 'apiUrl' => ['type' => 'string'], 'currencyCode' => ['type' => 'string'], 'license' => SHOP_MANAGER_PRO_COMMERCIAL ? \ShopManagerPro\Premium\License\LicenseAPI::INFO_SCHEMA : ['type' => 'null'], 'locale' => ['type' => 'string'], 'nonce' => ['type' => 'string'], 'pluginUrl' => ['type' => 'string'], 'shopUrl' => ['type' => 'string'], 'uploadsUrl' => ['type' => 'string'], 'plugins' => ['type' => 'object', 'additionalProperties' => false, 'required' => ['acf', 'germanMarket', 'wooCommerce'], 'properties' => ['acf' => ['type' => ['string', 'null']], 'germanMarket' => ['type' => ['string', 'null']], 'wooCommerce' => ['type' => ['string', 'null']]]], 'system' => ['type' => 'object', 'additionalProperties' => false, 'required' => ['phpVersion', 'pluginVersion', 'databaseSoftware', 'databaseVersion', 'phpMemoryLimit', 'phpMemoryPeakUsage', 'phpMaxExecutionTime', 'phpErrorLog'], 'properties' => ['databaseSoftware' => ['type' => 'string'], 'databaseVersion' => ['type' => 'string'], 'phpErrorLog' => ['type' => 'string'], 'phpMaxExecutionTime' => ['type' => 'string'], 'phpMemoryLimit' => ['type' => 'string'], 'phpMemoryPeakUsage' => ['type' => 'string'], 'phpVersion' => ['type' => 'string'], 'pluginVersion' => ['type' => 'string']]]]];

	public static function init() {
		add_action('rest_api_init', [self::class, 'registerRoutes']);
	}

	public static function registerRoutes() {
		register_rest_route(\ShopManagerPro\Shared\Utils\Constants::API_NAMESPACE, '/api', [['methods' => 'GET', 'callback' => [self::class, 'getData'], 'permission_callback' => [\ShopManagerPro\Shared\CapabilityService::class, 'requireReadCapability']], 'schema' => fn () => self::SCHEMA]);
		if (SHOP_MANAGER_PRO_COMMERCIAL) {
			$productExportTemplateSchema = \ShopManagerPro\Premium\Export\ProductExportTemplateAPI::getListSchema();
		} else {
			$productExportTemplateSchema = ['type' => 'null'];
		} register_rest_route(\ShopManagerPro\Shared\Utils\Constants::API_NAMESPACE, '/api/all', [['methods' => 'GET', 'callback' => [self::class, 'getAll'], 'permission_callback' => [\ShopManagerPro\Shared\CapabilityService::class, 'requireEditCapability']], 'schema' => fn () => ['title' => 'allEndpoints', 'type' => 'object', 'required' => ['filters', 'jobs', 'products', 'productExportTemplates', 'productFields', 'taxClasses', 'taxonomies', 'system'], 'additionalProperties' => false, 'properties' => ['filters' => FilterAPI::getListSchema(), 'jobs' => JobAPI::getJobsSchema(), 'productExportTemplates' => $productExportTemplateSchema, 'productFields' => ProductFieldAPI::schema(), 'products' => ProductAPI::getProductsSchema(), 'system' => self::SCHEMA, 'taxClasses' => TaxClassAPI::SCHEMA]]]);
	}

	public static function getData() {
		global $wpdb;
		$upload_dir = wp_upload_dir();
		$db_version = $wpdb->get_var('SELECT VERSION()');
		$db_software = 'MySQL';
		if (stripos($db_version, 'mariadb') !== false) {
			$db_software = 'MariaDB';
			preg_match('/^([0-9]+\.[0-9]+\.[0-9]+)/', $db_version, $matches);
			$db_version = $matches[1] ?? $db_version;
		}

return ['adminUrl' => get_admin_url(), 'ajaxUrl' => admin_url('admin-ajax.php'), 'apiUrl' => rest_url(), 'currencyCode' => get_woocommerce_currency(), 'license' => SHOP_MANAGER_PRO_COMMERCIAL ? \ShopManagerPro\Premium\License\LicenseValidatorService::getLicenseStatus() : null, 'locale' => get_user_locale(), 'nonce' => wp_create_nonce('wp_rest'), 'pluginUrl' => SHOP_MANAGER_PRO_PLUGIN_URL, 'shopUrl' => home_url('/'), 'uploadsUrl' => $upload_dir['baseurl'], 'plugins' => ['acf' => \ShopManagerPro\Shared\PluginDetectorService::$acfVersion, 'germanMarket' => \ShopManagerPro\Shared\PluginDetectorService::$germanMarketVersion, 'wooCommerce' => \ShopManagerPro\Shared\PluginDetectorService::$wooCommerceVersion], 'system' => ['databaseSoftware' => $db_software, 'databaseVersion' => $db_version, 'phpErrorLog' => ini_get('error_log'), 'phpMaxExecutionTime' => ini_get('max_execution_time').'s', 'phpMemoryLimit' => ini_get('memory_limit'), 'phpMemoryPeakUsage' => round(memory_get_peak_usage() / 1024 / 1024).'M', 'phpVersion' => phpversion(), 'pluginVersion' => SHOP_MANAGER_PRO_VERSION]];
	}

	public static function getAll(\WP_REST_Request $request) {
		$response = ['filters' => FilterAPI::getFilters($request)->data, 'jobs' => JobAPI::getJobs($request)->data, 'products' => ProductAPI::getProducts($request)->data, 'productFields' => ProductFieldAPI::getProductFields($request)->data, 'taxClasses' => TaxClassAPI::getTaxClasses($request)->data, 'system' => self::getData()];
		if (SHOP_MANAGER_PRO_COMMERCIAL) {
			$response['productExportTemplates'] = \ShopManagerPro\Premium\Export\ProductExportTemplateAPI::getProductExportTemplates($request)->data;
		}

return rest_ensure_response($response);
	}
}
