<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Register meta boxes for the 'stpo_story' custom post type.
 *
 * Uses the same _stpo_* meta key convention as the frontend user story uploader
 * so the player can read stories uniformly regardless of context.
 *
 * @since      1.0.0
 * @package    Storyposts
 * @subpackage Storyposts/includes/meta
 */
class Storyposts_Story_Meta {

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 */
	public function __construct() {
		add_action( 'init', array( $this, 'register_meta_fields' ) );
		add_action( 'storyposts_cmb2_admin_init', array( $this, 'register_metaboxes' ) );
		add_action( 'save_post_stpo_story', array( $this, 'handle_media_on_save' ), 10, 3 );
		
		// AJAX handler for admin poster upload
		add_action( 'wp_ajax_storyposts_upload_admin_poster', array( $this, 'handle_admin_poster_upload' ) );
	}

	/**
	 * Register meta fields for REST API.
	 *
	 * @since    1.0.0
	 */
	public function register_meta_fields() {
		$fields = [
			'_stpo_type',
			'_stpo_image_id',
			'_stpo_video_id',
			'_stpo_poster_id',
			'_stpo_color',
			'_stpo_caption',
			'_stpo_link',
			'_stpo_privacy',
			'_stpo_expire_at',
			'_story_context',
		];

		foreach ( $fields as $field ) {
			register_post_meta( 'stpo_story', $field, [
				'show_in_rest'  => true,
				'type'          => 'string',
				'single'        => true,
				'auth_callback' => function() {
					return current_user_can( 'edit_posts' );
				}
			] );
		}
	}

	/**
	 * Register the meta boxes using CMB2.
	 *
	 * @since    1.0.0
	 */
	public function register_metaboxes() {

		$prefix = '_stpo_';

		/**
		 * Story Details Metabox
		 */
		$cmb = new_storyposts_cmb2_box( array(
			'id'            => $prefix . 'story_details_metabox',
			'title'         => esc_html__( 'Story Details', 'storyposts' ),
			'object_types'  => array( 'stpo_story' ),
			'context'       => 'normal',
			'priority'      => 'high',
			'show_names'    => true,
		) );

		$context_options = array(
			'collection' => esc_html__( 'Collection (Admin)', 'storyposts' ),
		);

		if ( storyposts_component_exists( 'user-stories' ) ) {
			$context_options['user'] = esc_html__( 'User Story', 'storyposts' );
		}

		// Story Context (admin, user, auto)
		$cmb->add_field( array(
			'name'    => esc_html__( 'Story Context', 'storyposts' ),
			'desc'    => esc_html__( 'Where this story belongs. "Collection" stories are for admin-created collections.', 'storyposts' ),
			'id'      => '_story_context',
			'type'    => 'select',
			'default' => 'collection',
			'options' => $context_options,
		) );

		// Story Type
		$cmb->add_field( array(
			'name'    => esc_html__( 'Story Type', 'storyposts' ),
			'desc'    => esc_html__( 'Select the type of story content.', 'storyposts' ),
			'id'      => $prefix . 'type',
			'type'    => 'select',
			'default' => 'image',
			'options' => array(
				'text'  => esc_html__( 'Text', 'storyposts' ),
				'image' => esc_html__( 'Image', 'storyposts' ),
				'video' => esc_html__( 'Video', 'storyposts' ),
			),
		) );

		// Story Description/Caption
		$max_desc_length = Storyposts_Settings::get( 'max_desc_length', 120 );
		$cmb->add_field( array(
			'name'       => esc_html__( 'Description', 'storyposts' ),
			/* translators: %d: Maximum description length */
			'desc'       => sprintf( esc_html__( 'Story description/caption. Max %d characters.', 'storyposts' ), $max_desc_length ),
			'id'         => $prefix . 'caption',
			'type'       => 'textarea_small',
			'attributes' => array(
				'maxlength' => $max_desc_length,
				'rows'      => 3,
			),
		) );

		// =====================================================================
		// CONDITIONAL FIELDS BASED ON STORY TYPE
		// =====================================================================

		// Story Background Color - ONLY for Text stories
		$cmb->add_field( array(
			'name'       => esc_html__( 'Background Color', 'storyposts' ),
			'desc'       => esc_html__( 'Background color for text-only stories.', 'storyposts' ),
			'id'         => $prefix . 'color',
			'type'       => 'colorpicker',
			'default'    => '#93278f',
			'attributes' => array(
				'data-conditional-id'    => $prefix . 'type',
				'data-conditional-value' => 'text',
			),
		) );

		// Story Media (Image) - ONLY for Image stories
		$cmb->add_field( array(
			'name'         => esc_html__( 'Story Image', 'storyposts' ),
			'desc'         => esc_html__( 'Upload or select an image for this story.', 'storyposts' ),
			'id'           => $prefix . 'image_id',
			'type'         => 'file',
			'options'      => array(
				'url' => false,
			),
			'text'         => array(
				'add_upload_file_text' => esc_html__( 'Add Image', 'storyposts' ),
			),
			'query_args'   => array(
				'type' => 'image',
			),
			'preview_size' => 'medium',
			'attributes'   => array(
				'data-conditional-id'    => $prefix . 'type',
				'data-conditional-value' => 'image',
			),
		) );

		// Story Video - ONLY for Video stories
		$cmb->add_field( array(
			'name'       => esc_html__( 'Story Video', 'storyposts' ),
			'desc'       => esc_html__( 'Upload or select a video for this story. Supported formats: MP4, MOV.', 'storyposts' ),
			'id'         => $prefix . 'video_id',
			'type'       => 'file',
			'options'    => array(
				'url' => false,
			),
			'text'       => array(
				'add_upload_file_text' => esc_html__( 'Add Video', 'storyposts' ),
			),
			'query_args' => array(
				'type' => 'video',
			),
			'attributes' => array(
				'data-conditional-id'    => $prefix . 'type',
				'data-conditional-value' => 'video',
			),
		) );

		// Video Poster Image - ONLY for Video stories
		$cmb->add_field( array(
			'name'         => esc_html__( 'Video Poster Image', 'storyposts' ),
			'desc'         => esc_html__( 'Thumbnail image shown before video plays.', 'storyposts' ),
			'id'           => $prefix . 'poster_id',
			'type'         => 'file',
			'options'      => array(
				'url' => false,
			),
			'text'         => array(
				'add_upload_file_text' => esc_html__( 'Add Poster', 'storyposts' ),
			),
			'query_args'   => array(
				'type' => 'image',
			),
			'preview_size' => 'thumbnail',
			'attributes'   => array(
				'data-conditional-id'    => $prefix . 'type',
				'data-conditional-value' => 'video',
			),
		) );

		// =====================================================================
		// COMMON FIELDS
		// =====================================================================

		// Story Link (optional CTA)
		$cmb->add_field( array(
			'name' => esc_html__( 'Link URL', 'storyposts' ),
			'desc' => esc_html__( 'Optional link for "See More" or CTA button.', 'storyposts' ),
			'id'   => $prefix . 'link',
			'type' => 'text_url',
		) );

	}

	/**
	 * Handle media field processing on save.
	 *
	 * @since    1.0.0
	 * @param    int     $post_id Post ID.
	 * @param    WP_Post $post    Post object.
	 * @param    bool    $update  Whether this is an existing post being updated.
	 */
	public function handle_media_on_save( $post_id, $post, $update ) {
		// Don't run on autosave
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

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

		$story_type = get_post_meta( $post_id, '_stpo_type', true );

		// Clean up unused meta based on story type
		if ( $story_type === 'text' ) {
			delete_post_meta( $post_id, '_stpo_image_id' );
			delete_post_meta( $post_id, '_stpo_video_id' );
			// Keep _stpo_poster_id for text stories (generated poster)
		} elseif ( $story_type === 'image' ) {
			delete_post_meta( $post_id, '_stpo_video_id' );
			delete_post_meta( $post_id, '_stpo_poster_id' );
			delete_post_meta( $post_id, '_stpo_color' );
		} elseif ( $story_type === 'video' ) {
			delete_post_meta( $post_id, '_stpo_image_id' );
			delete_post_meta( $post_id, '_stpo_color' );
		}
	}

	/**
	 * Handle AJAX upload of generated poster images.
	 *
	 * Receives a blob from JavaScript, saves to media library,
	 * and returns the attachment ID.
	 *
	 * @since    1.0.0
	 */
	public function handle_admin_poster_upload() {
		// Verify nonce
		if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'storyposts_admin_poster_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed.' ) );
		}

		// Check user permissions
		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error( array( 'message' => 'Permission denied.' ) );
		}

		// Check for uploaded file
		if ( empty( $_FILES['poster'] ) ) {
			wp_send_json_error( array( 'message' => 'No file uploaded.' ) );
		}

		$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;

		// Require WordPress file handling functions
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/image.php';
		require_once ABSPATH . 'wp-admin/includes/media.php';

		// Use media_handle_upload to process the file
		$attachment_id = media_handle_upload( 'poster', $post_id );

		if ( is_wp_error( $attachment_id ) ) {
			wp_send_json_error( array( 'message' => $attachment_id->get_error_message() ) );
		}

		// Update the post meta with the new poster ID
		if ( $post_id ) {
			update_post_meta( $post_id, '_stpo_poster_id', $attachment_id );
		}

		wp_send_json_success( array(
			'attachment_id' => $attachment_id,
			'url'           => wp_get_attachment_url( $attachment_id ),
			'message'       => 'Poster uploaded successfully.',
		) );
	}

}
