<?php
/**
 * WP_List_Table subclass for displaying PayPal account records.
 *
 * @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';
}

/**
 * Tabular list of all PayPal accounts with row and bulk actions.
 *
 * Columns: Label, Country, Legal Entity, Merchant ID (truncated), Status, Actions.
 * Row actions: Edit, Deactivate (JS confirm), View Webhook Setup.
 * Bulk actions: Deactivate selected.
 *
 * @since 1.0.0
 */
class Account_List_Table extends \WP_List_Table {

	/**
	 * Maximum characters shown for merchant ID in the table cell.
	 *
	 * @since 1.0.0
	 *
	 * @var int
	 */
	private const MERCHANT_ID_TRUNCATE = 12;

	/**
	 * Account data source.
	 *
	 * @since 1.0.0
	 *
	 * @var Account_Repository_Interface
	 */
	private Account_Repository_Interface $account_repo;

	/**
	 * Initialise the list table.
	 *
	 * @since 1.0.0
	 *
	 * @param Account_Repository_Interface $account_repo  Account data source.
	 */
	public function __construct( Account_Repository_Interface $account_repo ) {
		parent::__construct(
			array(
				'singular' => 'paypal_account',
				'plural'   => 'paypal_accounts',
				'ajax'     => false,
			)
		);

		$this->account_repo = $account_repo;
	}

	/**
	 * Return the column definitions for the table.
	 *
	 * @since 1.0.0
	 *
	 * @return array<string,string>
	 */
	public function get_columns(): array {
		return array(
			'cb'              => '<input type="checkbox" />',
			'account_label'   => __( 'Label', 'alamin-donation-router' ),
			'account_country' => __( 'Country', 'alamin-donation-router' ),
			'legal_entity'    => __( 'Legal Entity', 'alamin-donation-router' ),
			'merchant_id'     => __( 'Merchant ID', 'alamin-donation-router' ),
			'mode'            => __( 'Mode', 'alamin-donation-router' ),
			'status'          => __( 'Status', 'alamin-donation-router' ),
			'actions'         => __( 'Actions', 'alamin-donation-router' ),
		);
	}

	/**
	 * Return the sortable column definitions.
	 *
	 * @since 1.0.0
	 *
	 * @return array<string,array{string,bool}>
	 */
	protected function get_sortable_columns(): array {
		return array(
			'account_label'   => array( 'account_label', true ),
			'account_country' => array( 'account_country', false ),
			'status'          => array( 'status', false ),
		);
	}

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

	/**
	 * Load all accounts and configure column headers.
	 *
	 * @since 1.0.0
	 *
	 * @return void
	 */
	public function prepare_items(): void {
		$this->_column_headers = array(
			$this->get_columns(),
			array(),
			$this->get_sortable_columns(),
			'account_label',
		);

		$this->items = $this->account_repo->find_all();
	}

	/**
	 * Render the checkbox column for bulk actions.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $item  Current row data object.
	 *
	 * @return string
	 */
	protected function column_cb( $item ): string {
		if ( ! $item instanceof PayPal_Account || null === $item->id ) {
			return '';
		}

		return sprintf(
			'<input type="checkbox" name="account_ids[]" value="%d" />',
			absint( $item->id )
		);
	}

	/**
	 * Render the Label column with row actions.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $item  Current row data object.
	 *
	 * @return string
	 */
	protected function column_account_label( $item ): string {
		if ( ! $item instanceof PayPal_Account ) {
			return '';
		}

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

		$deactivate_url = wp_nonce_url(
			add_query_arg(
				array(
					'action'     => 'ador_deactivate_account',
					'account_id' => $item->id,
				),
				admin_url( 'admin-post.php' )
			),
			'ador_deactivate_' . $item->id
		);

		$webhook_url = add_query_arg(
			array(
				'post_type'  => 'give_forms',
				'page'       => Admin_Settings::MENU_SLUG,
				'tab'        => Admin_Settings::TAB_ACCOUNTS,
				'view'       => 'webhook',
				'account_id' => $item->id,
			),
			admin_url( 'edit.php' )
		);

		$resync_url = wp_nonce_url(
			add_query_arg(
				array(
					'action'     => Onboarding_Handler::ACTION_RESYNC,
					'account_id' => $item->id,
				),
				admin_url( 'admin-post.php' )
			),
			Onboarding_Handler::ACTION_RESYNC . '_' . $item->id
		);

		$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-link" data-confirm="1">%s</a>',
				esc_url( $deactivate_url ),
				esc_html__( 'Deactivate', 'alamin-donation-router' )
			);
		} else {
			$activate_url = wp_nonce_url(
				add_query_arg(
					array(
						'action'     => Onboarding_Handler::ACTION_ACTIVATE,
						'account_id' => $item->id,
					),
					admin_url( 'admin-post.php' )
				),
				'ador_activate_' . $item->id
			);

			$row_actions['activate'] = sprintf(
				'<a href="%s" class="ador-activate-link">%s</a>',
				esc_url( $activate_url ),
				esc_html__( 'Activate', 'alamin-donation-router' )
			);
		}

		$row_actions['webhook'] = sprintf(
			'<a href="%s">%s</a>',
			esc_url( $webhook_url ),
			esc_html__( 'Webhook Setup', 'alamin-donation-router' )
		);

		$row_actions['resync'] = sprintf(
			'<a href="%s" class="ador-resync-link">%s</a>',
			esc_url( $resync_url ),
			esc_html__( 'Re-sync from GiveWP', 'alamin-donation-router' )
		);

		$register_webhook_url = wp_nonce_url(
			add_query_arg(
				array(
					'action'     => Onboarding_Handler::ACTION_REGISTER_WEBHOOK,
					'account_id' => $item->id,
				),
				admin_url( 'admin-post.php' )
			),
			Onboarding_Handler::ACTION_REGISTER_WEBHOOK . '_' . $item->id
		);

		$row_actions['register_webhook'] = sprintf(
			'<a href="%s" class="ador-register-webhook-link">%s</a>',
			esc_url( $register_webhook_url ),
			$item->webhook_id
				? esc_html__( 'Re-register webhook', 'alamin-donation-router' )
				: esc_html__( 'Register webhook', 'alamin-donation-router' )
		);

		$delete_url = wp_nonce_url(
			add_query_arg(
				array(
					'action'     => Onboarding_Handler::ACTION_DELETE,
					'account_id' => $item->id,
				),
				admin_url( 'admin-post.php' )
			),
			'ador_delete_' . $item->id
		);

		$row_actions['delete'] = sprintf(
			'<a href="%s" class="ador-delete-link" data-confirm="1">%s</a>',
			esc_url( $delete_url ),
			esc_html__( 'Delete', 'alamin-donation-router' )
		);

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

	/**
	 * Render the Mode column as a live/sandbox badge.
	 *
	 * @since 1.1.0
	 *
	 * @param mixed $item  Current row data object.
	 *
	 * @return string
	 */
	protected function column_mode( $item ): string {
		if ( ! $item instanceof PayPal_Account ) {
			return '';
		}

		$is_sandbox = 'sandbox' === $item->mode;

		return sprintf(
			'<span class="ador-mode-badge ador-mode-%1$s">%2$s</span>',
			esc_attr( $item->mode ),
			esc_html( $is_sandbox ? __( 'Sandbox', 'alamin-donation-router' ) : __( 'Live', 'alamin-donation-router' ) )
		);
	}

	/**
	 * Render the Country column.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $item  Current row data object.
	 *
	 * @return string
	 */
	protected function column_account_country( $item ): string {
		if ( ! $item instanceof PayPal_Account ) {
			return '';
		}

		$countries = Account_Form::get_paypal_countries();
		$name      = $countries[ $item->account_country ] ?? $item->account_country;

		return esc_html( $name );
	}

	/**
	 * Render the Legal Entity column.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $item  Current row data object.
	 *
	 * @return string
	 */
	protected function column_legal_entity( $item ): string {
		if ( ! $item instanceof PayPal_Account ) {
			return '';
		}

		return esc_html( $item->legal_entity_name );
	}

	/**
	 * Render the Merchant ID column with truncated display.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $item  Current row data object.
	 *
	 * @return string
	 */
	protected function column_merchant_id( $item ): string {
		if ( ! $item instanceof PayPal_Account ) {
			return '';
		}

		$mid = $item->merchant_id;
		if ( strlen( $mid ) > self::MERCHANT_ID_TRUNCATE ) {
			return sprintf(
				'<abbr title="%s">%s&hellip;</abbr>',
				esc_attr( $mid ),
				esc_html( substr( $mid, 0, self::MERCHANT_ID_TRUNCATE ) )
			);
		}

		return esc_html( $mid );
	}

	/**
	 * Render the Status column.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $item  Current row data object.
	 *
	 * @return string
	 */
	protected function column_status( $item ): string {
		if ( ! $item instanceof PayPal_Account ) {
			return '';
		}

		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>';
	}

	/**
	 * Render the Actions column with quick-action links.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $item  Current row data object.
	 *
	 * @return string
	 */
	protected function column_actions( $item ): string {
		if ( ! $item instanceof PayPal_Account ) {
			return '';
		}

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

		$output = sprintf(
			'<a href="%s" class="button button-small">%s</a>',
			esc_url( $edit_url ),
			esc_html__( 'Edit', 'alamin-donation-router' )
		);

		if ( $item->is_active ) {
			$deactivate_url = wp_nonce_url(
				add_query_arg(
					array(
						'action'     => 'ador_deactivate_account',
						'account_id' => $item->id,
					),
					admin_url( 'admin-post.php' )
				),
				'ador_deactivate_' . $item->id
			);

			$output .= sprintf(
				' <a href="%s" class="button button-small ador-deactivate-link" data-confirm="1">%s</a>',
				esc_url( $deactivate_url ),
				esc_html__( 'Deactivate', 'alamin-donation-router' )
			);
		} else {
			$activate_url = wp_nonce_url(
				add_query_arg(
					array(
						'action'     => Onboarding_Handler::ACTION_ACTIVATE,
						'account_id' => $item->id,
					),
					admin_url( 'admin-post.php' )
				),
				'ador_activate_' . $item->id
			);

			$output .= sprintf(
				' <a href="%s" class="button button-small ador-activate-link">%s</a>',
				esc_url( $activate_url ),
				esc_html__( 'Activate', 'alamin-donation-router' )
			);
		}

		$delete_url = wp_nonce_url(
			add_query_arg(
				array(
					'action'     => Onboarding_Handler::ACTION_DELETE,
					'account_id' => $item->id,
				),
				admin_url( 'admin-post.php' )
			),
			'ador_delete_' . $item->id
		);

		$output .= sprintf(
			' <a href="%s" class="button button-small ador-delete-link" data-confirm="1">%s</a>',
			esc_url( $delete_url ),
			esc_html__( 'Delete', 'alamin-donation-router' )
		);

		return $output;
	}

	/**
	 * Render a generic column value.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed  $item         Current row data object.
	 * @param string $column_name  Column key.
	 *
	 * @return string
	 */
	protected function column_default( $item, $column_name ): string {
		return '';
	}

	/**
	 * Render the message shown when no accounts exist.
	 *
	 * @since 1.0.0
	 *
	 * @return void
	 */
	public function no_items(): void {
		esc_html_e( 'No PayPal accounts connected yet. Click "Add New Account" to get started.', 'alamin-donation-router' );
	}
}
