<?php
/**
 * Global Tabs Class
 *
 * Handles the Global Tabs admin interface and functionality.
 *
 * @package RedFoxWP\RedFoxTabManager
 * @since 1.0.0
 */

namespace RedFoxWP\RedFoxTabManager;

use RedFoxWP\RedFoxTabManager\Abstracts\Abstract_Singleton;

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Class Global_Tabs
 *
 * Handles the Global Tabs admin page and related functionality.
 *
 * @since 1.0.0
 */
class Global_Tabs extends Abstract_Singleton {

	/**
	 * Option name for storing global tabs.
	 *
	 * @since 1.0.0
	 * @access public
	 * @static
	 *
	 * @var string
	 */
	const OPTION_NAME = 'redfox_tab_manager_global_tabs';

	/**
	 * Get default WooCommerce tabs.
	 *
	 * @since 1.0.0
	 * @access private
	 *
	 * @return array Default WooCommerce tabs.
	 */
	private function get_default_woocommerce_tabs() {
		return array(
			array(
				'id'       => 'description',
				'title'    => __( 'Description', 'redfox-tab-manager' ),
				'content'  => '',
				'priority' => 0, // 10 * 0 = 0 (first position)
				'enabled'  => true,
				'type'     => 'woocommerce_default',
				'source'   => 'woocommerce',
			),
			array(
				'id'       => 'additional_information',
				'title'    => __( 'Additional Information', 'redfox-tab-manager' ),
				'content'  => '',
				'priority' => 10, // 10 * 1 = 10 (second position)
				'enabled'  => true,
				'type'     => 'woocommerce_default',
				'source'   => 'woocommerce',
			),
			array(
				'id'       => 'reviews',
				'title'    => __( 'Reviews', 'redfox-tab-manager' ),
				'content'  => '',
				'priority' => 20, // 10 * 2 = 20 (third position)
				'enabled'  => true,
				'type'     => 'woocommerce_default',
				'source'   => 'woocommerce',
			),
		);
	}

	/**
	 * Get global tabs from database.
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return array Global tabs.
	 */
	public function get_global_tabs() {
		$tabs = get_option( self::OPTION_NAME, array() );

		// If no tabs exist, initialize with default WooCommerce tabs.
		if ( empty( $tabs ) ) {
			$tabs = $this->get_default_woocommerce_tabs();
			update_option( self::OPTION_NAME, $tabs );
		}

		// Sort tabs by priority (lower numbers first) to maintain order.
		if ( is_array( $tabs ) ) {
			usort(
				$tabs,
				function ( $a, $b ) {
					$priority_a = isset( $a['priority'] ) ? $a['priority'] : 0;
					$priority_b = isset( $b['priority'] ) ? $b['priority'] : 0;
					return $priority_a - $priority_b;
				}
			);
		}

		return $tabs;
	}

	/**
	 * Reset global tabs to default WooCommerce tabs
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return array Default tabs after reset.
	 */
	public function reset_to_defaults() {
		// Delete the existing option.
		delete_option( self::OPTION_NAME );

		// Get default tabs (this will also save them to the database).
		return $this->get_global_tabs();
	}
}
