<?php

/**
 * Enable/disable pattern sets
 */
/**
 * Add submenu to DragBlock Main Menu
 */
add_action('admin_menu', 'dragblock_admin_menu_patterns');
function dragblock_admin_menu_patterns()
{
	add_submenu_page(
		DRAGBLOCK_ADMIN_MENU_SLUG,
		__('Pattern Sets', 'dragblock'),
		__('Pattern Sets', 'dragblock'),
		'manage_options',
		DRAGBLOCK_PATTERNS,
		'dragblock_render_patterns_page' // Specify the callback function here
	);
}

function dragblock_pattern_action()
{
	if (!isset($_GET['nonce']) || !isset($_GET['action']) || !isset($_GET['pattern_set'])) {
		return;
	}
	// Verify nonce
	$nonce = sanitize_text_field(wp_unslash($_GET['nonce']));
	if (!wp_verify_nonce($nonce, DRAGBLOCK_PATTERN_SETS)) {
		wp_die('Wrong nonce');
		return;
	}

	$action = sanitize_text_field(wp_unslash($_GET['action']));
	$set = sanitize_text_field(wp_unslash($_GET['pattern_set']));

	$enabled = get_option(DRAGBLOCK_PATTERN_SETS, array('dragblock' => true));

	$enabled[$set] = $action === 'activate';
	update_option(DRAGBLOCK_PATTERN_SETS, $enabled);
}

// Callback function to render the content of the submenu page with a table
function dragblock_render_patterns_page()
{
	// var_dump(WP_Block_Pattern_Categories_Registry::get_instance()->get_all_registered( )); die();
	// var_dump(WP_Block_Patterns_Registry::get_instance()->get_all_registered( )); die();
	dragblock_pattern_action();

	// load all pattern sets
	$pattern_sets = array(
		'dragblock' => __('DragBlock Free Patterns', 'dragblock'),
		'core' => __('WordPress Core Patterns', 'dragblock'),
	);

	// register patterns
	foreach (WP_Block_Patterns_Registry::get_instance()->get_all_registered() as $pattern) {
		$slug = !empty($pattern['slug']) ? $pattern['slug'] : (
			!empty($pattern['name']) ? $pattern['name'] : ''
		);
		$slug = explode('/', $slug)[0];
		$pattern_sets[$slug] = ucwords(implode(' ', explode('-', $slug)) . ' ' . __('Patterns', 'dragblock'));
	}
	// $pattern_sets[''] = __('Uncategorized Patterns');

	// Include necessary WordPress files for List Table API
	require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');

	// Define your custom table class
	// check more in /Users/sneeit/Sites/wordpress/app/public/wp-admin/includes/class-wp-plugins-list-table.php
	class DragBlock_Patterns_Table extends WP_List_Table
	{
		public $enabled_pattern_sets = array();

		function __construct($pattern_sets = array())
		{
			parent::__construct(array(
				'singular' => 'plugin',
				'plural'   => 'plugins', // we use 'plugins' here to take advantage of active styles
				'ajax'     => false
			));

			$this->items = array();
			foreach ($pattern_sets as $slug => $name) {
				array_push($this->items, array(
					'name' => $name,
					'slug' => $slug
				));
			}
			// read enabled pattern sets
			$this->enabled_pattern_sets = get_option(DRAGBLOCK_PATTERN_SETS, array('dragblock' => true));
		}

		// Define columns
		function get_columns()
		{
			$columns = array(
				// 'cb'       => '<input type="checkbox" />',
				'name'     => __('Pattern Sets', 'dragblock'),
				// 'description' => __('Description', 'dragblock')
			);
			return $columns;
		}

		// Prepare items
		function prepare_items()
		{
			$this->_column_headers = array($this->get_columns(), array(), array());
		}

		public function single_row($item)
		{
			$pattern_set_slug = isset($item['slug']) ? $item['slug'] : '';
			$pattern_set_name = isset($item['name']) ? $item['name'] : '';
			$is_active = !empty($this->enabled_pattern_sets[$pattern_set_slug]);

			// Generate a nonce
			$nonce = wp_create_nonce(DRAGBLOCK_PATTERN_SETS);

			// Append the nonce to the URL
			$action_href = add_query_arg(
				array(
					'page' => DRAGBLOCK_PATTERNS,
					'pattern_set' => $pattern_set_slug,
					'action' => ($is_active ? 'deactivate' : 'activate'),
					'nonce' => $nonce // Append the nonce parameter
				),
				admin_url('admin.php')
			);

			$action_text = $is_active ? __('Deactivate', 'dragblock') : __('Activate', 'dragblock');
			$row_class = $is_active ? 'active' : 'inactive';

			echo '<tr class="' . $row_class . '"><td class="plugin-title column-primary">';
			echo '<strong>' . esc_html($pattern_set_name) . '</strong>';
			echo '<a href="' . esc_attr($action_href) . '">' . esc_html($action_text) . '</a>';
			echo '</td></tr>';
		}


		// Render the checkbox column
		function column_cb($item)
		{
			return '<input type="checkbox" />';
		}
	}

	// Create an instance of your custom table class
	$patterns_table = new DragBlock_Patterns_Table($pattern_sets);

	// Prepare items
	$patterns_table->prepare_items();
	$enabled = 0;

	foreach ($patterns_table->enabled_pattern_sets as $pattern) {
		if ($pattern) {
			$enabled++;
		}
	}

	// Render the table
	echo '<div class="wrap">';
	echo '<h2>' . __('Pattern Sets', 'dragblock') . '</h2>';

	if ($enabled > 3) {
		echo '<div class="notice notice-warning"><p>' . __('Warning: Enabling more than 3 pattern sets could hang up your editor.', 'dragblock') . '</p></div>';
	}
	$patterns_table->display();
	echo '</div>';
}

add_filter('rest_api_init', 'modify_block_patterns_response', 100);
function modify_block_patterns_response()
{
	/// disabled the pattern sets when registered
	$enabled = get_option(DRAGBLOCK_PATTERN_SETS, array('dragblock' => true));
	if (empty($enabled['core'])) {
		remove_theme_support('core-block-patterns');
	}
	foreach (WP_Block_Patterns_Registry::get_instance()->get_all_registered() as $pattern) {
		$slug = !empty($pattern['slug']) ? $pattern['slug'] : (
			!empty($pattern['name']) ? $pattern['name'] : ''
		);
		$pattern_set = strpos($slug, '/') !== false ? explode('/', $slug)[0] : 'core';
		if (!empty($enabled[$pattern_set])) {
			continue;
		}

		unregister_block_pattern($slug);
	}
}
