<?php
namespace SabaiApps\Directories\Component\WordPressUser\DisplayStatistic;

use SabaiApps\Directories\Component\Display;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class CommentCountDisplayStatistic extends Display\Statistic\AbstractStatistic {

	protected $_counts = array();

	protected function _displayStatisticInfo( Bundle $bundle ) {
		return array(
			'label'            => __( 'Comment count', 'drts' ),
			'default_settings' => array(
				'_icon' => 'far fa-comment',
			),
		);
	}

	public function displayStatisticRender( Bundle $bundle, IEntity $entity, array $settings ) {
		return array(
			'number' => $number = empty( $this->_counts[ $entity->getId() ] ) ? 0 : $this->_counts[ $entity->getId() ],
			'format' => _n( '%d comment', '%d comments', $number, 'directories-pro' ),
		);
	}

	public function displayStatisticIsPreRenderable( Bundle $bundle, array $settings ) {
		return true;
	}

	public function displayStatisticPreRender( Bundle $bundle, array $settings, array $entities = array() ) {
		if ( empty( $entities ) ) {
			return;
		}
		if ( ! $entity_ids = array_keys( array_diff_key( $entities, $this->_counts ) ) ) {
			return;
		}

		global $wpdb;
		$sql = 'SELECT user_id, COUNT(comment_ID) AS cnt FROM ' . $wpdb->comments . ' WHERE comment_approved = 1 AND user_id IN (' . implode( ',', $entity_ids ) . ') GROUP BY user_id';
		if ( $results = $wpdb->get_results( $sql ) ) {
			foreach ( $results as $result ) {
				$this->_counts[ $result->user_id ] = $result->cnt;
			}
		}
	}
}
