<?php

namespace Quicker\Core\Admin;

defined( 'ABSPATH' ) || exit;

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

class Table extends \WP_List_Table {

	public $singular_name;
	public $plural_name;
	public $id      = '';
	public $columns = array();

	/**
	 * Show list
	 */
	function __construct( $all_data_of_table ) {

		$this->singular_name = $all_data_of_table['singular_name'];
		$this->plural_name   = $all_data_of_table['plural_name'];
		$this->columns       = $all_data_of_table['columns'];

		parent::__construct(
			array(
				'singular' => $this->singular_name,
				'plural'   => $this->plural_name,
				'ajax'     => true,
			)
		);
	}

	/**
	 * Get column header function
	 */
	public function get_columns() {
		return $this->columns;
	}


	/**
	 * Sortable column function
	 */
	public function get_sortable_columns() {
		$sortable = $this->columns;
		unset( $sortable['cb'] );
		unset( $sortable['drag_handle'] );

		return $sortable;
	}

	/**
	 * Render the drag handle column
	 */
	function column_drag_handle( $item ) {
		return '<span class="quicker-drag-handle dashicons dashicons-menu"></span>';
	}

	/**
	 * Display all row function
	 */
	protected function column_default( $item, $column_name ) {
		if ( isset( $item[ $column_name ] ) ) {
			return $item[ $column_name ];
		}
		return '';
	}

	/**
	 * Render the field_enabled column with colored tag
	 */
	function column_field_enabled( $item ) {
		return $this->render_yes_no_tag( $item['field_enabled'] ?? '' );
	}

	/**
	 * Render the field_required column with colored tag
	 */
	function column_field_required( $item ) {
		return $this->render_yes_no_tag( $item['field_required'] ?? '' );
	}

	/**
	 * Render a yes/no value as a colored tag
	 */
	private function render_yes_no_tag( $value ) {
		$normalized = strtolower( trim( $value ) );
		if ( 'yes' === $normalized ) {
			return '<span class="quicker-tag quicker-tag-yes">' . esc_html__( 'Yes', 'quicker' ) . '</span>';
		}
		return '<span class="quicker-tag quicker-tag-no">' . esc_html__( 'No', 'quicker' ) . '</span>';
	}

	/**
	 * Get Bulk options
	 */
	public function get_bulk_actions() {
		$actions          = array();
		$actions['trash'] = esc_html__( 'Move to Trash', 'quicker' );

		return $actions;
	}

	/**
	 * Render the bulk edit checkbox
	 *
	 * @param array $item
	 *
	 * @return string
	 */
	function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="bulk-delete[]" value="%1$s" />',
			$item['ID']
		);
	}

	/**
	 * Render the field_label column with row actions
	 *
	 * @param array $item
	 *
	 * @return string
	 */
	function column_field_label( $item ) {
		$is_default = in_array( $item['field_type'] ?? '', array( 'billing', 'shipping' ), true ) && empty( $item['field_position'] );

		$actions = array(
			'edit' => sprintf(
				'<a href="#" class="update_checkout"
				data-id="%s"
				data-field_position="%s"
				data-field_type="%s"
				data-input_type="%s"
				data-field_label="%s"
				data-field_name="%s"
				data-field_placeholder="%s"
				data-field_required="%s"
				data-field_enabled="%s"
				data-display_in_emails="%s"
				data-display_in_order_details="%s"
				data-field_user_roles="%s"
				data-field_options="%s"
				data-field_conditions="%s"
				data-field_condition_action="%s"
				data-field_condition_enabled="%s">%s</a>',
				esc_attr( $item['ID'] ),
				esc_attr( $item['field_position'] ),
				esc_attr( $item['field_type'] ),
				esc_attr( $item['input_type'] ),
				esc_attr( $item['field_label'] ),
				esc_attr( $item['field_name'] ),
				esc_attr( $item['field_placeholder'] ),
				esc_attr( $item['field_required'] ),
				esc_attr( $item['field_enabled'] ),
				esc_attr( $item['display_in_emails'] ?? 'yes' ),
				esc_attr( $item['display_in_order_details'] ?? 'yes' ),
				esc_attr( is_array( $item['field_user_roles'] ?? '' ) ? implode( ',', $item['field_user_roles'] ) : ( $item['field_user_roles'] ?? '' ) ),
				esc_attr( ! empty( $item['field_options'] ) && is_array( $item['field_options'] ) ? wp_json_encode( $item['field_options'] ) : '' ),
				esc_attr( ! empty( $item['field_conditions'] ) && is_array( $item['field_conditions'] ) ? wp_json_encode( $item['field_conditions'] ) : '' ),
				esc_attr( $item['field_condition_action'] ?? 'show' ),
				esc_attr( $item['field_condition_enabled'] ?? '' ),
				esc_html__( 'Edit', 'quicker' )
			),
		);

		if ( ! $is_default ) {
			$actions['delete'] = sprintf(
				'<a href="#" class="delete_checkout_field" data-id="%s">%s</a>',
				esc_attr( $item['ID'] ),
				esc_html__( 'Delete', 'quicker' )
			);
		}

		return sprintf(
			'<strong>%1$s</strong>%2$s',
			esc_html( $item['field_label'] ),
			$this->row_actions( $actions )
		);
	}

	/**
	 * Override single_row to add data-id attribute for sortable.
	 */
	public function single_row( $item ) {
		echo '<tr data-id="' . esc_attr( $item['ID'] ) . '">';
		$this->single_row_columns( $item );
		echo '</tr>';
	}

	/**
	 * Delete data
	 */
	public function process_bulk_action() {
		$action = $this->current_action();
		if ( 'trash' === $action ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in parent class
			$delete_ids = isset( $_POST['bulk-delete'] ) ? array_map( 'absint', (array) $_POST['bulk-delete'] ) : array();
			foreach ( $delete_ids as $did ) {
				wp_delete_post( $did, true );
			}
			wp_safe_redirect( esc_url( add_query_arg() ) );

			exit;
		}
	}

	/**
	 * Main query and show function
	 */
	public function preparing_items() {
		$per_page              = 20;
		$column                = $this->get_columns();
		$hidden                = array();
		$sortable              = $this->get_sortable_columns();
		$this->_column_headers = array( $column, $hidden, $sortable );
		$current_page          = $this->get_pagenum();
		$offset                = ( $current_page - 1 ) * $per_page;
		$this->process_bulk_action();

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Sorting parameters in WP_List_Table
		if ( isset( $_REQUEST['orderby'] ) && isset( $_REQUEST['order'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Sorting parameters in WP_List_Table
			$args['orderby'] = sanitize_key( wp_unslash( $_REQUEST['orderby'] ) );
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Sorting parameters in WP_List_Table
			$args['order']   = sanitize_key( wp_unslash( $_REQUEST['order'] ) );
		}

		$args['limit']  = $per_page;
		$args['offset'] = $offset;

		$get_data = \Quicker\Utils\Helper::get_checkout_fields( $args['limit'] );
		$this->set_pagination_args(
			array(
				'total_items' => count( (array) \Quicker\Utils\Helper::get_checkout_fields() ),
				'per_page'    => $per_page,
			)
		);

		$this->items = $get_data;
	}
}
