<?php

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

class AVIN_Admin_Columns {
	private $repository;

	public function __construct( AVIN_Views_Repository $repository ) {
		$this->repository = $repository;
	}

	public function init() {
		foreach ( $this->tracked_post_types() as $post_type ) {
			add_filter( "manage_{$post_type}_posts_columns", array( $this, 'add_columns' ) );
			add_action( "manage_{$post_type}_posts_custom_column", array( $this, 'render_column' ), 10, 2 );
		}
	}

	public function add_columns( $columns ) {
		$columns['avin_total_views'] = __( 'Total Views', 'apex-view-insights' );
		$columns['avin_today_views'] = __( 'Today Views', 'apex-view-insights' );
		return $columns;
	}

	public function render_column( $column, $post_id ) {
		if ( 'avin_total_views' === $column ) {
			echo esc_html( number_format_i18n( $this->repository->get_total_views( $post_id ) ) );
		}

		if ( 'avin_today_views' === $column ) {
			echo esc_html( number_format_i18n( $this->repository->get_today_views( $post_id ) ) );
		}
	}

	private function tracked_post_types() {
		$types = get_option( 'avin_tracked_post_types', array( 'post', 'page', 'product' ) );
		return array_values( array_filter( array_map( 'sanitize_key', (array) $types ) ) );
	}
}
