<?php
/**
 * Trivia Post Type
 *
 * @package ClientCore
 */

namespace CNP;

use WP_Query;

/**
 * PostTypeTrivia Class
 */
class PostTypeTrivia {

	/**
	 * Used for object caching
	 *
	 * @var array
	 */
	private $cache;

	/**
	 * PostTypeTrivia constructor
	 */
	public function __construct() {

		add_action( 'acf/save_post', array( $this, 'action_save_post' ) );

	}

	/**
	 * Additional functions after post save
	 *
	 * @param int|string $post_id The ID of the post being saved.
	 */
	public function action_save_post( $post_id ) {

		if ( 'trivia' !== get_post_type( $post_id ) ) {
			return;
		}

		$trivia_display_date = get_field( 'trivia_display_date', $post_id );
		if ( ! $trivia_display_date ) {
			return;
		}

		$month = $trivia_display_date['month'];
		$day   = $trivia_display_date['day'];

		if ( '0' === $month || '0' === $day ) {
			return;
		}

		$trivia_date = sprintf( '%s/%s', $month, $day );
		update_post_meta( $post_id, '_trivia_date', $trivia_date );

	}

	/**
	 * Returns a trivia for today or a random trivia.
	 *
	 * @return string|false
	 */
	public function get() {

		$trivia = $this->get_trivia_for_date();
		if ( ! $trivia ) {
			$trivia = $this->get_random_trivia();
		}
		if ( ! $trivia ) {
			return false;
		}

		return $trivia[0]->post_title;
	}

	/**
	 * Get a random trivia
	 *
	 * @param array $args Array of WP_Query arguments.
	 *
	 * @return \WP_Post|false Returns a WP_Post object or false if no results
	 */
	public function get_trivia( $args ) {

		$trivia_query = new WP_Query( $args );
		if ( ! $trivia_query->have_posts() ) {

			return false;
		}

		$trivia_posts = $trivia_query->get_posts();
		shuffle( $trivia_posts );

		return array_slice( $trivia_posts, 0, 1 );
	}

	/**
	 * Get trivia for the provided date. Use m/j. If no date is provided, defaults to current month and day.
	 *
	 * @param string $date The date for which to get trivia.
	 *
	 * @return \WP_Post|false Returns a WP_Post object or false if no results
	 */
	public function get_trivia_for_date( $date = '' ) {

		if ( empty( $date ) ) {
			$date = sprintf( '%s/%s', gmdate( 'n' ), gmdate( 'j' ) );
		}

		if ( empty( $this->cache[ $date ] ) ) {

			$args = array(
				'post_type'  => 'trivia',
				'meta_query' => array(
					array(
						'key'   => '_trivia_date',
						'value' => $date,
					),
				),
			);

			$this->cache[ $date ] = $this->get_trivia( $args );

		}

		return $this->cache[ $date ];
	}

	/**
	 * Get a random trivia.
	 *
	 * @return \WP_Post|false Returns a WP_Post object or false if no results
	 */
	public function get_random_trivia() {

		if ( empty( $this->cache['random'] ) ) {

			$args = array(
				'post_type'  => 'trivia',
				'meta_query' => array(
					array(
						'key'   => 'trivia_random',
						'value' => '1',
					),
				),
			);

			$this->cache['random'] = $this->get_trivia( $args );

		}

		return $this->cache['random'];
	}

}
