<?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\Metaboxes;

use Vimeify\Core\Abstracts\BaseProvider;
use Vimeify\Core\Components\Database;

class GalleryMeta extends BaseProvider {

	/**
	 * Registers specific piece of functionality
	 * @return void
	 */
	public function register() {
		add_action( 'add_meta_boxes', [ $this, 'register_metaboxes' ] );
		add_action( 'save_post_' . Database::POST_TYPE_GALLERY, [ $this, 'save_metabox' ], 10, 2 );
	}

	/**
	 * Register the metaboxes
	 * @return void
	 */
	public function register_metaboxes() {
		add_meta_box(
			'vimeify_gallery_videos',
			__( 'Gallery Videos', 'vimeify' ),
			[ $this, 'render_videos_metabox' ],
			Database::POST_TYPE_GALLERY,
			'normal',
			'high'
		);

		add_meta_box(
			'vimeify_gallery_settings',
			__( 'Gallery Settings', 'vimeify' ),
			[ $this, 'render_settings_metabox' ],
			Database::POST_TYPE_GALLERY,
			'side',
			'default'
		);
	}

	/**
	 * Render the videos metabox
	 * @param \WP_Post $post
	 * @return void
	 */
	public function render_videos_metabox( $post ) {
		wp_nonce_field( 'vimeify_gallery_meta', 'vimeify_gallery_meta_nonce' );

		$selected_videos = get_post_meta( $post->ID, '_vimeify_gallery_videos', true );
		if ( ! is_array( $selected_videos ) ) {
			$selected_videos = [];
		}

		$this->plugin->system()->views()->render_view( 'admin/metaboxes/gallery-videos', [
			'plugin'           => $this->plugin,
			'post'             => $post,
			'selected_videos'  => $selected_videos,
		] );
	}

	/**
	 * Render the settings metabox
	 * @param \WP_Post $post
	 * @return void
	 */
	public function render_settings_metabox( $post ) {
		$settings = get_post_meta( $post->ID, '_vimeify_gallery_settings', true );
		if ( ! is_array( $settings ) ) {
			$settings = [];
		}

		// Get available settings fields
		$fields = $this->get_settings_fields();

		$this->plugin->system()->views()->render_view( 'admin/metaboxes/gallery-settings', [
			'plugin'   => $this->plugin,
			'post'     => $post,
			'settings' => $settings,
			'fields'   => $fields,
		] );
	}

	/**
	 * Get the settings fields configuration
	 * Can be filtered by pro version or other extensions
	 * @return array
	 */
	public function get_settings_fields() {
		$fields = [
			[
				'id'      => 'posts_per_page',
				'label'   => __( 'Videos per page', 'vimeify' ),
				'type'    => 'number',
				'default' => 12,
				'desc'    => __( 'Number of videos to display per page', 'vimeify' ),
			],
			[
				'id'      => 'columns',
				'label'   => __( 'Columns', 'vimeify' ),
				'type'    => 'select',
				'options' => [
					'2' => '2',
					'3' => '3',
					'4' => '4',
					'6' => '6',
				],
				'default' => '3',
				'desc'    => __( 'Number of columns in the grid', 'vimeify' ),
			],
			[
				'id'      => 'show_title',
				'label'   => __( 'Show Video Title', 'vimeify' ),
				'type'    => 'checkbox',
				'default' => true,
				'desc'    => __( 'Display video titles below thumbnails', 'vimeify' ),
			],
			[
				'id'      => 'show_description',
				'label'   => __( 'Show Description', 'vimeify' ),
				'type'    => 'checkbox',
				'default' => false,
				'desc'    => __( 'Display video descriptions', 'vimeify' ),
			],
			[
				'id'      => 'order',
				'label'   => __( 'Order', 'vimeify' ),
				'type'    => 'radio',
				'options' => [
					'asc'  => __( 'Ascending', 'vimeify' ),
					'desc' => __( 'Descending', 'vimeify' ),
				],
				'default' => 'desc',
				'desc'    => __( 'Order direction for videos', 'vimeify' ),
			],
		];

		return apply_filters( 'vimeify_gallery_settings_fields', $fields, $this->plugin );
	}

	/**
	 * Save the metabox data
	 * @param int $post_id
	 * @param \WP_Post $post
	 * @return void
	 */
	public function save_metabox( $post_id, $post ) {
		// Check nonce
		if ( ! isset( $_POST['vimeify_gallery_meta_nonce'] ) || ! wp_verify_nonce( $_POST['vimeify_gallery_meta_nonce'], 'vimeify_gallery_meta' ) ) {
			return;
		}

		// Check autosave
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		// Check permissions
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// Save selected videos
		if ( isset( $_POST['vimeify_gallery_videos'] ) && is_array( $_POST['vimeify_gallery_videos'] ) ) {
			$video_ids = array_map( 'intval', $_POST['vimeify_gallery_videos'] );
			update_post_meta( $post_id, '_vimeify_gallery_videos', $video_ids );
		} else {
			update_post_meta( $post_id, '_vimeify_gallery_videos', [] );
		}

		// Save settings
		if ( isset( $_POST['vimeify_gallery_settings'] ) && is_array( $_POST['vimeify_gallery_settings'] ) ) {
			$settings = [];
			$fields = $this->get_settings_fields();

			foreach ( $fields as $field ) {
				$field_id = $field['id'];

				if ( isset( $_POST['vimeify_gallery_settings'][ $field_id ] ) ) {
					$value = $_POST['vimeify_gallery_settings'][ $field_id ];

					// Sanitize based on type
					switch ( $field['type'] ) {
						case 'number':
							$settings[ $field_id ] = intval( $value );
							break;
						case 'checkbox':
							$settings[ $field_id ] = (bool) $value;
							break;
						case 'text':
							$settings[ $field_id ] = sanitize_text_field( $value );
							break;
						default:
							$settings[ $field_id ] = sanitize_text_field( $value );
					}
				} else {
					// Handle unchecked checkboxes
					if ( $field['type'] === 'checkbox' ) {
						$settings[ $field_id ] = false;
					}
				}
			}

			update_post_meta( $post_id, '_vimeify_gallery_settings', $settings );
		}
	}

	/**
	 * Get gallery settings for a specific gallery
	 * @param int $gallery_id
	 * @return array
	 */
	public static function get_gallery_settings( $gallery_id ) {
		$settings = get_post_meta( $gallery_id, '_vimeify_gallery_settings', true );
		if ( ! is_array( $settings ) ) {
			$settings = [];
		}

		return $settings;
	}

	/**
	 * Get gallery videos for a specific gallery
	 * @param int $gallery_id
	 * @return array
	 */
	public static function get_gallery_videos( $gallery_id ) {
		$videos = get_post_meta( $gallery_id, '_vimeify_gallery_videos', true );
		if ( ! is_array( $videos ) ) {
			$videos = [];
		}

		return $videos;
	}
}
