<?php
/**
 * Generation History List Table.
 *
 * @package    100Prints
 */

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

class Hundred_Prints_Generation_History_List_Table extends WP_List_Table {

	/** @var Hundred_Prints_Analytics_Service */
	private $service;

	public function __construct() {
		$this->service = new Hundred_Prints_Analytics_Service();

		parent::__construct( [
			'singular' => 'generation',
			'plural'   => 'generations',
			'ajax'     => false,
		] );
	}

	public function get_columns() {
		return [
			'cb'              => '<input type="checkbox" />',
			'template_name'   => 'Template',
			'output_format'   => 'Format',
			'render_quality'  => 'Quality',
			'status'          => 'Status',
			'user_id'         => 'User',
			'visitor_ip'      => 'IP Address',
			'created_at'      => 'Date',
		];
	}

	protected function get_sortable_columns() {
		return [
			'template_name' => [ 'template_name', false ],
			'status'        => [ 'status', false ],
			'created_at'    => [ 'created_at', true ],
		];
	}

	protected function get_bulk_actions() {
		return [
			'delete' => 'Delete',
		];
	}

	protected function column_default( $item, $column_name ) {
		switch ( $column_name ) {
			case 'template_name':
				return esc_html( $item['template_name'] ?: $item['template_id'] );
			case 'output_format':
				return '<span style="text-transform:uppercase;font-weight:600;font-size:11px;background:#F0F0F0;padding:2px 8px;border-radius:4px;">' . esc_html( $item['output_format'] ) . '</span>';
			case 'render_quality':
				return esc_html( ucfirst( $item['render_quality'] ) );
			case 'status':
				$color = $item['status'] === 'success' ? '#16A34A' : '#DC2626';
				$bg    = $item['status'] === 'success' ? '#F0FDF4' : '#FEF2F2';
				return '<span style="color:' . $color . ';background:' . $bg . ';padding:2px 10px;border-radius:12px;font-size:12px;font-weight:500;">' . esc_html( ucfirst( $item['status'] ) ) . '</span>';
			case 'user_id':
				if ( empty( $item['user_id'] ) ) {
					return '<span style="color:#999;">Guest</span>';
				}
				$user = get_userdata( $item['user_id'] );
				return $user ? esc_html( $user->display_name ) : '#' . absint( $item['user_id'] );
			case 'visitor_ip':
				return $item['visitor_ip'] ? esc_html( $item['visitor_ip'] ) : '—';
			case 'created_at':
				return esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $item['created_at'] ) ) );
			default:
				return isset( $item[ $column_name ] ) ? esc_html( $item[ $column_name ] ) : '';
		}
	}

	protected function column_cb( $item ) {
		return sprintf( '<input type="checkbox" name="generation_id[]" value="%d" />', $item['id'] );
	}

	protected function column_template_name( $item ) {
		$detail_url = add_query_arg( [
			'page'   => '100prints-generation-history',
			'action' => 'view',
			'id'     => $item['id'],
		], admin_url( 'admin.php' ) );

		$delete_url = wp_nonce_url(
			add_query_arg( [
				'page'   => '100prints-generation-history',
				'action' => 'delete',
				'id'     => $item['id'],
			], admin_url( 'admin.php' ) ),
			'delete_generation_' . $item['id']
		);

		$title = esc_html( $item['template_name'] ?: $item['template_id'] );
		$actions = [
			'view'   => '<a href="' . esc_url( $detail_url ) . '">View Details</a>',
			'delete' => '<a href="' . esc_url( $delete_url ) . '" class="submitdelete" onclick="return confirm(\'Delete this record?\');">Delete</a>',
		];

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

	/**
	 * Extra controls between bulk actions and pagination.
	 */
	protected function extra_tablenav( $which ) {
		if ( 'top' !== $which ) {
			return;
		}

		global $wpdb;
		$table = esc_sql( $wpdb->prefix . '100p_generation_history' );
		$templates = $wpdb->get_results( "SELECT DISTINCT template_id, template_name FROM {$table} ORDER BY template_name ASC", OBJECT );
		$current_template = isset( $_REQUEST['filter_template'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['filter_template'] ) ) : '';
		$current_status   = isset( $_REQUEST['filter_status'] ) ? sanitize_key( wp_unslash( $_REQUEST['filter_status'] ) ) : '';
		?>
		<div class="alignleft actions">
			<select name="filter_template">
				<option value="">All Templates</option>
				<?php foreach ( $templates as $t ) : ?>
					<option value="<?php echo esc_attr( $t->template_id ); ?>" <?php selected( $current_template, $t->template_id ); ?>>
						<?php echo esc_html( $t->template_name ?: $t->template_id ); ?>
					</option>
				<?php endforeach; ?>
			</select>
			<select name="filter_status">
				<option value="">All Statuses</option>
				<option value="success" <?php selected( $current_status, 'success' ); ?>>Success</option>
				<option value="error" <?php selected( $current_status, 'error' ); ?>>Error</option>
			</select>
			<?php submit_button( 'Filter', '', 'filter_action', false ); ?>
		</div>
		<?php
	}

	public function prepare_items() {
		global $wpdb;
		$table = esc_sql( $wpdb->prefix . '100p_generation_history' );

		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
			$this->items = [];
			$this->set_pagination_args( [ 'total_items' => 0, 'per_page' => 20 ] );
			return;
		}

		$per_page = 20;
		$columns  = $this->get_columns();
		$hidden   = [];
		$sortable = $this->get_sortable_columns();

		$this->_column_headers = [ $columns, $hidden, $sortable ];

		// Handle bulk delete.
		$this->process_bulk_action();

		// Build query.
		$where_clauses = [];
		$where_values  = [];

		// Search.
		$search = isset( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) : '';
		if ( $search ) {
			$like = '%' . $wpdb->esc_like( $search ) . '%';
			$where_clauses[] = '(template_name LIKE %s OR template_id LIKE %s OR variables_json LIKE %s)';
			$where_values[]  = $like;
			$where_values[]  = $like;
			$where_values[]  = $like;
		}

		// Filter by template.
		$filter_template = isset( $_REQUEST['filter_template'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['filter_template'] ) ) : '';
		if ( $filter_template ) {
			$where_clauses[] = 'template_id = %s';
			$where_values[]  = $filter_template;
		}

		// Filter by status.
		$filter_status = isset( $_REQUEST['filter_status'] ) ? sanitize_key( wp_unslash( $_REQUEST['filter_status'] ) ) : '';
		if ( $filter_status ) {
			$where_clauses[] = 'status = %s';
			$where_values[]  = $filter_status;
		}

		$where_sql = '';
		if ( ! empty( $where_clauses ) ) {
			$where_sql = 'WHERE ' . implode( ' AND ', $where_clauses );
		}

		// Sorting.
		$allowed_orderby = [ 'template_name', 'status', 'created_at', 'output_format' ];
		$orderby = isset( $_REQUEST['orderby'] ) && in_array( $_REQUEST['orderby'], $allowed_orderby, true )
			? sanitize_key( $_REQUEST['orderby'] )
			: 'created_at';
		$order = isset( $_REQUEST['order'] ) && strtoupper( $_REQUEST['order'] ) === 'ASC' ? 'ASC' : 'DESC';

		// Count.
		if ( ! empty( $where_values ) ) {
			$total_items = (int) $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM {$table} {$where_sql}",
					...$where_values
				)
			);
		} else {
			$total_items = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} {$where_sql}" );
		}

		// Paginate.
		$current_page = $this->get_pagenum();
		$offset       = ( $current_page - 1 ) * $per_page;

		$query_values = array_merge( $where_values, [ $per_page, $offset ] );
		$this->items = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$table} {$where_sql} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d",
				...$query_values
			),
			ARRAY_A
		);

		$this->set_pagination_args( [
			'total_items' => $total_items,
			'per_page'    => $per_page,
			'total_pages' => ceil( $total_items / $per_page ),
		] );
	}

	/**
	 * Process bulk actions.
	 */
	private function process_bulk_action() {
		if ( 'delete' !== $this->current_action() ) {
			return;
		}

		// Single delete.
		if ( isset( $_REQUEST['id'] ) && isset( $_REQUEST['_wpnonce'] ) ) {
			$id    = absint( $_REQUEST['id'] );
			$nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );
			if ( $nonce && wp_verify_nonce( $nonce, 'delete_generation_' . $id ) ) {
				$this->service->delete_record( $id );
			}
			return;
		}

		// Bulk delete.
		$ids = isset( $_REQUEST['generation_id'] ) ? array_map( 'absint', (array) $_REQUEST['generation_id'] ) : [];
		if ( ! empty( $ids ) ) {
			check_admin_referer( 'bulk-generations' );
			$this->service->bulk_delete( $ids );
		}
	}
}
