<?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\Abstracts\BaseProvider;

class Options extends BaseProvider {

	/**
	 * The list of array
	 * @var array
	 */
	protected $args;

	/**
	 * The settings page instance
	 * @var SettingsPage
	 */
	protected $settings_page;

	/**
	 * Constructor
	 */
	public function register() {

		// Add header bar to settings page
		add_action( 'in_admin_header', [ $this, 'render_header_bar' ] );

		$required_sections = [
			[
				'id'    => 'overview',
				'title' => __( 'Overview', 'vimeify' ),
			],
		];

		if ( $this->plugin->system()->vimeo()->state->is_connected ) {
			$required_settings = [
				[
					'id'      => 'connection',
					'label'   => __( 'Connection', 'vimeify' ),
					'type'    => 'html',
					'section' => 'overview',
					'markup'  => [ $this, 'create_overview_connection' ],
				],
				[
					'id'      => 'environment',
					'label'   => __( 'Environment', 'vimeify' ),
					'type'    => 'html',
					'section' => 'overview',
					'markup'  => [ $this, 'create_overview_environment' ],
				],
				[
					'id'      => 'issues',
					'label'   => __( 'Troubleshooting', 'vimeify' ),
					'type'    => 'html',
					'section' => 'overview',
					'markup'  => [ $this, 'create_overview_issues' ],
				],

			];
		} else {
			$required_settings = [
				/**
				 * API Connection
				 */
				[
					'id'      => 'authentication',
					'label'   => __( 'Authentication', 'vimeify' ),
					'type'    => 'html',
					'section' => 'overview',
					'markup'  => [ $this, 'create_api_auth_form' ],
				],

			];
		}


		$other_sections = [];
		$other_settings = [];

		if ( $this->plugin->system()->vimeo()->state->is_connected ) {

			require_once( ABSPATH . 'wp-includes/pluggable.php' );

			$other_sections = [
				[
					'id'    => 'admin',
					'title' => __( 'Admin Settings', 'vimeify' ),
				],
				[
					'id'    => 'frontend',
					'title' => __( 'Frontend Settings', 'vimeify' ),
				],
				[
					'id'    => 'sync',
					'title' => __( 'Sync Settings', 'vimeify' ),
				],
				[
					'id'    => 'upload_profiles',
					'title' => __( 'Upload Profiles', 'vimeify' ),
				],
			];

			$other_settings = [
				[
					'id'           => 'behavior',
					'label'        => __( 'Front-end Behavior', 'vimeify' ),
					'desc'         => '',
					'std'          => '',
					'type'         => 'checkbox',
					'section'      => 'frontend',
					'rows'         => '',
					'post_type'    => '',
					'taxonomy'     => '',
					'min_max_step' => '',
					'class'        => '',
					'condition'    => '',
					'operator'     => 'and',
					'group'        => true,
					'choices'      => array(
						'enable_single_pages' => array(
							'value' => 1,
							'label' => __( 'Enable single video pages for the uploaded videos', 'vimeify' ),
							'src'   => '',
						),
					),
				],

				//
				// Sync Settings
				[
					'id'           => 'sync_behavior',
					'label'        => __( 'Video Sync Behavior', 'vimeify' ),
					'desc'         => __( 'Choose how the automatic sync should handle videos from your Vimeo account.', 'vimeify' ),
					'std'          => 'existing_only',
					'type'         => 'radio',
					'section'      => 'sync',
					'rows'         => '',
					'post_type'    => '',
					'taxonomy'     => '',
					'min_max_step' => '',
					'class'        => '',
					'condition'    => '',
					'operator'     => 'and',
					'choices'      => array(
						array(
							'value' => 'existing_only',
							'label' => __( 'Update existing videos only', 'vimeify' ),
							'src'   => '',
						),
						array(
							'value' => 'create_all',
							'label' => __( 'Sync all videos from Vimeo and create local entries', 'vimeify' ),
							'src'   => '',
						),
					),
				],
				[
					'id'      => 'sync_status_link',
					'label'   => __( 'Sync Status', 'vimeify' ),
					'type'    => 'html',
					'section' => 'sync',
					'markup'  => [ $this, 'create_sync_status_link' ],
				],

				//
				// Admin Settngs
				[
					'id'           => 'upload_forms',
					'label'        => __( 'Upload Form', 'vimeify' ),
					'desc'         => '',
					'std'          => '',
					'type'         => 'checkbox',
					'section'      => 'admin',
					'rows'         => '',
					'post_type'    => '',
					'taxonomy'     => '',
					'min_max_step' => '',
					'class'        => '',
					'condition'    => '',
					'operator'     => 'and',
					'group'        => true,
					'choices'      => array(
						'enable_view_privacy' => array(
							'value' => 1,
							'label' => __( 'Enable Vimeo View Privacy option in the WP-Admin Video upload form', 'vimeify' ),
							'src'   => '',
						),
						'enable_folders'      => array(
							'value' => 1,
							'label' => __( 'Enable Vimeo Folders option in the WP-Admin Video upload form', 'vimeify' ),
							'src'   => '',
						),
					),
				],
				[
					'id'           => 'gutenberg',
					'label'        => __( 'Gutenberg Block', 'vimeify' ),
					'desc'         => '',
					'std'          => '',
					'type'         => 'checkbox',
					'section'      => 'admin',
					'rows'         => '',
					'post_type'    => '',
					'taxonomy'     => '',
					'min_max_step' => '',
					'class'        => '',
					'condition'    => '',
					'operator'     => 'and',
					'group'        => true,
					'choices'      => array(
						'enable_view_privacy'      => array(
							'value' => 1,
							'label' => __( 'Enable Vimeo View Privacy option in Gutenberg upload modal', 'vimeify' ),
							'src'   => '',
						),
						'enable_folders'           => array(
							'value' => 1,
							'label' => __( 'Enable Vimeo Folders dropdown in Gutenberg upload modal', 'vimeify' ),
							'src'   => '',
						),
						'enable_account_search'    => array(
							'value' => 1,
							'label' => __( 'Enable Vimeo account search option in upload form', 'vimeify' ),
							'src'   => '',
						),
						'enable_local_search'      => array(
							'value' => 1,
							'label' => __( 'Enable Local Library search option in upload form', 'vimeify' ),
							'src'   => '',
						),
						'show_author_uploads_only' => array(
							'value' => 1,
							'label' => __( 'Restrict to current user\'s uploads in Local Library search option', 'vimeify' ),
							'src'   => '',
						)
					),
				],

				[
					'id'           => 'tinymce',
					'label'        => __( 'TinyMCE Modal', 'vimeify' ),
					'desc'         => '',
					'std'          => '',
					'type'         => 'checkbox',
					'section'      => 'admin',
					'rows'         => '',
					'post_type'    => '',
					'taxonomy'     => '',
					'min_max_step' => '',
					'class'        => '',
					'condition'    => '',
					'operator'     => 'and',
					'group'        => true,
					'choices'      => array(
						'enable_view_privacy'      => array(
							'value' => 1,
							'label' => __( 'Enable Vimeo View Privacy option in upload modal', 'vimeify' ),
							'src'   => '',
						),
						'enable_folders'           => array(
							'value' => 1,
							'label' => __( 'Enable Vimeo Folders option in upload modal', 'vimeify' ),
							'src'   => '',
						),
						'enable_account_search'    => array(
							'value' => 1,
							'label' => __( 'Enable Vimeo account search option in upload modal', 'vimeify' ),
							'src'   => '',
						),
						'enable_local_search'      => array(
							'value' => 1,
							'label' => __( 'Enable local library search option in upload modal', 'vimeify' ),
							'src'   => '',
						),
						'show_author_uploads_only' => array(
							'value' => 1,
							'label' => __( 'Restrict to current user\'s uploads in local library search option', 'vimeify' ),
							'src'   => '',
						)
					),
				],

				[
					'id'           => 'video_management',
					'label'        => __( 'Video Management Page', 'vimeify' ),
					'desc'         => __( 'Select which video elements to be enabled for editing videos.', 'vimeify' ),
					'std'          => '',
					'type'         => 'checkbox',
					'section'      => 'admin',
					'rows'         => '',
					'post_type'    => '',
					'taxonomy'     => '',
					'min_max_step' => '',
					'class'        => '',
					'condition'    => '',
					'operator'     => 'and',
					'group'        => true,
					'choices'      => array(
						'enable_embed_presets' => array(
							'value' => 1,
							'label' => __( 'Enable Embed Presets panel in the single video management page', 'vimeify' ),
							'src'   => '',
						),
						'enable_embed_privacy' => array(
							'value' => 1,
							'label' => __( 'Enable Embed Privacy panel in the single video management page', 'vimeify' ),
							'src'   => '',
						),
						'enable_folders'       => array(
							'value' => 1,
							'label' => __( 'Enable Folders panel in the single video management page', 'vimeify' ),
							'src'   => '',
						),
					),
				],

				[
					'id'           => 'videos_list_table',
					'label'        => __( 'Videos list table', 'vimeify' ),
					'desc'         => '',
					'std'          => '',
					'type'         => 'checkbox',
					'section'      => 'admin',
					'rows'         => '',
					'post_type'    => '',
					'taxonomy'     => '',
					'min_max_step' => '',
					'class'        => '',
					'condition'    => '',
					'operator'     => 'and',
					'group'        => true,
					'choices'      => array(
						'enable_thumbnails'        => array(
							'value' => 1,
							'label' => __( 'Enable thumbnails near the Video title', 'vimeify' ),
							'src'   => '',
						),
						'show_author_uploads_only' => array(
							'value' => 1,
							'label' => __( 'Only show the Videos uploaded by the current user on the Vimeo list table', 'vimeify' ),
							'src'   => '',
						)
					),
				],
			];

			/**
			 * Add upload profiles
			 */
			foreach ( $this->get_upload_profiles() as $profile ) {
				if ( ! isset( $profile['key'] ) || ! isset( $profile['title'] ) || ! isset( $profile['desc'] ) ) {
					continue;
				}
				array_push( $other_settings, $this->create_upload_profile_option(
					$profile['key'],
					$profile['title'],
					$profile['desc'],
				) );
			}
		}

		/**
		 * Allow filter to modify them
		 */
		$sections = array_merge( $required_sections, $other_sections );
		$settings = array_merge( $required_settings, $other_settings );
		$sections = apply_filters( 'vimeify_settings_sections', $sections );
		$settings = apply_filters( 'vimeify_settings_fields', $settings );


		$this->register_options( $sections, $settings );
	}

	/**
	 * Create the overview
	 * @return false|string
	 */
	public function create_overview_connection() {
		return wp_kses(
			'<table class="vimeify-status-wrapper">' . $this->plugin->system()->views()->get_view( 'admin/partials/status-api', array(
				'plugin' => $this->plugin
			) ) . '</table>',
			wp_kses_allowed_html( 'vimeify' )
		);
	}

	/**
	 * Create the overview
	 * @return false|string
	 */
	public function create_overview_environment() {
		return wp_kses(
			'<table class="vimeify-status-wrapper">' . $this->plugin->system()->views()->get_view( 'admin/partials/status-env', array(
				'plugin' => $this->plugin
			) ) . '</table>',
			wp_kses_allowed_html( 'vimeify' )
		);
	}

	/**
	 * Create the overview
	 * @return false|string
	 */
	public function create_overview_issues() {
		return wp_kses(
			'<table class="vimeify-status-wrapper">' . $this->plugin->system()->views()->get_view( 'admin/partials/status-issues', array(
				'plugin' => $this->plugin
			) ) . '</table>',
			wp_kses_allowed_html( 'vimeify' )
		);
	}

	public function create_api_auth_form() {
		return wp_kses(
			'<table class="vimeify-status-wrapper">' . $this->plugin->system()->views()->get_view( 'admin/partials/auth-form', array(
				'plugin' => $this->plugin
			) ) . '</table>',
			wp_kses_allowed_html( 'vimeify' )
		);
	}

	/**
	 * Create sync status link to Action Scheduler
	 *
	 * @return string
	 */
	public function create_sync_status_link() {
		$url = admin_url( 'tools.php?page=action-scheduler&s=vimeify&action=-1&action2=-1&orderby=schedule&order=desc' );

		$html = '<div class="vimeify-sync-status-link">';
		$html .= '<p>' . esc_html__( 'Background sync tasks are managed by Action Scheduler. You can view the status of all scheduled sync jobs below:', 'vimeify' ) . '</p>';
		$html .= '<p><a href="' . esc_url( $url ) . '" class="button button-secondary" target="_blank">';
		$html .= esc_html__( 'View Sync Status & Scheduled Tasks', 'vimeify' );
		$html .= ' <span class="dashicons dashicons-external" style="margin-top: 3px;"></span>';
		$html .= '</a></p>';
		$html .= '<p class="description">';
		$html .= esc_html__( 'This will show you all scheduled sync tasks including metadata sync (every 10 minutes), status sync (every 20 minutes), and cleanup tasks (hourly).', 'vimeify' );
		$html .= '</p>';
		$html .= '</div>';

		return $html;
	}

	/**
	 * Registers the options
	 *
	 * @param $sections
	 * @param $settings
	 *
	 * @return void
	 */
	protected function register_options( $sections, $settings ) {
		$this->args = [
			'id'    => $this->plugin->settings_key(),
			'pages' => [
				[
					'id'              => $this->plugin->settings_key(),
					'parent_slug'     => 'vimeify',
					'page_title'      => __( 'Settings', 'vimeify' ),
					'menu_title'      => __( 'Settings', 'vimeify' ),
					'capability'      => apply_filters( 'vimeify_manage_options_capability', 'manage_options' ),
					'menu_slug'       => 'vimeify-settings',
					'icon_url'        => null,
					'position'        => null,
					'updated_message' => __( 'Options updated!', 'vimeify' ),
					'reset_message'   => __( 'Options reset!', 'vimeify' ),
					'button_text'     => __( 'Save changes', 'vimeify' ),
					'show_buttons'    => true,
					'show_subheader'  => false,
					'hide_reset'      => true,
					'screen_icon'     => 'options-general',
					'sections'        => $sections,
					'settings'        => $settings
				]
			]
		];

		$this->args = apply_filters( 'vimeify_settings_args', $this->args );

		$this->settings_page = new SettingsPage( $this->plugin, $this->args );
		$this->settings_page->register();
	}

	/**
	 * The default lazyloaded options
	 *
	 * @param $option
	 * @param $section
	 *
	 * @return array[]
	 */
	public function get_lazyloaded_options( $option, $section ) {
		$current_value = $this->plugin->system()->settings()->global()->get( sprintf( '%s.%s', $section, $option ), '' );
		$current_name  = ! empty( $current_value ) && ( 'default' != $current_value ) ? get_the_title( $current_value ) : __( 'Default', 'vimeify' );

		return [
			[
				'value' => $current_value,
				'label' => $current_name,
			]
		];

	}


	public function create_upload_profile_option( $id, $title, $description ) {
		return [
			'id'           => $id,
			'label'        => $title,
			'desc'         => $description,
			'std'          => '',
			'type'         => 'select',
			'section'      => 'upload_profiles',
			'ajax'         => [
				'endpoint' => admin_url( 'admin-ajax.php' ),
				'action'   => 'vimeify_upload_profile_search',
				'nonce'    => \wp_create_nonce( 'vimeify_nonce' )
			],
			'placeholder'  => __( 'Select profile...', 'vimeify' ),
			'rows'         => '',
			'post_type'    => '',
			'taxonomy'     => '',
			'min_max_step' => '',
			'class'        => '',
			'condition'    => '',
			'operator'     => 'and',
			'group'        => true,
			'choices'      => $this->get_lazyloaded_options( $id, 'upload_profiles' ),
		];
	}

	/**
	 * Return upload profiles
	 * @return mixed|null
	 */
	public function get_upload_profiles() {
		return $this->plugin()
		            ->system()
		            ->settings()
		            ->profile()
		            ->get_profile_contexts();
	}

	/**
	 * Render the header bar on the settings page
	 * @return void
	 */
	public function render_header_bar() {
		$screen = get_current_screen();
		if ( ! $screen || strpos( $screen->id, 'vimeify-settings' ) === false ) {
			return;
		}

		$plugin = $this->plugin;
		include $this->plugin->path() . 'views/admin/partials/header-bar.php';
	}


}
