<?php

namespace WarrantyCart\Admin\Product;

use WC_Product;
use WP_Screen;

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

/**
 * Admin Product Columns Class
 *
 * Handles custom columns in product list table.
 */
class Columns {

	/**
	 * Constructor
	 */
	public function __construct() {
		add_filter( 'manage_product_posts_columns', array( $this, 'add_product_columns' ) );
		add_action( 'manage_product_posts_custom_column', array( $this, 'render_product_columns' ), 10, 2 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
	}

	/**
	 * Add columns to product list table
	 *
	 * @param array<string, string> $columns Existing columns.
	 *
	 * @return array<string, string>
	 */
	public function add_product_columns( array $columns ): array {
		/**
		 * Filter product columns to add
		 *
		 * @param array $new_columns Columns to add.
		 */
		$new_columns = apply_filters(
			'warranty_cart_product_columns',
			array(
				'warranty_type' => \__( 'Warranty Type', 'warranty-cart' ),
			)
		);

		return array_merge( $columns, $new_columns );
	}

	/**
	 * Render custom columns
	 *
	 * @param string $column Column name.
	 * @param int    $post_id Post ID.
	 */
	public function render_product_columns( string $column, int $post_id ): void {
		if ( 'warranty_type' !== $column ) {
			return;
		}

		$product = wc_get_product( $post_id );
		if ( ! $product instanceof WC_Product ) {
			return;
		}

		$product_type = $product->get_meta( '_warranty_cart_product_type', true );
		if ( 'main_warranty' === $product_type ) {
			echo '<span class="dashicons dashicons-star-filled" title="' . esc_attr__( 'Main Warranty', 'warranty-cart' ) . '"></span>';
			esc_html_e( 'Main Warranty', 'warranty-cart' );
		} elseif ( 'additional_service' === $product_type ) {
			echo '<span class="dashicons dashicons-plus" title="' . esc_attr__( 'Additional Service', 'warranty-cart' ) . '"></span>';
			esc_html_e( 'Additional Service', 'warranty-cart' );
		} else {
			echo '<span class="dashicons dashicons-minus" title="' . esc_attr__( 'Not a Warranty Product', 'warranty-cart' ) . '"></span>';
			esc_html_e( 'Not a Warranty', 'warranty-cart' );
		}
	}

	/**
	 * Enqueue admin scripts and styles for product list table
	 *
	 * @param string $hook The current admin page hook.
	 *
	 * @return void
	 */
	public function enqueue_admin_scripts( string $hook ): void {
		$screen = get_current_screen();

		if ( 'edit.php' !== $hook || ! $screen instanceof WP_Screen ) {
			return;
		}

		if ( 'edit-product' !== $screen->id ) {
			return;
		}

		wp_add_inline_style(
			'woocommerce_admin_styles',
			'table.wp-list-table .column-warranty_type { width: 8%; min-width: 120px; }'
		);
	}
}
