<?php

/**
 * The plugin gutenberg block query Initializer.
 *
 * @link       https://shapedplugin.com/
 * @since      2.0.0
 *
 * @package    Smart_Post_Show_Pro
 * @subpackage Smart_Post_Show_Pro/blocks/includes
 * @author     ShapedPlugin <support@shapedplugin.com>
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Image and Video Meta Field Class
 */
class Image_And_Video_Meta_Field {

	/**
	 * Constructor for the class.
	 */
	public function __construct() {

		$module_option = get_option( 'sp-pcp-blocks-modules-options', array() );

		$image_gallery = true;
		$feature_video = true;

		if ( ! empty( $module_option ) && ( is_array( $module_option ) || $module_option instanceof Traversable ) ) {
			foreach ( $module_option as $option ) {

				$module_name = is_array( $option ) ? ( $option['module_name'] ?? '' ) : ( $option->module_name ?? '' );

				$show = is_array( $option ) ? ( $option['show'] ?? false ) : ( $option->show ?? false );

				switch ( $module_name ) {
					case 'image-gallery':
						$image_gallery = (bool) $show;
						break;
					case 'featured-video':
						$feature_video = (bool) $show;
						break;
				}
			}
		}

		if ( $image_gallery ) {
			add_action( 'add_meta_boxes', array( $this, 'sp_register_video_metabox' ) );
			add_action(
				'admin_enqueue_scripts',
				function ( $hook ) {
					if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ) ) ) {
						return;
					}
					wp_enqueue_script( 'jquery-ui-sortable' );
				}
			);
		}
		if ( $feature_video ) {
			add_action( 'save_post', array( $this, 'sp_save_video_meta' ) );
		}
	}

	/**
	 * Register meta boxes
	 */
	public function sp_register_video_metabox() {
		add_meta_box(
			'sp_post_video_box',
			'Featured Video',
			array( $this, 'sp_post_video_box_callback' ),
			'post',
			'side',
			'default'
		);

		add_meta_box(
			'sp_post_gallery_box',
			'Image Gallery',
			array( $this, 'sp_post_gallery_box_callback' ),
			'post',
			'side',
			'default'
		);
	}

	/**
	 * Video meta box HTML.
	 */
	public function sp_post_video_box_callback( $post ) {
		wp_nonce_field( 'sp_save_video_and_gallery_meta', 'sp_video_and_gallery_nonce' );

		$video_meta_data = get_post_meta( $post->ID, '_sp_video_meta', true );
		$video_url       = $video_meta_data['url'] ?? '';
		$video_caption   = $video_meta_data['caption'] ?? '';

		?>
		<div class="sp-smart-video-metabox">
			<span>Upload Video</span>
			<div class="sp-smart-video-metabox-input">
				<input type="text" id="sp_video_url" name="sp_video_url" value="<?php echo esc_attr( $video_url ); ?>" />
				<button type="button" class="sp-smart-upload-video-btn">
					<!-- SVG icon -->
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
						<path d="M12 3.63779C8.44131 3.63779 5.70181 6.46654 5.3856 9.9449C2.74317 10.2533 0.599976 12.3137 0.599976 15.0378C0.599976 17.9719 2.99029 20.3622 5.92443 20.3622H18.0815C21.0156 20.3622 23.4 17.9719 23.4 15.0378C23.4 12.314 21.2623 10.2537 18.6203 9.9449C18.3041 6.46654 15.5586 3.63779 12 3.63779ZM11.9911 8.19927C12.1974 8.19524 12.3943 8.27869 12.5388 8.4249L15.5803 11.4649C16.4117 12.1771 15.2207 13.368 14.5086 12.5366L12.7629 10.788V16.0793C12.7629 17.0928 11.2429 17.0928 11.2429 16.0793V10.7925L9.4988 12.5366C8.78662 13.368 7.59569 12.1771 8.42708 11.4649L11.4671 8.4249C11.6057 8.2853 11.7937 8.20214 11.9911 8.19927Z" fill="currentColor"/>
					</svg>
				</button>
			</div>
			<i class="sp-smart-video-metabox-note"><b>Note:</b> Enter Youtube/ Vimeo/ Self Hosted URL</i>
			<span>Video Caption</span>
			<div class="sp-smart-video-metabox-input">
				<input type="text" id="sp_video_caption" name="sp_video_caption" value="<?php echo esc_attr( $video_caption ); ?>" />
			</div>
		</div>
		<?php
	}

	/**
	 * Gallery meta box HTML
	 */
	public function sp_post_gallery_box_callback( $post ) {
		$gallery_ids = get_post_meta( $post->ID, '_sp_gallery_ids', true );
		$gallery_ids = is_array( $gallery_ids ) ? $gallery_ids : array();

		?>
		<style>
			.sp-gallery-preview { display: flex; flex-wrap: wrap; gap: 10px; }
			.sp-gallery-preview-images { cursor: move; position: relative; border: 1px solid #ddd; padding: 5px; background: #fff; }
			.sp-gallery-sortable-placeholder { border: 2px dashed #ccc; width: 66px; height: 70px; background: #fafafa; }
		</style>
		<div class="sp-gallery-metabox">
			<div class="sp-gallery-preview">
				<?php
				foreach ( $gallery_ids as $id ) :
					$thumb = wp_get_attachment_image_src( $id, 'thumbnail' );
					if ( $thumb ) :
						?>
						<div class="sp-gallery-preview-images">
							<img src="<?php echo esc_url( $thumb[0] ); ?>" data-image_id="<?php echo esc_attr( $id ); ?>" />
							<span class="sp-gallery-remove-img" data-image_id="<?php echo esc_attr( $id ); ?>">×</span>
						</div>
						<?php
					endif;
				endforeach;
				?>
			</div>

			<input type="hidden" id="sp_gallery_ids" name="sp_gallery_ids" value="<?php echo esc_attr( implode( ',', $gallery_ids ) ); ?>" />

			<button type="button" class="sp-upload-gallery">
				<?php esc_html_e( 'Add post gallery images', 'smart-post-show-pro' ); ?>
			</button>
		</div>
		<?php
	}

	/**
	 * Save meta data securely
	 */
	public function sp_save_video_meta( $post_id ) {
		// Verify nonce.
		if ( ! isset( $_POST['sp_video_and_gallery_nonce'] ) || ! wp_verify_nonce( $_POST['sp_video_and_gallery_nonce'], 'sp_save_video_and_gallery_meta' ) ) {
			return;
		}

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

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

		$sp_video_url     = isset( $_POST['sp_video_url'] ) ? trim( $_POST['sp_video_url'] ) : '';
		$sp_video_caption = isset( $_POST['sp_video_caption'] ) ? trim( $_POST['sp_video_caption'] ) : '';
		$sp_gallery_ids   = isset( $_POST['sp_gallery_ids'] ) ? trim( $_POST['sp_gallery_ids'] ) : '';

		// Save Video Meta.
		if ( $sp_video_url !== '' ) {
			update_post_meta(
				$post_id,
				'_sp_video_meta',
				array(
					'url'     => esc_url_raw( $sp_video_url ),
					'caption' => sanitize_text_field( $sp_video_caption ),
				)
			);
		} else {
			delete_post_meta( $post_id, '_sp_video_meta' );
		}

		// Save Gallery Meta.
		if ( $sp_gallery_ids !== '' ) {
			$ids = array_filter( array_map( 'absint', explode( ',', $sp_gallery_ids ) ) );
			if ( ! empty( $ids ) ) {
				update_post_meta( $post_id, '_sp_gallery_ids', $ids );
			} else {
				delete_post_meta( $post_id, '_sp_gallery_ids' );
			}
		} else {
			delete_post_meta( $post_id, '_sp_gallery_ids' );
		}
	}
}
