<?php
/**
 * Training Videos List Table
 *
 * Displays training videos in admin using WP_List_Table
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/admin
 * @since      1.0.27
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Load WP_List_Table if not loaded.
if ( ! class_exists( 'WP_List_Table' ) ) {
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

/**
 * Class MACM_Videos_List_Table
 *
 * Extends WP_List_Table to display training videos
 *
 * @since 1.0.27
 */
class MACM_Videos_List_Table extends WP_List_Table {

	/**
	 * Constructor
	 *
	 * @since 1.0.27
	 */
	public function __construct() {
		parent::__construct(
			array(
				'singular' => 'video',
				'plural'   => 'videos',
				'ajax'     => false,
			)
		);
	}

	/**
	 * Get table columns
	 *
	 * @since 1.0.27
	 * @return array Column names and labels.
	 */
	public function get_columns() {
		return array(
			'cb'            => '<input type="checkbox" />',
			'thumbnail'     => __( 'Thumbnail', 'martial-arts-club-manager' ),
			'title'         => __( 'Title', 'martial-arts-club-manager' ),
			'belt_level'    => __( 'Belt Level', 'martial-arts-club-manager' ),
			'category'      => __( 'Category', 'martial-arts-club-manager' ),
			'difficulty'    => __( 'Difficulty', 'martial-arts-club-manager' ),
			'instructor'    => __( 'Instructor', 'martial-arts-club-manager' ),
			'video_type'    => __( 'Type', 'martial-arts-club-manager' ),
			'duration'      => __( 'Duration', 'martial-arts-club-manager' ),
			'display_order' => __( 'Order', 'martial-arts-club-manager' ),
			'status'        => __( 'Status', 'martial-arts-club-manager' ),
			'created_at'    => __( 'Date', 'martial-arts-club-manager' ),
		);
	}

	/**
	 * Get sortable columns
	 *
	 * @since 1.0.27
	 * @return array Sortable column names.
	 */
	public function get_sortable_columns() {
		return array(
			'title'         => array( 'title', false ),
			'belt_level'    => array( 'belt_level', false ),
			'category'      => array( 'category', false ),
			'difficulty'    => array( 'difficulty', false ),
			'instructor'    => array( 'instructor', false ),
			'video_type'    => array( 'video_type', false ),
			'display_order' => array( 'display_order', true ),
			'status'        => array( 'status', false ),
			'created_at'    => array( 'created_at', true ),
		);
	}

	/**
	 * Get bulk actions
	 *
	 * @since 1.0.27
	 * @return array Bulk actions.
	 */
	public function get_bulk_actions() {
		return array(
			'delete'  => __( 'Delete', 'martial-arts-club-manager' ),
			'publish' => __( 'Publish', 'martial-arts-club-manager' ),
			'draft'   => __( 'Draft', 'martial-arts-club-manager' ),
		);
	}

	/**
	 * Prepare items for display
	 *
	 * @since 1.0.27
	 */
	public function prepare_items() {
		$per_page     = 20;
		$current_page = $this->get_pagenum();

		$columns  = $this->get_columns();
		$hidden   = array();
		$sortable = $this->get_sortable_columns();

		$this->_column_headers = array( $columns, $hidden, $sortable );

		// Handle bulk actions.
		$this->process_bulk_action();

		// Get videos - read-only sorting parameters with strict allowlist validation.
		// Uses filter_input for secure parameter access (standard WordPress pattern for WP_List_Table).
		$allowed_orderby = array( 'title', 'belt_level', 'category', 'difficulty', 'instructor', 'video_type', 'display_order', 'status', 'created_at', 'instructor_id' );
		$orderby         = 'display_order';
		$orderby_input   = filter_input( INPUT_GET, 'orderby', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( ! empty( $orderby_input ) ) {
			$orderby_sanitized = sanitize_key( $orderby_input );
			if ( in_array( $orderby_sanitized, $allowed_orderby, true ) ) {
				$orderby = $orderby_sanitized;
			}
		}

		$order       = 'ASC';
		$order_input = filter_input( INPUT_GET, 'order', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( ! empty( $order_input ) ) {
			$order_sanitized = sanitize_key( $order_input );
			if ( in_array( strtolower( $order_sanitized ), array( 'asc', 'desc' ), true ) ) {
				$order = strtoupper( $order_sanitized );
			}
		}

		// Map 'instructor' column to 'instructor_id' for sorting.
		if ( 'instructor' === $orderby ) {
			$orderby = 'instructor_id';
		}

		$args = array(
			'status'  => '', // Get all statuses in admin.
			'orderby' => $orderby,
			'order'   => $order,
		);

		$videos      = MACM_Video::get_all( $args );
		$total_items = count( $videos );

		// Pagination.
		$this->items = array_slice( $videos, ( ( $current_page - 1 ) * $per_page ), $per_page );

		$this->set_pagination_args(
			array(
				'total_items' => $total_items,
				'per_page'    => $per_page,
				'total_pages' => ceil( $total_items / $per_page ),
			)
		);
	}

	/**
	 * Column: Checkbox
	 *
	 * @since 1.0.27
	 * @param object $item Video item.
	 * @return string Checkbox HTML.
	 */
	public function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="video_ids[]" value="%s" />',
			esc_attr( $item->id )
		);
	}

	/**
	 * Column: Thumbnail
	 *
	 * @since 1.0.27
	 * @param object $item Video item.
	 * @return string Thumbnail HTML.
	 */
	public function column_thumbnail( $item ) {
		$thumbnail_url = MACM_Video::get_thumbnail_url( $item, 'thumbnail' );

		if ( $thumbnail_url ) {
			return sprintf(
				'<img src="%s" alt="%s" style="width: 60px; height: auto; border-radius: 4px;" />',
				esc_url( $thumbnail_url ),
				esc_attr( $item->title )
			);
		}

		return '<span class="dashicons dashicons-video-alt3" style="font-size: 40px; color: #D1D5DB;"></span>';
	}

	/**
	 * Column: Title
	 *
	 * @since 1.0.27
	 * @param object $item Video item.
	 * @return string Title HTML with row actions.
	 */
	public function column_title( $item ) {
		$edit_url = add_query_arg(
			array(
				'page'   => 'kcm-training-videos',
				'action' => 'edit',
				'id'     => $item->id,
			),
			admin_url( 'admin.php' )
		);

		$delete_url = wp_nonce_url(
			add_query_arg(
				array(
					'page'   => 'kcm-training-videos',
					'action' => 'delete',
					'id'     => $item->id,
				),
				admin_url( 'admin.php' )
			),
			'macm_delete_video_' . $item->id
		);

		$confirm_message = esc_js( __( 'Are you sure you want to delete this video? This action cannot be undone.', 'martial-arts-club-manager' ) );

		$actions = array(
			'edit'   => sprintf(
				'<a href="%s">%s</a>',
				esc_url( $edit_url ),
				esc_html__( 'Edit', 'martial-arts-club-manager' )
			),
			'delete' => sprintf(
				'<a href="%s" class="submitdelete" onclick="return confirm(&quot;%s&quot;);" style="color: #b32d2e;">%s</a>',
				esc_url( $delete_url ),
				$confirm_message,
				esc_html__( 'Delete', 'martial-arts-club-manager' )
			),
		);

		return sprintf(
			'<strong><a href="%s">%s</a></strong>%s',
			esc_url( $edit_url ),
			esc_html( $item->title ),
			$this->row_actions( $actions )
		);
	}

	/**
	 * Column: Video Type
	 *
	 * @since 1.0.27
	 * @param object $item Video item.
	 * @return string Video type label.
	 */
	public function column_video_type( $item ) {
		$types = array(
			'youtube' => __( 'YouTube', 'martial-arts-club-manager' ),
			'vimeo'   => __( 'Vimeo', 'martial-arts-club-manager' ),
			'direct'  => __( 'Direct URL', 'martial-arts-club-manager' ),
			'embed'   => __( 'Custom Embed', 'martial-arts-club-manager' ),
		);

		return isset( $types[ $item->video_type ] ) ? $types[ $item->video_type ] : esc_html( $item->video_type );
	}

	/**
	 * Column: Duration
	 *
	 * @since 1.0.27
	 * @param object $item Video item.
	 * @return string Duration.
	 */
	public function column_duration( $item ) {
		return $item->duration ? esc_html( $item->duration ) : '—';
	}

	/**
	 * Column: Belt Level
	 *
	 * @since 1.0.89
	 * @param object $item Video item.
	 * @return string Belt level.
	 */
	public function column_belt_level( $item ) {
		return ! empty( $item->belt_level ) ? esc_html( $item->belt_level ) : '—';
	}

	/**
	 * Column: Category
	 *
	 * @since 1.0.89
	 * @param object $item Video item.
	 * @return string Category.
	 */
	public function column_category( $item ) {
		return ! empty( $item->category ) ? esc_html( $item->category ) : '—';
	}

	/**
	 * Column: Difficulty
	 *
	 * @since 1.0.89
	 * @param object $item Video item.
	 * @return string Difficulty.
	 */
	public function column_difficulty( $item ) {
		return ! empty( $item->difficulty ) ? esc_html( $item->difficulty ) : '—';
	}

	/**
	 * Column: Instructor
	 *
	 * @since 1.0.89
	 * @param object $item Video item.
	 * @return string Instructor name.
	 */
	public function column_instructor( $item ) {
		if ( ! empty( $item->instructor_id ) ) {
			$instructor = MACM_Instructor::get( $item->instructor_id );
			return $instructor ? esc_html( $instructor->full_name ) : '—';
		}
		return '—';
	}

	/**
	 * Column: Display Order
	 *
	 * @since 1.0.27
	 * @param object $item Video item.
	 * @return string Display order.
	 */
	public function column_display_order( $item ) {
		return absint( $item->display_order );
	}

	/**
	 * Column: Status
	 *
	 * @since 1.0.27
	 * @param object $item Video item.
	 * @return string Status badge.
	 */
	public function column_status( $item ) {
		$status = $item->status;
		$class  = 'published' === $status ? 'kcm-status-published' : 'kcm-status-draft';
		$label  = 'published' === $status ? __( 'Published', 'martial-arts-club-manager' ) : __( 'Draft', 'martial-arts-club-manager' );

		return sprintf(
			'<span class="%s">%s</span>',
			esc_attr( $class ),
			esc_html( $label )
		);
	}

	/**
	 * Column: Date Created
	 *
	 * @since 1.0.27
	 * @param object $item Video item.
	 * @return string Formatted date.
	 */
	public function column_created_at( $item ) {
		return date_i18n( get_option( 'date_format' ), strtotime( $item->created_at ) );
	}

	/**
	 * Process bulk actions
	 *
	 * @since 1.0.27
	 */
	public function process_bulk_action() {
		// Check if action is set.
		if ( ! $this->current_action() ) {
			return;
		}

		// Verify nonce.
		$nonce = isset( $_POST['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'bulk-videos' ) ) {
			return;
		}

		// Check capability.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'martial-arts-club-manager' ) );
		}

		// Get selected video IDs.
		$video_ids = isset( $_POST['video_ids'] ) ? array_map( 'absint', wp_unslash( $_POST['video_ids'] ) ) : array();

		if ( empty( $video_ids ) ) {
			return;
		}

		$action = $this->current_action();

		switch ( $action ) {
			case 'delete':
				foreach ( $video_ids as $video_id ) {
					MACM_Video::delete( $video_id );
				}
				add_settings_error(
					'macm_videos',
					'videos_deleted',
					sprintf(
						/* translators: %d: number of videos */
						_n( '%d video deleted.', '%d videos deleted.', count( $video_ids ), 'martial-arts-club-manager' ),
						count( $video_ids )
					),
					'success'
				);
				break;

			case 'publish':
				foreach ( $video_ids as $video_id ) {
					MACM_Video::update( $video_id, array( 'status' => 'published' ) );
				}
				add_settings_error(
					'macm_videos',
					'videos_published',
					sprintf(
						/* translators: %d: number of videos */
						_n( '%d video published.', '%d videos published.', count( $video_ids ), 'martial-arts-club-manager' ),
						count( $video_ids )
					),
					'success'
				);
				break;

			case 'draft':
				foreach ( $video_ids as $video_id ) {
					MACM_Video::update( $video_id, array( 'status' => 'draft' ) );
				}
				add_settings_error(
					'macm_videos',
					'videos_drafted',
					sprintf(
						/* translators: %d: number of videos */
						_n( '%d video set to draft.', '%d videos set to draft.', count( $video_ids ), 'martial-arts-club-manager' ),
						count( $video_ids )
					),
					'success'
				);
				break;
		}
	}

	/**
	 * Message to display when no items found
	 *
	 * @since 1.0.27
	 */
	public function no_items() {
		esc_html_e( 'No videos found.', 'martial-arts-club-manager' );
	}
}
