<?php
/**
 * WP_List_Table subclass for the country routing rules admin view.
 *
 * @since   1.0.0
 * @package DonationRouter
 */

declare( strict_types=1 );
namespace DonationRouter;

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

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

/**
 * Renders a paginated list of country routing rules in the admin.
 *
 * @since 1.0.0
 */
class Country_Routing_List_Table extends \WP_List_Table {

	/**
	 * Routing data source.
	 *
	 * @since 1.0.0
	 *
	 * @var Country_Routing_Repository_Interface
	 */
	private Country_Routing_Repository_Interface $routing_repo;

	/**
	 * Account data source (for resolving account labels).
	 *
	 * @since 1.0.0
	 *
	 * @var Account_Repository_Interface
	 */
	private Account_Repository_Interface $account_repo;

	/**
	 * Initialise with required repositories.
	 *
	 * @since 1.0.0
	 *
	 * @param Country_Routing_Repository_Interface $routing_repo  Routing data source.
	 * @param Account_Repository_Interface         $account_repo  Account data source.
	 */
	public function __construct(
		Country_Routing_Repository_Interface $routing_repo,
		Account_Repository_Interface $account_repo
	) {
		parent::__construct(
			array(
				'singular' => 'routing',
				'plural'   => 'routings',
				'ajax'     => false,
			)
		);

		$this->routing_repo = $routing_repo;
		$this->account_repo = $account_repo;
	}

	/**
	 * Return the list of columns.
	 *
	 * @since 1.0.0
	 *
	 * @return array<string,string>
	 */
	public function get_columns(): array {
		return array(
			'cb'            => '<input type="checkbox" />',
			'country_code'  => __( 'Country', 'alamin-donation-router' ),
			'display_label' => __( 'Display Label', 'alamin-donation-router' ),
			'form_id'       => __( 'Donation Form', 'alamin-donation-router' ),
			'account'       => __( 'PayPal Account', 'alamin-donation-router' ),
			'sort_order'    => __( 'Order', 'alamin-donation-router' ),
			'status'        => __( 'Status', 'alamin-donation-router' ),
		);
	}

	/**
	 * Return sortable columns.
	 *
	 * @since 1.0.0
	 *
	 * @return array<string,array<int,mixed>>
	 */
	protected function get_sortable_columns(): array {
		return array(
			'country_code'  => array( 'country_code', false ),
			'display_label' => array( 'display_label', false ),
			'sort_order'    => array( 'sort_order', true ),
			'status'        => array( 'status', false ),
		);
	}

	/**
	 * Return the list of bulk actions.
	 *
	 * @since 1.0.0
	 *
	 * @return array<string,string>
	 */
	protected function get_bulk_actions(): array {
		return array(
			'deactivate' => __( 'Deactivate', 'alamin-donation-router' ),
		);
	}

	/**
	 * Load items and set pagination data.
	 *
	 * @since 1.0.0
	 *
	 * @return void
	 */
	public function prepare_items(): void {
		$columns  = $this->get_columns();
		$hidden   = array();
		$sortable = $this->get_sortable_columns();

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

		$routings    = $this->routing_repo->find_all();
		$this->items = $routings;

		$this->set_pagination_args(
			array(
				'total_items' => count( $routings ),
				'per_page'    => count( $routings ),
			)
		);
	}

	/**
	 * Render the checkbox column for bulk actions.
	 *
	 * @since 1.0.0
	 *
	 * @param Country_Routing $item  Current row item.
	 *
	 * @return string
	 */
	protected function column_cb( $item ): string { // phpcs:ignore
		return sprintf(
			'<input type="checkbox" name="routing_ids[]" value="%d" />',
			(int) $item->id
		);
	}

	/**
	 * Render the Country column with row actions.
	 *
	 * @since 1.0.0
	 *
	 * @param Country_Routing $item  Current row item.
	 *
	 * @return string
	 */
	protected function column_country_code( $item ): string { // phpcs:ignore
		$countries    = Account_Form::get_paypal_countries();
		$country_name = $countries[ $item->country_code ] ?? $item->country_code;

		$edit_url = add_query_arg(
			array(
				'post_type'  => 'give_forms',
				'page'       => Admin_Settings::MENU_SLUG,
				'tab'        => Admin_Settings::TAB_ROUTING,
				'view'       => 'edit',
				'routing_id' => $item->id,
			),
			admin_url( 'edit.php' )
		);

		$deactivate_url = wp_nonce_url(
			add_query_arg(
				array(
					'action'     => 'ador_deactivate_routing',
					'routing_id' => $item->id,
				),
				admin_url( 'admin-post.php' )
			),
			'ador_deactivate_routing_' . $item->id,
			'ador_nonce'
		);

		$row_actions = array(
			'edit' => sprintf(
				'<a href="%s">%s</a>',
				esc_url( $edit_url ),
				esc_html__( 'Edit', 'alamin-donation-router' )
			),
		);

		if ( $item->is_active ) {
			$row_actions['deactivate'] = sprintf(
				'<a href="%s" class="ador-deactivate-routing-link" data-confirm="%s">%s</a>',
				esc_url( $deactivate_url ),
				esc_attr__( 'Are you sure you want to deactivate this routing rule?', 'alamin-donation-router' ),
				esc_html__( 'Deactivate', 'alamin-donation-router' )
			);
		}

		return sprintf(
			'<strong><abbr title="%s">%s</abbr></strong> %s',
			esc_attr( $country_name ),
			esc_html( $item->country_code ),
			$this->row_actions( $row_actions )
		);
	}

	/**
	 * Render the Display Label column.
	 *
	 * @since 1.0.0
	 *
	 * @param Country_Routing $item  Current row item.
	 *
	 * @return string
	 */
	protected function column_display_label( $item ): string { // phpcs:ignore
		return wp_kses_post( $item->display_label );
	}

	/**
	 * Render the Donation Form column.
	 *
	 * @since 1.0.0
	 *
	 * @param Country_Routing $item  Current row item.
	 *
	 * @return string
	 */
	protected function column_form_id( $item ): string { // phpcs:ignore
		$title = get_the_title( $item->form_id );
		if ( '' === (string) $title ) {
			return esc_html( sprintf( '#%d', $item->form_id ) );
		}

		$edit_link = get_edit_post_link( $item->form_id );
		if ( is_string( $edit_link ) && '' !== $edit_link ) {
			return sprintf( '<a href="%s">%s</a>', esc_url( $edit_link ), esc_html( $title ) );
		}

		return esc_html( $title );
	}

	/**
	 * Render the PayPal Account column.
	 *
	 * @since 1.0.0
	 *
	 * @param Country_Routing $item  Current row item.
	 *
	 * @return string
	 */
	protected function column_account( $item ): string { // phpcs:ignore
		try {
			$account = $this->account_repo->find_by_id( $item->account_id );
			return esc_html( $account->account_label );
		} catch ( Account_Not_Found_Exception $e ) {
			return esc_html( sprintf( '#%d', $item->account_id ) );
		}
	}

	/**
	 * Render the Sort Order column.
	 *
	 * @since 1.0.0
	 *
	 * @param Country_Routing $item  Current row item.
	 *
	 * @return string
	 */
	protected function column_sort_order( $item ): string { // phpcs:ignore
		return esc_html( (string) $item->sort_order );
	}

	/**
	 * Render the Status column.
	 *
	 * @since 1.0.0
	 *
	 * @param Country_Routing $item  Current row item.
	 *
	 * @return string
	 */
	protected function column_status( $item ): string { // phpcs:ignore
		if ( $item->is_active ) {
			return '<span class="ador-badge ador-badge--active">' . esc_html__( 'Active', 'alamin-donation-router' ) . '</span>';
		}

		return '<span class="ador-badge ador-badge--inactive">' . esc_html__( 'Inactive', 'alamin-donation-router' ) . '</span>';
	}

	/**
	 * Default column renderer.
	 *
	 * @since 1.0.0
	 *
	 * @param Country_Routing $item         Current row item.
	 * @param string          $column_name  Column slug.
	 *
	 * @return string
	 */
	protected function column_default( $item, $column_name ): string { // phpcs:ignore
		return '';
	}

	/**
	 * Render the "no items" message.
	 *
	 * @since 1.0.0
	 *
	 * @return void
	 */
	public function no_items(): void {
		esc_html_e( 'No country routing rules found. Add one to get started.', 'alamin-donation-router' );
	}
}
