<?php
/**
 * Customers list screen built on WP_List_Table.
 *
 * Renders active customers (status = 'active') read from the repository. Sorting
 * links and the search box are rendered here; their server-side handling is
 * completed in plan 01-02. The default list (active rows, default order,
 * pagination) is fully functional in this plan.
 *
 * @package WrenchPress
 */

defined( 'ABSPATH' ) || exit;

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

/**
 * Class WrenchPress_Customers_List_Table
 */
class WrenchPress_Customers_List_Table extends WP_List_Table {

	/**
	 * Admin page slug the row actions link back to.
	 */
	const PAGE_SLUG = 'wrenchpress-customers';

	/**
	 * Configure the list table.
	 */
	public function __construct() {
		parent::__construct(
			array(
				'singular' => 'customer',
				'plural'   => 'customers',
				'ajax'     => false,
			)
		);
	}

	/**
	 * Visible columns (D-14).
	 *
	 * @return array<string,string>
	 */
	public function get_columns() {
		return array(
			'name'       => __( 'Name', 'pitdesk-repair-crm' ),
			'phone'      => __( 'Phone', 'pitdesk-repair-crm' ),
			'email'      => __( 'Email', 'pitdesk-repair-crm' ),
			'created_at' => __( 'Date added', 'pitdesk-repair-crm' ),
		);
	}

	/**
	 * Sortable columns (D-14). The request key matches the repository sortable
	 * map; only Name and Date added are sortable.
	 *
	 * @return array<string,array{0:string,1:bool}>
	 */
	public function get_sortable_columns() {
		return array(
			'name'       => array( 'name', false ),
			'created_at' => array( 'created_at', false ),
		);
	}

	/**
	 * Name is the primary column (carries the row actions).
	 *
	 * @return string
	 */
	protected function get_default_primary_column_name() {
		return 'name';
	}

	/**
	 * Empty-state copy. Differentiates "no customers at all" from "no search
	 * match" per the UI copywriting contract.
	 *
	 * @return void
	 */
	public function no_items() {
		$search = isset( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		if ( '' !== $search ) {
			esc_html_e( 'No customers found matching your search.', 'pitdesk-repair-crm' );
			return;
		}

		echo '<strong>' . esc_html__( 'No customers yet', 'pitdesk-repair-crm' ) . '</strong><br />';
		echo esc_html__( 'Add your first customer to start tracking visits and service history.', 'pitdesk-repair-crm' );

		if ( current_user_can( WrenchPress_Capabilities::CREATE_CUSTOMERS ) ) {
			$add_url = add_query_arg(
				array(
					'page'   => self::PAGE_SLUG,
					'action' => 'add',
				),
				admin_url( 'admin.php' )
			);
			echo ' <a href="' . esc_url( $add_url ) . '" class="button button-primary">' . esc_html__( 'Add Customer', 'pitdesk-repair-crm' ) . '</a>';
		}
	}

	/**
	 * Render the Name column as "Last, First" with row actions.
	 *
	 * The Edit, View, and Archive targets are wired in plan 01-02; the links are
	 * rendered now (nonce-protected where they mutate state).
	 *
	 * @param object $item Customer row.
	 * @return string
	 */
	public function column_name( $item ) {
		$display = sprintf( '%s, %s', $item->last_name, $item->first_name );
		$base    = admin_url( 'admin.php' );
		$actions = array();

		if ( current_user_can( WrenchPress_Capabilities::EDIT_CUSTOMERS ) ) {
			$edit_url        = add_query_arg(
				array(
					'page'     => self::PAGE_SLUG,
					'action'   => 'edit',
					'customer' => (int) $item->id,
				),
				$base
			);
			$actions['edit'] = '<a href="' . esc_url( $edit_url ) . '">' . esc_html__( 'Edit', 'pitdesk-repair-crm' ) . '</a>';
		}

		$view_url        = add_query_arg(
			array(
				'page'     => self::PAGE_SLUG,
				'action'   => 'view',
				'customer' => (int) $item->id,
			),
			$base
		);
		$actions['view'] = '<a href="' . esc_url( $view_url ) . '">' . esc_html__( 'View', 'pitdesk-repair-crm' ) . '</a>';

		if ( current_user_can( WrenchPress_Capabilities::DELETE_CUSTOMERS ) ) {
			$archive_url        = wp_nonce_url(
				add_query_arg(
					array(
						'page'     => self::PAGE_SLUG,
						'action'   => 'archive',
						'customer' => (int) $item->id,
					),
					$base
				),
				'wrenchpress_archive_customer_' . (int) $item->id
			);
			$actions['archive'] = '<a href="' . esc_url( $archive_url ) . '" class="submitdelete">' . esc_html__( 'Archive', 'pitdesk-repair-crm' ) . '</a>';
		}

		return '<strong>' . esc_html( $display ) . '</strong>' . $this->row_actions( $actions );
	}

	/**
	 * Render non-primary columns with escaped output.
	 *
	 * @param object $item        Customer row.
	 * @param string $column_name Column key.
	 * @return string
	 */
	public function column_default( $item, $column_name ) {
		switch ( $column_name ) {
			case 'phone':
				return esc_html( $item->phone );

			case 'email':
				return esc_html( $item->email );

			case 'created_at':
				$timestamp = strtotime( (string) $item->created_at );
				return $timestamp ? esc_html( date_i18n( get_option( 'date_format' ), $timestamp ) ) : '';

			default:
				return '';
		}
	}

	/**
	 * Query active customers and configure pagination and column headers.
	 *
	 * @return void
	 */
	public function prepare_items() {
		$per_page     = 20;
		$current_page = $this->get_pagenum();
		$offset       = ( $current_page - 1 ) * $per_page;

		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only list filters from a GET request.
		$search  = isset( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) : '';
		$orderby = isset( $_REQUEST['orderby'] ) ? sanitize_key( wp_unslash( $_REQUEST['orderby'] ) ) : 'name';
		$order   = ( isset( $_REQUEST['order'] ) && 'desc' === strtolower( sanitize_key( wp_unslash( $_REQUEST['order'] ) ) ) ) ? 'DESC' : 'ASC';
		// phpcs:enable WordPress.Security.NonceVerification.Recommended

		$args = array(
			'search'   => $search,
			'orderby'  => $orderby,
			'order'    => $order,
			'per_page' => $per_page,
			'offset'   => $offset,
		);

		$this->items = WrenchPress_Customers_Repository::list_active( $args );

		$total = WrenchPress_Customers_Repository::count_active( array( 'search' => $search ) );

		$this->_column_headers = array(
			$this->get_columns(),
			array(),
			$this->get_sortable_columns(),
		);

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