<?php
/**
 * Defines Activities page functionality
 *
 * @link https://personalizewp.com/
 * @since 3.3.0
 *
 * @package PersonalizeWP
 * @subpackage PersonalizeWP/Admin
 */

namespace PersonalizeWP\Admin;

use PersonalizeWP\Admin\Admin_Base_Page;
use PersonalizeWP\Model\Activity;

defined( 'ABSPATH' ) || exit; // Exit if accessed directly.

/**
 * Defines Activities page functionality
 */
class PageActivities extends Admin_Base_Page {

	/**
	 * Slug for activities admin page
	 */
	const SLUG = 'personalizewp/recent-events';

	/**
	 * URL for main activities admin page (listing)
	 *
	 * @var string
	 */
	public static $index_url = 'admin.php?page=' . self::SLUG;

	/**
	 * URL for deleting an activity
	 *
	 * @var string
	 */
	public static $delete_activity_url = 'admin.php?page=' . self::SLUG . '&' . Admin::URL_ACTION . '=delete-activity&id=';

	/**
	 * Store the path for Activities templates
	 *
	 * @var string
	 */
	public $template_path;

	/**
	 * Used to store the current page from the URL, shared between process/route actions
	 *
	 * @var string
	 */
	protected $current_page;

	/**
	 * Constructor
	 */
	protected function __construct() {
		parent::__construct();

		$this->page_title    = __( 'Recent Events', 'personalizewp' );
		$this->template_path = plugin_dir_path( __DIR__ ) . 'admin/partials/activities/';

		$this->current_action = isset( $_REQUEST[ Admin::URL_ACTION ] ) ? sanitize_text_field( wp_unslash( $_REQUEST[ Admin::URL_ACTION ] ) ) : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$this->current_page   = isset( $_REQUEST['page'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['page'] ) ) : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reason: verified elsewhere

		add_action( 'admin_init', [ $this, 'process' ] );
		add_filter( 'set-screen-option', [ $this, 'set_screen_options' ], 10, 3 );
	}

	/**
	 * Display the Dashboard screen options.
	 */
	public function dashboard_screen_options() {
		$screen = get_current_screen();

		$is_screen = is_object( $screen ) && str_ends_with( $screen->id, self::SLUG );
		if ( ! $is_screen ) {
			return;
		}
		// Re-trigger core WP, as admins' call runs way too early IMHO.
		set_screen_options();

		$args = array(
			'label'   => __( 'Number of Recent Events per page (max 200):', 'personalizewp' ),
			'default' => 20,
			'option'  => 'edit_pwp_recent_events_per_page',
		);
		add_screen_option( 'per_page', $args );
	}

	/**
	 * Store the screen options.
	 *
	 * @param mixed  $screen_option The value to save instead of the option value.
	 *                              Default false (to skip saving the current option).
	 * @param string $option        The option name.
	 * @param int    $value         The option value.
	 */
	public function set_screen_options( $screen_option, $option, $value ) {
		if ( 'edit_pwp_recent_events_per_page' === $option ) {
			// Enforce maximum of 200 recent events
			return min( max( (int) $value, 1 ), 200 );
		}
		return $screen_option;
	}

	/**
	 * Process the current Activities request, typically POST/GET, followed by a redirect.
	 *
	 * @return void
	 */
	public function process() {
		// Double check for user caps before any possible processing of data.
		if ( ! current_user_can( Admin::CAP ) ) {
			return;
		}

		if ( self::SLUG !== $this->current_page ) {
			return;
		}

		$item_id = (int) isset( $_REQUEST['id'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['id'] ) ) : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reason: used as intval

		switch ( $this->current_action ) {
			case 'delete-activity':
				if ( empty( $item_id ) ) {
					wp_safe_redirect( admin_url( self::$index_url ) );
					exit;
				}
				check_admin_referer( 'delete-activity-' . $item_id ); // Immediately dies on failing.
				$this->delete_activity_action( $item_id );
				break;
		}
	}

	/**
	 * Route to the correct screen
	 *
	 * @return void
	 */
	public function route() {
		// Double check for user caps before any possible processing of data.
		if ( ! current_user_can( Admin::CAP ) ) {
			return;
		}

		if ( self::SLUG !== $this->current_page ) {
			return;
		}

		// Default to index screen (Recent Events)
		$this->index_screen();
	}

	/**
	 * Display Recent Events screen
	 *
	 * @return void
	 */
	protected function index_screen() {

		$status_message = '';
		// Trigger messaging from actions.
		if ( isset( $_REQUEST['deleted'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- this is only displaying a message with no dynamic values.
			$status_message = __( 'Activity deleted', 'personalizewp' );
		}
		if ( $status_message ) {
			wp_admin_notice(
				'<span class="dashicons dashicons-yes-alt"></span>' . $status_message,
				array(
					'type'        => 'success',
					'id'          => 'message',
					'dismissible' => true,
				)
			);
		}

		$this->display_header();

		// Display Recent Events content
		require_once $this->template_path . 'index.php';

		$this->display_footer();
	}

	/**
	 * Delete Activity entry
	 *
	 * @param int $activity_id Activity ID
	 *
	 * @return void
	 */
	protected function delete_activity_action( $activity_id ) {
		$activity = Activity::find( $activity_id );
		if ( ! $activity ) {
			// Nothing to do
			wp_safe_redirect( admin_url( self::$index_url ) );
			exit;
		}

		$contact_id = $activity->contact_id;
		Activity::delete( $activity_id );

		// Default redirect URL
		$redirect_url = add_query_arg( array( 'deleted' => 1 ), admin_url( self::$index_url ) );

		/**
		 * Filters the redirect URL after deleting an activity.
		 *
		 * @since 3.2.0
		 *
		 * @param string $redirect_url Default redirect URL (Recent Events).
		 * @param int    $activity_id  The deleted activity ID.
		 * @param int    $contact_id   The contact ID associated with the activity.
		 */
		$redirect_url = apply_filters( 'personalizewp_activity_delete_redirect', $redirect_url, $activity_id, $contact_id );

		wp_safe_redirect( $redirect_url );
		exit;
	}

	/**
	 * Converts Activity type string into translated string.
	 *
	 * @param string $type Activity Type
	 *
	 * @return string
	 */
	public static function translate_activity_type( $type ) {

		// Assume unknown
		$label = __( 'Unknown', 'personalizewp' );

		// Check against all registered events.
		$all_event_types = personalizewp()->get_registered_event_types();
		if ( isset( $all_event_types[ $type ] ) ) {
			$label = $all_event_types[ $type ]['label'];
		}

		/**
		 * Filters the Activity type label, shown when listing activities
		 *
		 * @param string $label  Processed label
		 * @param string $type   Activity type
		 */
		return apply_filters( 'personalizewp_activity_type_label', $label, $type );
	}
}
