<?php

namespace Blazemedia\Affiliation\AdminUserInterface\Settings;

use Blazemedia\Affiliation\AdminUserInterface\Settings\Capability;
use Blazemedia\Affiliation\Utils\HttpRequest;

/**
 * Generated by the WordPress Option Page generator
 * at http://jeremyhixon.com/wp-tools/option-page/
 */

class CacheAndTransient {


	private $affiliation_settings_options;

	public function __construct() {

		if (!empty($_POST)) {

			if (isset($_POST['flush_transient_command']) && $_POST['flush_transient_command'] == 'purge') {
				// Verifica permessi
				if (!current_user_can('manage_options')) {
					wp_die('Permessi insufficienti');
				}

				// Verifica nonce
				if (!isset($_POST['flush_transient_nonce']) || !wp_verify_nonce($_POST['flush_transient_nonce'], 'flush_transient_action')) {
					wp_die('Verifica di sicurezza fallita');
				}

				// Richiede solo sidebar sbloccata (nessuna password aggiuntiva)
				if (!$this->isSidebarUnlocked()) {
					header("location: ./admin.php?page=affiliation-settings&flush_result=locked");
					exit;
				}

				$this->purge();
				header("location: ./admin.php?page=affiliation-settings&flush_result=purge_success");
			}
		}

		add_action('admin_head', [$this, 'transientFlushedNotice']);
		add_action('admin_head', [$this, 'cacheFlushedNotice']);
		add_action('rest_api_init', [$this, 'setPurgeTransientRouting'], 1);

		// Aggiungi il menu nella barra superiore per svuotare i meta dei formati
		add_action('admin_bar_menu', [$this, 'add_admin_bar_menu'], 100);
		add_action('wp_ajax_clear_post_formats_meta', [$this, 'clear_post_formats_meta']);
	}

	public function purge() {

		$this->delete_transients_with_prefix('gt_');
		$this->delete_transients_with_prefix('format-provider');

		// Svuotare la cache degli oggetti
		wp_cache_flush();

		// Svuota tutti i meta dei formati di affiliazione
		$this->delete_affiliation_formats_meta();
	}

	private function delete_affiliation_formats_meta() {
		global $wpdb;

		// Elimina tutti i meta con chiave "_blz_affiliation_formats"
		$deleted_formats = $wpdb->delete(
			$wpdb->postmeta,
			array('meta_key' => '_blz_affiliation_formats'),
			array('%s')
		);

		// Elimina tutti i meta con chiave "_blz_affiliation_formats_signature"
		$deleted_signatures = $wpdb->delete(
			$wpdb->postmeta,
			array('meta_key' => '_blz_affiliation_formats_signature'),
			array('%s')
		);

		// Elimina anche i meta hook
		$deleted_formats_hook = $wpdb->delete(
			$wpdb->postmeta,
			array('meta_key' => '_blz_affiliation_formats_hook'),
			array('%s')
		);

		$deleted_signatures_hook = $wpdb->delete(
			$wpdb->postmeta,
			array('meta_key' => '_blz_affiliation_formats_signature_hook'),
			array('%s')
		);

		// Log del risultato (opzionale)
		if ($deleted_formats || $deleted_signatures || $deleted_formats_hook || $deleted_signatures_hook) {
			error_log(sprintf(
				'Affiliation meta purged: %d formats, %d signatures, %d formats_hook, %d signatures_hook deleted',
				$deleted_formats,
				$deleted_signatures,
				$deleted_formats_hook,
				$deleted_signatures_hook
			));
		}
	}

	private function isSidebarUnlocked(): bool
	{
		$userId = get_current_user_id();
		$key = 'affiliation_sidebar_unlocked_' . (int) $userId;
		return (bool) get_transient($key);
	}

	public function setPurgeTransientRouting() {

		register_rest_route("api/v1", "/purge_transients", [

			'methods'  => 'GET',
			'callback' => array($this, 'purgeData'),
			'permission_callback' => '__return_true'
		]);
	}

	public function purgeData($request) {

		$this->purge();
		return rest_ensure_response(['SUCCESS' => 'OK']);
		exit;
	}


	protected function getDomain() {

		return preg_replace('/^.*?\.(.*?\..*?)$/', '$1', home_url());
	}


	public static function transientFlushedNotice() {

		if (strpos($_SERVER['REQUEST_URI'], "transients_flushed") == true) {
			echo '<div class="notice notice-success"><p>✅ <strong>Transient Formati</strong> vuotati correttamente</p></div>';
		}
	}

	public static function cacheFlushedNotice() {
		if (strpos($_SERVER['REQUEST_URI'], "cache_flushed") == true) {
			echo '<div class="notice notice-success"><p>✅ <strong>Cache del Randering Manager</strong> vuotata per questo dominio</p></div>';
		}
		if (strpos($_SERVER['REQUEST_URI'], "cache_not_flushed") == true) {
			echo '<div class="notice notice-error"><p>⛔ <strong>Password errata</strong></p></div>';
		}
		if (strpos($_SERVER['REQUEST_URI'], "formats_meta_cleared") == true) {
			echo '<div class="notice notice-success"><p>✅ <strong>Meta dei formati</strong> svuotati correttamente per questo post</p></div>';
		}
		if (strpos($_SERVER['REQUEST_URI'], "transients_not_flushed") == true) {
			echo '<div class="notice notice-error"><p>⛔ <strong>Password errata</strong></p></div>';
		}
	}



	public function delete_transients_with_prefix($prefix) {
		foreach ($this->get_transient_keys_with_prefix($prefix) as $key) {
			delete_transient($key);
		}
	}

	function get_transient_keys_with_prefix($prefix) {
		global $wpdb;

		$prefix = $wpdb->esc_like('_transient_' . $prefix);
		$sql    = "SELECT `option_name` FROM $wpdb->options WHERE `option_name` LIKE '%s'";
		$keys   = $wpdb->get_results($wpdb->prepare($sql, $prefix . '%'), ARRAY_A);

		if (is_wp_error($keys)) {
			return [];
		}

		return array_map(function ($key) {
			// Remove '_transient_' from the option name.
			return ltrim($key['option_name'], '_transient_');
		}, $keys);
	}


	/**
	 * Aggiunge il menu nella barra superiore di WordPress
	 */
	public function add_admin_bar_menu($wp_admin_bar) {

		// Mostra il menu solo nelle pagine di modifica dei post
		if (!is_admin() || !$this->is_edit_post_screen()) {
			return;
		}

		$post_id = $this->get_current_post_id();
		if (!$post_id) {
			return;
		}

		// Verifica se il post ha i meta dei formati
		if (!$this->post_has_formats_meta($post_id)) {
			return;
		}

		$wp_admin_bar->add_menu(array(
			'id'    => 'clear-formats-meta',
			'title' => '🗑️ Svuota Formati del Post',
			'href'  => '#',
			'meta'  => array(
				'onclick' => 'clearPostFormatsMeta(' . $post_id . '); return false;',
				'title'   => 'Svuota i meta dei formati per questo post'
			)
		));

		// Aggiungi JavaScript inline
		add_action('admin_footer', [$this, 'add_clear_formats_js']);
	}

	/**
	 * Verifica se siamo nella schermata di modifica del post
	 */
	private function is_edit_post_screen() {
		global $pagenow;
		return $pagenow === 'post.php' || ($pagenow === 'post-new.php');
	}

	/**
	 * Ottiene l'ID del post corrente
	 */
	private function get_current_post_id() {
		global $post;

		if (isset($_GET['post']) && is_numeric($_GET['post'])) {
			return (int) $_GET['post'];
		}

		if (isset($post->ID)) {
			return $post->ID;
		}

		return false;
	}

	/**
	 * Verifica se il post ha i meta dei formati
	 */
	private function post_has_formats_meta($post_id) {
		$formats = get_post_meta($post_id, '_blz_affiliation_formats', true);
		$signature = get_post_meta($post_id, '_blz_affiliation_formats_signature', true);
		$formatsHook = get_post_meta($post_id, '_blz_affiliation_formats_hook', true);
		$signatureHook = get_post_meta($post_id, '_blz_affiliation_formats_signature_hook', true);
		
		return !empty($formats) || !empty($signature) || !empty($formatsHook) || !empty($signatureHook);
	}

	/**
	 * Gestisce la richiesta AJAX per svuotare i meta dei formati
	 */
	public function clear_post_formats_meta() {

		// Verifica il nonce
		if (!wp_verify_nonce($_POST['nonce'], 'clear_formats_meta_nonce')) {
			wp_die('Errore di sicurezza');
		}

		// Verifica i permessi
		if (!current_user_can('edit_posts')) {
			wp_die('Permessi insufficienti');
		}

		$post_id = intval($_POST['post_id']);

		if (!$post_id) {
			wp_send_json_error('ID post non valido');
		}

		// Rimuovi i meta dei formati
		$deleted_formats = delete_post_meta($post_id, '_blz_affiliation_formats');
		$deleted_signature = delete_post_meta($post_id, '_blz_affiliation_formats_signature');
		$deleted_formatsHook = delete_post_meta($post_id, '_blz_affiliation_formats_hook');
		$deleted_signatureHook = delete_post_meta($post_id, '_blz_affiliation_formats_signature_hook');
		if ($deleted_formats || $deleted_signature || $deleted_formatsHook || $deleted_signatureHook) {
			wp_send_json_success('Meta dei formati svuotati con successo');
		} else {
			wp_send_json_error('Nessun meta da svuotare trovato');
		}
	}

	/**
	 * Aggiunge il JavaScript per gestire la pulizia dei meta
	 */
	public function add_clear_formats_js() {
		$nonce = wp_create_nonce('clear_formats_meta_nonce');
?>
		<script type="text/javascript">
			function clearPostFormatsMeta(postId) {
				if (!confirm('Sei sicuro di voler svuotare i meta dei formati per questo post? Questa azione non può essere annullata.')) {
					return;
				}

				jQuery.ajax({
					url: ajaxurl,
					type: 'POST',
					data: {
						action: 'clear_post_formats_meta',
						post_id: postId,
						nonce: '<?php echo $nonce; ?>'
					},
					success: function(response) {
						if (response.success) {
							alert('✅ ' + response.data);
							// Ricarica la pagina per aggiornare l'interfaccia
							location.reload();
						} else {
							alert('❌ Errore: ' + response.data);
						}
					},
					error: function() {
						alert('❌ Errore durante la richiesta');
					}
				});
			}
		</script>
<?php
	}
}
