<?php
/**
 * Code Snippet List Table
 *
 * Standard WordPress list table for code snippets (like Posts/Pages).
 *
 * @package CodeSnippet
 * @since 1.0.0
 */

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

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

/**
 * Class Code_Snippet_List_Table
 */
class Code_Snippet_List_Table extends WP_List_Table {

	/**
	 * Module instance.
	 *
	 * @var \CodeSnippet\Module
	 */
	private $module;

	/**
	 * Status filter: all, active, inactive.
	 *
	 * @var string
	 */
	private $status_filter;

	/**
	 * Search query.
	 *
	 * @var string
	 */
	private $search_query;

	/**
	 * Constructor.
	 *
	 * @param \CodeSnippet\Module $module Module instance.
	 * @param string              $status Status filter (all, active, inactive).
	 * @param string              $search Search query.
	 */
	public function __construct( $module, $status = 'all', $search = '' ) {
		$this->module        = $module;
		$this->status_filter = $status;
		$this->search_query  = $search;
		parent::__construct(
			[
				'singular' => 'snippet',
				'plural'   => 'snippets',
				'ajax'     => false,
			]
		);
	}

	/**
	 * Get table columns.
	 *
	 * @return array
	 */
	public function get_columns() {
		return [
			'cb'       => '<input type="checkbox" />',
			'title'    => __( 'Title', 'wp-powersuite' ),
			'author'   => __( 'Author', 'wp-powersuite' ),
			'id'       => __( 'ID', 'wp-powersuite' ),
			'type'     => __( 'Type', 'wp-powersuite' ),
			'location' => __( 'Location', 'wp-powersuite' ),
			'priority' => __( 'Priority', 'wp-powersuite' ),
			'created'  => __( 'Created', 'wp-powersuite' ),
			'status'   => __( 'Status', 'wp-powersuite' ),
		];
	}

	/**
	 * Get sortable columns.
	 *
	 * @return array
	 */
	protected function get_sortable_columns() {
		return [
			'title'    => [ 'title', false ],
			'author'   => [ 'author', false ],
			'id'       => [ 'ID', false ],
			'priority' => [ 'priority', false ],
			'created'  => [ 'date', false ],
		];
	}

	/**
	 * Get bulk actions.
	 *
	 * @return array
	 */
	protected function get_bulk_actions() {
		return [
			'activate'   => __( 'Activate', 'wp-powersuite' ),
			'deactivate' => __( 'Deactivate', 'wp-powersuite' ),
			'delete'     => __( 'Delete', 'wp-powersuite' ),
		];
	}

	/**
	 * Prepare items for display.
	 */
	public function prepare_items() {
		$args = [
			'orderby' => 'modified',
			'order'   => 'DESC',
		];
		if ( isset( $_REQUEST['orderby'] ) ) {
			$ob = sanitize_key( wp_unslash( $_REQUEST['orderby'] ) );
			if ( in_array( $ob, [ 'title', 'ID', 'author', 'date', 'modified', 'priority' ], true ) ) {
				$args['orderby'] = $ob;
			}
		}
		if ( isset( $_REQUEST['order'] ) && strtolower( wp_unslash( $_REQUEST['order'] ) ) === 'asc' ) {
			$args['order'] = 'ASC';
		}
		if ( $this->status_filter === 'active' ) {
			$args['post_status'] = 'publish';
		} elseif ( $this->status_filter === 'inactive' ) {
			$args['post_status'] = 'draft';
		} else {
			$args['post_status'] = 'any';
		}
		if ( $this->search_query !== '' ) {
			$args['s'] = $this->search_query;
		}
		$this->items = $this->module->getAllSnippets( $args );
		$this->_column_headers = [
			$this->get_columns(),
			[],
			$this->get_sortable_columns(),
			'title',
		];
	}

	/**
	 * Default column output.
	 *
	 * @param \WP_Post $item        Snippet post.
	 * @param string   $column_name Column name.
	 * @return string
	 */
	protected function column_default( $item, $column_name ) {
		return '';
	}

	/**
	 * Checkbox column.
	 *
	 * @param \WP_Post $item Snippet post.
	 * @return string
	 */
	protected function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="snippet[]" value="%d" />',
			(int) $item->ID
		);
	}

	/**
	 * Title column with row actions.
	 *
	 * @param \WP_Post $item Snippet post.
	 * @return string
	 */
	protected function column_title( $item ) {
		$edit_url = admin_url( 'admin.php?page=powersuite-code-snippet&action=edit&id=' . $item->ID );
		$title    = $item->post_title ?: __( '(no title)', 'wp-powersuite' );
		$actions  = [
			'edit' => sprintf(
				'<a href="%s">%s</a>',
				esc_url( $edit_url ),
				__( 'Edit', 'wp-powersuite' )
			),
		];
		$active = $item->post_status === 'publish';
		if ( $active ) {
			$actions['deactivate'] = sprintf(
				'<a href="%s" class="submitdelete">%s</a>',
				esc_url( wp_nonce_url( admin_url( 'admin.php?page=powersuite-code-snippet&action=deactivate&id=' . $item->ID ), 'deactivate-snippet_' . $item->ID ) ),
				__( 'Deactivate', 'wp-powersuite' )
			);
		} else {
			$actions['activate'] = sprintf(
				'<a href="%s">%s</a>',
				esc_url( wp_nonce_url( admin_url( 'admin.php?page=powersuite-code-snippet&action=activate&id=' . $item->ID ), 'activate-snippet_' . $item->ID ) ),
				__( 'Activate', 'wp-powersuite' )
			);
		}
		$actions['delete'] = sprintf(
			'<a href="#" class="submitdelete wpps-cs-delete-link" data-id="%d">%s</a>',
			(int) $item->ID,
			__( 'Delete', 'wp-powersuite' )
		);
		$row_actions = $this->row_actions( $actions );
		return '<strong><a href="' . esc_url( $edit_url ) . '" class="row-title">' . esc_html( $title ) . '</a></strong>' . $row_actions;
	}

	/**
	 * Author column.
	 *
	 * @param \WP_Post $item Snippet post.
	 * @return string
	 */
	protected function column_author( $item ) {
		$author = get_userdata( $item->post_author );
		return $author ? esc_html( $author->display_name ?: $author->user_login ) : '—';
	}

	/**
	 * ID column.
	 *
	 * @param \WP_Post $item Snippet post.
	 * @return string
	 */
	protected function column_id( $item ) {
		$shortcode = sprintf( '[wpps_code id="%d"]', $item->ID );
		return '<code title="' . esc_attr( $shortcode ) . '">' . (int) $item->ID . '</code>';
	}

	/**
	 * Type column with colored badges.
	 *
	 * @param \WP_Post $item Snippet post.
	 * @return string
	 */
	protected function column_type( $item ) {
		$types = [
			'html' => __( 'HTML', 'wp-powersuite' ),
			'css'  => __( 'CSS', 'wp-powersuite' ),
			'js'   => __( 'JavaScript', 'wp-powersuite' ),
			'php'  => __( 'PHP', 'wp-powersuite' ),
		];
		$type = get_post_meta( $item->ID, '_wpps_code_type', true ) ?: 'html';
		$label = $types[ $type ] ?? $type;
		return '<span class="wpps-cs-type-badge wpps-cs-type-' . esc_attr( $type ) . '">' . esc_html( $label ) . '</span>';
	}

	/**
	 * Location column.
	 *
	 * @param \WP_Post $item Snippet post.
	 * @return string
	 */
	protected function column_location( $item ) {
		$loc = get_post_meta( $item->ID, '_wpps_location', true ) ?: 'footer';
		$locations = \CodeSnippet\Module::getLocations();
		$label = $loc === 'shortcode' ? __( 'Shortcode', 'wp-powersuite' ) : ( $locations[ $loc ] ?? $loc );
		return esc_html( $label );
	}

	/**
	 * Priority column.
	 *
	 * @param \WP_Post $item Snippet post.
	 * @return string
	 */
	protected function column_priority( $item ) {
		$prio = (int) ( get_post_meta( $item->ID, '_wpps_priority', true ) ?: 10 );
		return (string) $prio;
	}

	/**
	 * Created column.
	 *
	 * @param \WP_Post $item Snippet post.
	 * @return string
	 */
	protected function column_created( $item ) {
		return esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $item->post_date ) ) );
	}

	/**
	 * Status column with toggle.
	 *
	 * @param \WP_Post $item Snippet post.
	 * @return string
	 */
	protected function column_status( $item ) {
		$active = $item->post_status === 'publish';
		$id     = (int) $item->ID;
		$label  = $active ? __( 'Active', 'wp-powersuite' ) : __( 'Inactive', 'wp-powersuite' );
		return sprintf(
			'<label class="wpps-cs-status-toggle" title="%s">
				<input type="checkbox" class="wpps-cs-status-switch" data-id="%d" %s>
				<span class="wpps-cs-status-slider"></span>
				<span class="wpps-cs-status-label">%s</span>
			</label>',
			esc_attr( $active ? __( 'Deactivate', 'wp-powersuite' ) : __( 'Activate', 'wp-powersuite' ) ),
			$id,
			$active ? 'checked' : '',
			esc_html( $label )
		);
	}

	/**
	 * Message when no items.
	 */
	public function no_items() {
		esc_html_e( 'No code snippets found.', 'wp-powersuite' );
	}

	/**
	 * Get views for the list table (All, Active, Inactive).
	 *
	 * @return array
	 */
	protected function get_views() {
		$base_url = admin_url( 'admin.php?page=powersuite-code-snippet' );
		$search   = $this->search_query !== '' ? '&s=' . rawurlencode( $this->search_query ) : '';
		$counts   = $this->module->getSnippetCounts();
		$count_all = $counts['all'];
		$count_active = $counts['active'];
		$count_inactive = $counts['inactive'];
		$views = [
			'all' => sprintf(
				'<a href="%s" class="%s">%s <span class="count">(%d)</span></a>',
				esc_url( add_query_arg( 'status', 'all', $base_url ) . $search ),
				$this->status_filter === 'all' ? 'current' : '',
				__( 'All', 'wp-powersuite' ),
				$count_all
			),
			'active' => sprintf(
				'<a href="%s" class="%s">%s <span class="count">(%d)</span></a>',
				esc_url( add_query_arg( 'status', 'active', $base_url ) . $search ),
				$this->status_filter === 'active' ? 'current' : '',
				__( 'Active', 'wp-powersuite' ),
				$count_active
			),
			'inactive' => sprintf(
				'<a href="%s" class="%s">%s <span class="count">(%d)</span></a>',
				esc_url( add_query_arg( 'status', 'inactive', $base_url ) . $search ),
				$this->status_filter === 'inactive' ? 'current' : '',
				__( 'Inactive', 'wp-powersuite' ),
				$count_inactive
			),
		];
		return $views;
	}
}
