<?php
/**
 * Post status filter.
 *
 * @package mwp-al-ext
 */

namespace WSAL\MainWPExtension\Extensions\Search;

use \WSAL\MainWPExtension as MWPAL_Extension;
use \WSAL\MainWPExtension\Models\OccurrenceQuery as OccurrenceQuery;
use \WSAL\MainWPExtension\Adapters\MySQL\Meta as Meta;
use \WSAL\MainWPExtension\Adapters\MySQL\Occurrence as Occurrence;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Post status filter class.
 */
class Filter_Post_Status extends Abstract_Filter {

	/**
	 * Get name.
	 */
	public function get_name() {
		return esc_html__( 'Post Status', 'mwp-al-ext' );
	}

	/**
	 * Get prefixes.
	 */
	public function get_prefixes() {
		return array( 'poststatus' );
	}

	/**
	 * Get widgets.
	 */
	public function get_widgets() {
		// Intialize post status widget class.
		$widget = new Widget_Select_Single( 'poststatus', esc_html__( 'Post Status', 'mwp-al-ext' ), __( 'Select a Post Status to filter by' ) );

		// Add select options to widget.
		foreach ( array( 'draft', 'future', 'pending', 'private', 'publish' ) as $status ) {
			$text = 'publish' === $status ? 'published' : $status;
			$widget->add( ucwords( $text ), $status );
		}

		return array( $widget );
	}

	/**
	 * Allow this filter to change the DB query according to the search value.
	 *
	 * @param OccurrenceQuery $query  - Database query for selecting occurrences.
	 * @param string          $prefix - The filter name (filter string prefix).
	 * @param array           $value  - The filter value.
	 * @throws \Exception Thrown when filter is unsupported.
	 */
	public function modify_query( $query, $prefix, $value ) {
		// Get DB connection array.
		$connection = MWPAL_Extension\mwpal_extension()->get_connector()->getAdapter( 'Occurrence' )->get_connection();
		$connection->set_charset( $connection->dbh, 'utf8mb4', 'utf8mb4_general_ci' );

		// Tables.
		$meta       = new Meta( $connection );
		$table_meta = $meta->GetTable(); // Metadata.
		$occurrence = new Occurrence( $connection );
		$table_occ  = $occurrence->GetTable(); // Occurrences.

		// Post status search condition.
		$sql = "$table_occ.id IN ( SELECT occurrence_id FROM $table_meta as meta WHERE meta.name='PostStatus' AND ( ";

		// Get the last post status.
		$last_status = end( $value );

		foreach ( $value as $post_status ) {
			if ( $last_status === $post_status ) {
				continue;
			} else {
				$sql .= "meta.value='$post_status' OR ";
			}
		}

		// Add placeholder for the last post status.
		$sql .= "meta.value='%s' ) )";

		// Check prefix.
		switch ( $prefix ) {
			case 'poststatus':
				$query->addORCondition( array( $sql => $last_status ) );
				break;
			default:
				/* Translators: %s: Filter prefix. */
				throw new \Exception( sprintf( __( 'Unsupported filter %s.', 'mwp-al-ext' ), $prefix ) );
		}
	}
}
