<?php

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

class Sabriel_Module_Core extends Sabriel_Module {

	const CLEANUP_HOOK        = 'sabriel_ai_pulizia_transient';
	const CLEANUP_HOOK_LEGACY = 'sab_pulizia_transient_scaduti';
	const CLEANUP_BATCH_SIZE = 200;

	private $locale_bot_richiesta = '';

	public function get_id() {
		return 'core';
	}

	public function register_hooks() {

		add_action( 'init', [ $this, 'forza_lingua_bot_rest' ], 1 );

		add_action( 'admin_init', [ __CLASS__, 'assicura_cron' ] );
		add_action( self::CLEANUP_HOOK, [ $this, 'cleanup_expired_transients' ] );
	}

	public static function assicura_cron() {
		if ( wp_next_scheduled( self::CLEANUP_HOOK_LEGACY ) ) {
			wp_clear_scheduled_hook( self::CLEANUP_HOOK_LEGACY );
		}
		if ( ! wp_next_scheduled( self::CLEANUP_HOOK ) ) {
			wp_schedule_event( time(), 'weekly', self::CLEANUP_HOOK );
		}
	}

	public function forza_lingua_bot_rest( $result = null, $server = null, $request = null ) {
		if ( ! $this->e_una_richiesta_del_bot() || ! class_exists( 'Sabriel_Module_Settings' ) ) {
			return $result;
		}
		$locale = Sabriel_Module_Settings::locale_bot();
		if ( $locale ) {
			$this->locale_bot_richiesta = $locale;
			add_filter( 'pre_determine_locale', [ $this, 'lingua_bot_per_i_clienti' ] );
		}
		return $result;
	}

	const ROTTE_DEL_PANNELLO = '#^/sabriel/v1/(?:'
		. 'ai/(?:test-key|remove-key)/'
		. '|chat/unlock$'
		. ')#';

	private function e_una_richiesta_del_bot() {
		$uri = isset( $_SERVER['REQUEST_URI'] ) ? rawurldecode( (string) wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- il valore serve solo a un preg_match interno: sanitize_text_field() cancellerebbe le sequenze %2F e romperebbe il riconoscimento della rotta.
		if ( '' === $uri ) {
			return false;
		}
		$prefisso = trim( (string) rest_get_url_prefix(), '/' );

		$rotta = '';
		if ( preg_match( '#/' . preg_quote( $prefisso, '#' ) . '(/sabriel/v1[^?&]*)#', $uri, $pezzi ) ) {
			$rotta = $pezzi[1];
		} elseif ( preg_match( '#rest_route=(/sabriel/v1[^&]*)#', $uri, $pezzi ) ) {
			$rotta = $pezzi[1];
		}
		if ( '' === $rotta ) {
			return false;
		}

		return ! preg_match( self::ROTTE_DEL_PANNELLO, rtrim( $rotta, '/' ) );
	}

	public function lingua_bot_per_i_clienti( $locale ) {
		return $this->locale_bot_richiesta ? $this->locale_bot_richiesta : $locale;
	}

	public function cleanup_expired_transients() {
		global $wpdb;
		$now          = time();
		$timeout_keys = $wpdb->get_col( $wpdb->prepare(
			"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND option_value < %d LIMIT %d",
			$wpdb->esc_like( '_transient_timeout_sab' ) . '%',
			$now,
			self::CLEANUP_BATCH_SIZE
		) );
		foreach ( $timeout_keys as $k ) {
			$name = str_replace( '_transient_timeout_', '', $k );
			delete_transient( $name );
		}

		if ( count( $timeout_keys ) >= self::CLEANUP_BATCH_SIZE && ! wp_next_scheduled( self::CLEANUP_HOOK ) ) {
			wp_schedule_single_event( time() + MINUTE_IN_SECONDS, self::CLEANUP_HOOK );
		}
	}
}
