<?php
/**
 * Employees list table.
 *
 * @package MerchantKits\AttendanceManager
 */

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

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

/**
 * Renders the employees admin list with sorting, search, filters, and bulk actions.
 */
class MKAM_Admin_Employees_Table extends WP_List_Table {

	/**
	 * Total items for pagination.
	 *
	 * @var int
	 */
	private $total_items = 0;

	/**
	 * Set up the table.
	 */
	public function __construct() {
		parent::__construct(
			array(
				'singular' => 'employee',
				'plural'   => 'employees',
				'ajax'     => false,
			)
		);
	}

	/**
	 * Define columns.
	 *
	 * @return array
	 */
	public function get_columns() {
		return array(
			'cb'              => '<input type="checkbox" />',
			'employee_id'     => __( 'Employee ID', 'merchantkits-attendance-manager' ),
			'name'            => __( 'Name', 'merchantkits-attendance-manager' ),
			'email'           => __( 'Email', 'merchantkits-attendance-manager' ),
			'department'      => __( 'Department', 'merchantkits-attendance-manager' ),
			'designation'     => __( 'Designation', 'merchantkits-attendance-manager' ),
			'employment_type' => __( 'Type', 'merchantkits-attendance-manager' ),
			'status'          => __( 'Status', 'merchantkits-attendance-manager' ),
		);
	}

	/**
	 * Sortable columns.
	 *
	 * @return array
	 */
	public function get_sortable_columns() {
		return array(
			'employee_id' => array( 'id', false ),
			'name'        => array( 'last_name', false ),
			'email'       => array( 'email', false ),
			'department'  => array( 'department', false ),
			'status'      => array( 'status', false ),
		);
	}

	/**
	 * Bulk actions.
	 *
	 * @return array
	 */
	public function get_bulk_actions() {
		return array(
			'activate'   => __( 'Activate', 'merchantkits-attendance-manager' ),
			'deactivate' => __( 'Deactivate', 'merchantkits-attendance-manager' ),
			'delete'     => __( 'Delete', 'merchantkits-attendance-manager' ),
			'export'     => __( 'Export CSV', 'merchantkits-attendance-manager' ),
		);
	}

	/**
	 * Checkbox column.
	 *
	 * @param array $item Employee row.
	 * @return string
	 */
	public function column_cb( $item ) {
		return sprintf( '<input type="checkbox" name="employee[]" value="%d" />', absint( $item['id'] ) );
	}

	/**
	 * Name column with row actions.
	 *
	 * @param array $item Employee row.
	 * @return string
	 */
	public function column_name( $item ) {
		$base = admin_url( 'admin.php?page=mkam-employees' );

		$edit_url = wp_nonce_url(
			add_query_arg(
				array(
					'action' => 'edit',
					'id'     => absint( $item['id'] ),
				),
				$base
			),
			'mkam_employee_edit_' . $item['id']
		);

		$attendance_url = add_query_arg(
			array(
				'page'        => 'mkam-attendance',
				'employee_id' => absint( $item['id'] ),
			),
			admin_url( 'admin.php' )
		);

		$leaves_url = add_query_arg(
			array(
				'page'        => 'mkam-leaves',
				'employee_id' => absint( $item['id'] ),
			),
			admin_url( 'admin.php' )
		);

		$delete_url = wp_nonce_url(
			add_query_arg(
				array(
					'action' => 'delete',
					'id'     => absint( $item['id'] ),
				),
				$base
			),
			'mkam_employee_delete_' . $item['id']
		);

		$name = MKAM_Employee::full_name( $item );

		$actions = array(
			'edit'       => sprintf( '<a href="%s">%s</a>', esc_url( $edit_url ), esc_html__( 'Edit', 'merchantkits-attendance-manager' ) ),
			'attendance' => sprintf( '<a href="%s">%s</a>', esc_url( $attendance_url ), esc_html__( 'View Attendance', 'merchantkits-attendance-manager' ) ),
			'leaves'     => sprintf( '<a href="%s">%s</a>', esc_url( $leaves_url ), esc_html__( 'View Leaves', 'merchantkits-attendance-manager' ) ),
			'delete'     => sprintf(
				'<a href="%s" class="mkam-delete" onclick="return confirm(\'%s\');">%s</a>',
				esc_url( $delete_url ),
				esc_js( __( 'Delete this employee?', 'merchantkits-attendance-manager' ) ),
				esc_html__( 'Delete', 'merchantkits-attendance-manager' )
			),
		);

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

	/**
	 * Status column with a colored pill.
	 *
	 * @param array $item Employee row.
	 * @return string
	 */
	public function column_status( $item ) {
		$status = $item['status'];
		$labels = array(
			'active'     => __( 'Active', 'merchantkits-attendance-manager' ),
			'inactive'   => __( 'Inactive', 'merchantkits-attendance-manager' ),
			'terminated' => __( 'Terminated', 'merchantkits-attendance-manager' ),
			'on_leave'   => __( 'On Leave', 'merchantkits-attendance-manager' ),
		);

		$label = isset( $labels[ $status ] ) ? $labels[ $status ] : $status;

		return sprintf(
			'<span class="mkam-badge mkam-badge--%s">%s</span>',
			esc_attr( $status ),
			esc_html( $label )
		);
	}

	/**
	 * Employment type column with a readable label.
	 *
	 * @param array $item Employee row.
	 * @return string
	 */
	public function column_employment_type( $item ) {
		$labels = array(
			'full_time' => __( 'Full-time', 'merchantkits-attendance-manager' ),
			'part_time' => __( 'Part-time', 'merchantkits-attendance-manager' ),
			'contract'  => __( 'Contract', 'merchantkits-attendance-manager' ),
			'intern'    => __( 'Intern', 'merchantkits-attendance-manager' ),
		);

		return isset( $labels[ $item['employment_type'] ] ) ? esc_html( $labels[ $item['employment_type'] ] ) : esc_html( $item['employment_type'] );
	}

	/**
	 * Default column rendering with escaping.
	 *
	 * @param array  $item        Employee row.
	 * @param string $column_name Column key.
	 * @return string
	 */
	public function column_default( $item, $column_name ) {
		$value = isset( $item[ $column_name ] ) ? $item[ $column_name ] : '';
		return esc_html( $value );
	}

	/**
	 * Message shown when there are no employees.
	 *
	 * @return void
	 */
	public function no_items() {
		esc_html_e( 'No employees found.', 'merchantkits-attendance-manager' );
	}

	/**
	 * Render the department/status filter controls above the table.
	 *
	 * @param string $which Top or bottom.
	 * @return void
	 */
	protected function extra_tablenav( $which ) {
		if ( 'top' !== $which ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$current_status = isset( $_REQUEST['status_filter'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['status_filter'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$current_dept = isset( $_REQUEST['department_filter'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['department_filter'] ) ) : '';

		$statuses = array(
			'active'     => __( 'Active', 'merchantkits-attendance-manager' ),
			'inactive'   => __( 'Inactive', 'merchantkits-attendance-manager' ),
			'terminated' => __( 'Terminated', 'merchantkits-attendance-manager' ),
			'on_leave'   => __( 'On Leave', 'merchantkits-attendance-manager' ),
		);

		echo '<div class="alignleft actions">';

		echo '<select name="status_filter">';
		echo '<option value="">' . esc_html__( 'All statuses', 'merchantkits-attendance-manager' ) . '</option>';
		foreach ( $statuses as $value => $label ) {
			printf(
				'<option value="%s" %s>%s</option>',
				esc_attr( $value ),
				selected( $current_status, $value, false ),
				esc_html( $label )
			);
		}
		echo '</select>';

		echo '<input type="text" name="department_filter" value="' . esc_attr( $current_dept ) . '" placeholder="' . esc_attr__( 'Department', 'merchantkits-attendance-manager' ) . '" />';

		submit_button( __( 'Filter', 'merchantkits-attendance-manager' ), '', 'filter_action', false );

		echo '</div>';
	}

	/**
	 * Prepare query args, pagination, columns, and items.
	 *
	 * @return void
	 */
	public function prepare_items() {
		$per_page = (int) get_option( 'mkam_items_per_page', 20 );
		$paged    = $this->get_pagenum();

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

		$this->process_bulk_action();

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$search = isset( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$status = isset( $_REQUEST['status_filter'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['status_filter'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$department = isset( $_REQUEST['department_filter'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['department_filter'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$orderby = isset( $_REQUEST['orderby'] ) ? sanitize_key( wp_unslash( $_REQUEST['orderby'] ) ) : 'created_at';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$order = isset( $_REQUEST['order'] ) ? sanitize_key( wp_unslash( $_REQUEST['order'] ) ) : 'desc';

		$args = array(
			'status'     => $status,
			'department' => $department,
			'search'     => $search,
			'orderby'    => $orderby,
			'order'      => $order,
			'per_page'   => $per_page,
			'page'       => $paged,
		);

		$this->total_items = MKAM_Employee::count( $args );
		$this->items       = MKAM_Employee::query( $args );

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

	/**
	 * Handle bulk actions.
	 *
	 * @return void
	 */
	public function process_bulk_action() {
		$action = $this->current_action();

		if ( ! $action ) {
			return;
		}

		// Verify the WP_List_Table bulk-action nonce.
		check_admin_referer( 'bulk-' . $this->_args['plural'] );

		if ( ! current_user_can( MKAM_Core::admin_capability() ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$ids = isset( $_REQUEST['employee'] ) ? array_map( 'absint', (array) wp_unslash( $_REQUEST['employee'] ) ) : array();

		if ( empty( $ids ) ) {
			return;
		}

		switch ( $action ) {
			case 'activate':
				foreach ( $ids as $id ) {
					MKAM_Employee::update( $id, array( 'status' => 'active' ) );
				}
				break;

			case 'deactivate':
				foreach ( $ids as $id ) {
					MKAM_Employee::update( $id, array( 'status' => 'inactive' ) );
				}
				break;

			case 'delete':
				foreach ( $ids as $id ) {
					MKAM_Employee::delete( $id );
				}
				break;

			case 'export':
				if ( class_exists( 'MKAM_Export' ) ) {
					$export = new MKAM_Export();
					$export->employees_csv( $ids );
				}
				break;
		}
	}
}
