<?php
/**
 * Admin Columns Handler
 *
 * Adds custom columns to post list tables.
 *
 * @package WP_Agentic_Writer
 * @since 0.1.0
 */

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

/**
 * Admin Columns Handler Class
 */
class WP_Agentic_Writer_Admin_Columns {

	/**
	 * Instance of this class.
	 *
	 * @var WP_Agentic_Writer_Admin_Columns
	 */
	private static $instance = null;

	/**
	 * Get instance.
	 *
	 * @return WP_Agentic_Writer_Admin_Columns
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		// Use the specific post type hooks for 'post' post type
		add_filter( 'manage_post_posts_columns', array( $this, 'add_cost_column' ) );
		add_action( 'manage_post_posts_custom_column', array( $this, 'render_cost_column' ), 10, 2 );
		add_filter( 'manage_edit-post_sortable_columns', array( $this, 'make_cost_column_sortable' ) );
		add_action( 'pre_get_posts', array( $this, 'sort_by_cost' ) );
		add_action( 'admin_head', array( $this, 'custom_css' ) );
	}

	/**
	 * Add cost column to post list table.
	 *
	 * @param array $columns Existing columns.
	 * @return array Modified columns.
	 */
	public function add_cost_column( $columns ) {
		// Insert cost column before date column
		$new_columns = array();
		foreach ( $columns as $key => $value ) {
			if ( $key === 'date' ) {
				$new_columns['wp_aw_cost'] = '💰 OpenRouter Cost';
			}
			$new_columns[ $key ] = $value;
		}
		return $new_columns;
	}

	/**
	 * Render cost column content.
	 *
	 * @param string $column Column name.
	 * @param int    $post_id Post ID.
	 */
	public function render_cost_column( $column, $post_id ) {
		if ( $column !== 'wp_aw_cost' ) {
			return;
		}

		$total_cost = 0.0;
		if ( class_exists( 'WP_Agentic_Writer_Cost_Tracker' ) ) {
			$total_cost = WP_Agentic_Writer_Cost_Tracker::get_instance()->get_session_total( $post_id );
		}

		if ( $total_cost && $total_cost > 0 ) {
			// Color code based on cost
			$color = '#61ff86ff'; // Green
			if ( $total_cost > 0.5 ) {
				$color = '#fac62aff'; // Yellow
			}
			if ( $total_cost > 1.0 ) {
				$color = '#fe717fff'; // Red
			}

			printf(
				'<span style="color: %s; font-weight: 600; font-family: ui-monospace, monospace;">$%s</span>',
				esc_attr( $color ),
				esc_html( number_format( $total_cost, 4 ) )
			);
		} else {
			echo '<span style="color: #999; font-family: ui-monospace, monospace;">-</span>';
		}
	}

	/**
	 * Make cost column sortable.
	 *
	 * @param array $columns Sortable columns.
	 * @return array Modified columns.
	 */
	public function make_cost_column_sortable( $columns ) {
		$columns['wp_aw_cost'] = 'wp_aw_cost';
		return $columns;
	}

	/**
	 * Sort posts by cost when column is clicked.
	 *
	 * @param WP_Query $query Query object.
	 */
	public function sort_by_cost( $query ) {
		if ( ! is_admin() || ! $query->is_main_query() ) {
			return;
		}

		$orderby = $query->get( 'orderby' );
		if ( $orderby !== 'wp_aw_cost' ) {
			return;
		}

		global $wpdb;
		$table_name = $wpdb->prefix . 'wpaw_cost_tracking';

		// Join with costs table and order by sum
		$query->set( 'meta_query', array() );
		add_filter( 'posts_join', array( $this, 'cost_join' ) );
		add_filter( 'posts_orderby', array( $this, 'cost_orderby' ) );
		add_filter( 'posts_groupby', array( $this, 'cost_groupby' ) );
	}

	/**
	 * Join with costs table.
	 *
	 * @param string $join Join clause.
	 * @return string Modified join clause.
	 */
	public function cost_join( $join ) {
		global $wpdb;
		$table_name = $wpdb->prefix . 'wpaw_cost_tracking';
		$join .= " LEFT JOIN {$table_name} ON {$wpdb->posts}.ID = {$table_name}.post_id";
		return $join;
	}

	/**
	 * Order by cost sum.
	 *
	 * @param string $orderby Order by clause.
	 * @return string Modified order by clause.
	 */
	public function cost_orderby( $orderby ) {
		global $wpdb;
		$order = isset( $_GET['order'] ) && $_GET['order'] === 'asc' ? 'ASC' : 'DESC';
		$table_name = $wpdb->prefix . 'wpaw_cost_tracking';
		return "SUM({$table_name}.cost) {$order}";
	}

	/**
	 * Group by post ID.
	 *
	 * @param string $groupby Group by clause.
	 * @return string Modified group by clause.
	 */
	public function cost_groupby( $groupby ) {
		global $wpdb;
		if ( ! $groupby ) {
			$groupby = "{$wpdb->posts}.ID";
		}
		return $groupby;
	}

	public function custom_css() {
		?>
		<style>
			th#wp_aw_cost a > span:first-child, td.wp_aw_cost.column-wp_aw_cost > span {
				font-family: ui-monospace, monospace;
				font-weight: 600;
				font-size: 12px;
				background: #1e1e1e;
				padding: 3px 6px;
				color: #cacaca;
			}
		</style>
		<?php
	}
}
