<?php
/********************************************************************
 * Copyright (C) 2024 Darko Gjorgjijoski (https://darkog.com/)
 * Copyright (C) 2024 IDEOLOGIX MEDIA Dooel (https://ideologix.com/)
 *
 * This file is property of IDEOLOGIX MEDIA Dooel (https://ideologix.com)
 * This file is part of Vimeify Plugin - https://wordpress.org/plugins/vimeify/
 *
 * Vimeify - Formerly "WP Vimeo Videos" is free software: you can redistribute
 * it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 2 of the License,
 * or (at your option) any later version.
 *
 * Vimeify - Formerly "WP Vimeo Videos" is distributed in the hope that it
 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this plugin. If not, see <https://www.gnu.org/licenses/>.
 *
 * Code developed by Darko Gjorgjijoski <dg@darkog.com>.
 **********************************************************************/

namespace Vimeify\Core\Backend;

use Vimeify\Core\Plugin;

class SettingsPage {

	/**
	 * The plugin instance
	 *
	 * @var Plugin
	 */
	protected $plugin;

	/**
	 * The settings page ID
	 *
	 * @var string
	 */
	protected $page_id;

	/**
	 * The page configuration
	 *
	 * @var array
	 */
	protected $config;

	/**
	 * Constructor
	 *
	 * @param Plugin $plugin
	 * @param array  $config
	 */
	public function __construct( Plugin $plugin, $config = array() ) {
		$this->plugin  = $plugin;
		$this->config  = $config;
		$this->page_id = isset( $config['id'] ) ? $config['id'] : 'vimeify_settings';
	}

	/**
	 * Register the settings page
	 *
	 * @return void
	 */
	public function register() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	/**
	 * Add the settings menu page
	 *
	 * @return void
	 */
	public function add_menu_page() {
		$page = isset( $this->config['pages'][0] ) ? $this->config['pages'][0] : array();

		$parent_slug = isset( $page['parent_slug'] ) ? $page['parent_slug'] : 'vimeify';
		$page_title  = isset( $page['page_title'] ) ? $page['page_title'] : __( 'Settings', 'vimeify' );
		$menu_title  = isset( $page['menu_title'] ) ? $page['menu_title'] : __( 'Settings', 'vimeify' );
		$capability  = isset( $page['capability'] ) ? $page['capability'] : 'manage_options';
		$menu_slug   = isset( $page['menu_slug'] ) ? $page['menu_slug'] : 'vimeify-settings';

		add_submenu_page(
			$parent_slug,
			$page_title,
			$menu_title,
			$capability,
			$menu_slug,
			array( $this, 'render_page' )
		);
	}

	/**
	 * Render the settings page
	 *
	 * @return void
	 */
	public function render_page() {
		$page       = isset( $this->config['pages'][0] ) ? $this->config['pages'][0] : array();
		$page_title = isset( $page['page_title'] ) ? $page['page_title'] : __( 'Settings', 'vimeify' );

		echo '<div class="wrap vimeify-wrap--with-header">';
		echo '<h1>' . esc_html( $page_title ) . '</h1>';
		echo '<div id="vimeify-settings-root" data-page-id="' . esc_attr( $this->page_id ) . '"></div>';
		echo '</div>';
	}

	/**
	 * Enqueue assets for the settings page
	 *
	 * @return void
	 */
	public function enqueue_assets() {
		if ( ! $this->is_settings_page() ) {
			return;
		}

		$page = isset( $this->config['pages'][0] ) ? $this->config['pages'][0] : array();

		// Prepare sections data
		$sections = isset( $page['sections'] ) ? $page['sections'] : array();

		// Prepare settings/fields data
		$settings = isset( $page['settings'] ) ? $page['settings'] : array();

		// Process HTML callbacks in settings
		$settings = $this->process_settings_callbacks( $settings );

		// Get current values
		$values = $this->plugin->system()->settings()->global()->all();

		// Prepare localized data
		$localized_data = array(
			'pageId'           => $this->page_id,
			'sections'         => $sections,
			'settings'         => $settings,
			'values'           => $values,
			'ajaxUrl'          => admin_url( 'admin-ajax.php' ),
			'nonce'            => wp_create_nonce( 'vimeify_nonce' ),
			'saveAction'       => 'vimeify_save_settings',
			'showButtons'      => isset( $page['show_buttons'] ) ? $page['show_buttons'] : true,
			'buttonText'       => isset( $page['button_text'] ) ? $page['button_text'] : __( 'Save changes', 'vimeify' ),
			'updatedMessage'   => isset( $page['updated_message'] ) ? $page['updated_message'] : __( 'Options updated!', 'vimeify' ),
			'documentationUrl' => $this->plugin->documentation_url(),
			'i18n'             => array(
				'saving'        => __( 'Saving...', 'vimeify' ),
				'saved'         => __( 'Saved!', 'vimeify' ),
				'error'         => __( 'Error saving settings', 'vimeify' ),
				'loading'       => __( 'Loading...', 'vimeify' ),
				'noResults'     => __( 'No results found', 'vimeify' ),
				'searching'     => __( 'Searching...', 'vimeify' ),
				'typeToSearch'  => __( 'Type to search...', 'vimeify' ),
				'documentation' => __( 'Documentation', 'vimeify' ),
			),
		);

		wp_localize_script( 'vimeify-settings', 'Vimeify_Settings', $localized_data );
	}

	/**
	 * Check if we're on the settings page
	 *
	 * @return bool
	 */
	protected function is_settings_page() {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return false;
		}

		$screen = get_current_screen();
		if ( ! $screen ) {
			return false;
		}

		return strpos( $screen->id, 'vimeify-settings' ) !== false;
	}

	/**
	 * Process settings callbacks (like HTML markup callbacks)
	 *
	 * @param array $settings
	 *
	 * @return array
	 */
	protected function process_settings_callbacks( $settings ) {
		foreach ( $settings as $key => $setting ) {
			// Process HTML type with callback
			if ( isset( $setting['type'] ) && $setting['type'] === 'html' ) {
				if ( isset( $setting['markup'] ) && is_callable( $setting['markup'] ) ) {
					$settings[ $key ]['markup'] = call_user_func( $setting['markup'] );
				}
			}

			// Process choices with callbacks if needed
			if ( isset( $setting['choices'] ) && is_callable( $setting['choices'] ) ) {
				$settings[ $key ]['choices'] = call_user_func( $setting['choices'] );
			}
		}

		return $settings;
	}
}
