<?php

namespace GravityKit\GravityActions\Actions;

use function GravityKit\GravityActions\get_request_var;


use \GFAPI;
use \GFCommon;
use \GFFormsModel;
use \GF_Entry_List_Table;
use function GravityKit\GravityActions\is_truthy;

/**
 * Class ActionAbstract
 *
 * @since 1.0
 *
 * @package GravityKit\GravityActions\Actions
 */
abstract class ActionAbstract implements ActionInterface {
	/**
	 * {@inheritDoc}
	 */
	public function register() {
		$this->hook();
	}

	/**
	 * {@inheritDoc}
	 */
	public function hook() {
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ], 15 );
	}

	/**
	 * {@inheritDoc}
	 */
	public function prepare_template_vars( array $template_vars = [] ) {
		$template_vars['reload_window'] = true;
		$template_vars['is_all_entries'] = is_truthy( get_request_var( 'is_all_entries', false ) );
		$template_vars['current_query_args'] = wp_parse_args( get_request_var( 'current_query_args', [] ) );

		if ( ! $template_vars['is_all_entries'] ) {
			return $template_vars;
		}

		$entries = $this->get_all_entries( $template_vars['form_id'] );
		if ( ! empty( $entries ) ) {
			$template_vars['entries'] = $entries;
		}

		return $template_vars;
	}

	/**
	 * {@inheritDoc}
	 */
	public function validate_modal_request( array $template_vars = [] ) {
		return true;
	}

	/**
	 * Specifically to find all the Items based on the search criteria passed, this method looks around quite a bit, so
	 * we should avoid using it anywhere else other than the current usage unless we abstract the code a little further,
	 * so we can pass the search criteria.
	 *
	 * @since 1.3
	 *
	 * @param int $form_id
	 *
	 * @return array
	 */
	protected function get_all_entries( $form_id ) {
		if ( ! class_exists( 'GF_Entry_List_Table' ) ) {
			require_once( GFCommon::get_base_path() . '/entry_list.php' );
		}

		// All of the hacking below is to avoid having to duplicate code from GF around the search.
		$GLOBALS['hook_suffix'] = 'forms_page_gf_entries';
		set_current_screen( 'forms_page_gf_entries' );

		$query_args = wp_parse_args( get_request_var( 'current_query_args', [] ) );

		// Set the GET vars.
		$_GET = $query_args;

		$form            = GFFormsModel::get_form_meta( $form_id );
		$table           = new GF_Entry_List_Table( [ 'form_id' => $form_id, 'form' => $form ] );
		$search_criteria = $table->get_search_criteria();

		return GFAPI::get_entry_ids( $form_id, $search_criteria );
	}
}