<?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'){
				$this->purge();
				header("location: ./admin.php?page=affiliation-settings&transients_flushed=true");
			}

			
		}

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

	}

	public function purge() {

		$this->delete_transients_with_prefix('gt_');
		$this->delete_transients_with_prefix('format-provider');
		// Svuotare la cache degli oggetti
		wp_cache_flush();
    }


	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>';
		} 
    }

	

	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 );
	}




}