<?php
/**
 * Dashboard admin controller.
 *
 * @package Awesomemotive\Rewardswp\Controllers\Admin
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Controllers\Admin;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Awesomemotive\Rewardswp\Interfaces\ControllerInterface;
use Awesomemotive\Rewardswp\Factories\ViewsFactory;
use Awesomemotive\Rewardswp\Services\AssetsService;
use Awesomemotive\Rewardswp\Services\DashboardService;
use Awesomemotive\Rewardswp\Views\Admin\SetupView;
use Awesomemotive\Rewardswp\Settings\Options\Referrals\EnabledOption as ReferralsEnabledOption;
use Awesomemotive\Rewardswp\Settings\Options\Points\PointsEnabledOption;
use function Awesomemotive\Rewardswp\Helpers\get_option_value;
use function Awesomemotive\Rewardswp\Helpers\get_rewardswp_setup_template;


/**
 * Dashboard Admin Controller.
 *
 * @since 1.0.0
 */
class DashboardAdminController implements ControllerInterface {

	/**
	 * Summary of MENU_SLUG
	 *
	 * @var string
	 */
	const MENU_SLUG = 'rewardswp';

	/**
	 * Summary of views_factory
	 *
	 * @var ViewsFactory
	 */
	private ViewsFactory $views_factory;
	/**
	 * Summary of assets_service
	 *
	 * @var AssetsService
	 */
	private AssetsService $assets_service;
	/**
	 * Summary of dashboard_service
	 *
	 * @var DashboardService
	 */
	private DashboardService $dashboard_service;

	/**
	 * Constructor.
	 *
	 * @param ViewsFactory     $views_factory Views factory.
	 * @param AssetsService    $assets_service Assets service.
	 * @param DashboardService $dashboard_service Dashboard service.
	 */
	public function __construct(
		ViewsFactory $views_factory,
		AssetsService $assets_service,
		DashboardService $dashboard_service
	) {
		$this->views_factory     = $views_factory;
		$this->assets_service    = $assets_service;
		$this->dashboard_service = $dashboard_service;
	}

	/**
	 * Returns the page title.
	 *
	 * @since 1.0.0
	 *
	 * @return string Page title.
	 */
	public function get_page_title(): string {
		return esc_html__( 'Dashboard', 'rewardswp' );
	}

	/**
	 * Initializes the controller.
	 *
	 * @since 1.0.0
	 *
	 * @return void Initializes the controller.
	 */
	public function init() {
		add_action( 'admin_enqueue_scripts', [ $this, 'maybe_enqueue_dashboard_assets' ] );
		add_action( 'wp_ajax_rewardswp_dismiss_checklist', [ $this, 'handle_ajax_dismiss_checklist' ] );
		add_action( 'wp_ajax_rewardswp_show_checklist', [ $this, 'handle_ajax_show_checklist' ] );
		add_action( 'wp_ajax_rewardswp_mark_widget_explored', [ $this, 'handle_ajax_mark_widget_explored' ] );
	}

	/**
	 * Renders the dashboard page.
	 *
	 * @since 1.0.0
	 *
	 * @return void Renders the dashboard page.
	 */
	public function render_page() {
		// Get KPI definitions and data from service.
		$kpi_definitions = $this->dashboard_service->get_kpi_definitions();
		$date_ranges     = $this->dashboard_service->get_date_ranges();
		$default_range   = 'last_30_days';

		// Get KPI data for each range to pass to view.
		$kpi_data_by_range = [];
		foreach ( array_keys( $date_ranges ) as $range_key ) {
			$kpi_data_by_range[ $range_key ] = $this->dashboard_service->get_kpi_data( $range_key );
		}

		$data_for_view = [
			'kpi_definitions'    => $kpi_definitions,
			'date_ranges'        => $date_ranges,
			'default_range'      => $default_range,
			'kpi_cards_by_range' => $kpi_data_by_range,
		];

		$view = $this->views_factory->get_view( \Awesomemotive\Rewardswp\Views\Admin\DashboardAdminView::class );
		if ( method_exists( $view, 'render' ) ) {
			$view->render( $data_for_view );
		}

		// Render setup wizard dialog over the dashboard when requested (only once).
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only display check, no data modification.
		if ( isset( $_GET['setup'] ) && '1' === $_GET['setup'] ) {
			$option_name = sprintf( 'rewardswp_%s_setup_initiated', get_rewardswp_setup_template() );

			// Only show the wizard if it hasn't been initiated before.
			if ( false === get_option( $option_name, false ) ) {
				add_option( $option_name, time(), '', false );

				$setup_view = $this->views_factory->get_view( SetupView::class );
				if ( method_exists( $setup_view, 'render' ) ) {
					$setup_view->render();
				}
			}
		}
	}

	/**
	 * Conditionally enqueues assets for the dashboard page.
	 * Hooked to admin_enqueue_scripts.
	 *
	 * @since 1.0.0
	 *
	 * @param string $hook_suffix The hook suffix.
	 *
	 * @return void Conditionally enqueues assets for the dashboard page.
	 */
	public function maybe_enqueue_dashboard_assets( $hook_suffix ) {
		if ( 'toplevel_page_' . self::MENU_SLUG === $hook_suffix ) {
			$this->enqueue_dashboard_assets();
		}
	}

	/**
	 * Enqueues the actual assets for the dashboard.
	 * Called by enqueue_dashboard_assets_conditionally.
	 */
	private function enqueue_dashboard_assets() {

		// Localize checklist data.
		$checklist_tasks     = $this->get_checklist_tasks();
		$checklist_dismissed = get_user_meta( get_current_user_id(), 'rewardswp_setup_tasks_dismissed', true );

		wp_localize_script(
			AssetsService::ADMIN_SCRIPT_HANDLE,
			'rewardsWP',
			[
				'nonce'              => wp_create_nonce( 'rewardswp-nonce' ),
				'checklistTasks'     => $checklist_tasks,
				'checklistDismissed' => (bool) $checklist_dismissed,
				'settingsUrl'        => admin_url( 'admin.php?page=rewardswp-settings' ),
			]
		);
	}

	/**
	 * Handles AJAX request to dismiss the checklist.
	 */
	public function handle_ajax_dismiss_checklist() {
		check_ajax_referer( 'rewardswp-nonce', '_ajax_nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Permission denied.', 'rewardswp' ) ], 403 );
		}

		update_user_meta( get_current_user_id(), 'rewardswp_setup_tasks_dismissed', true );

		wp_send_json_success( [ 'message' => esc_html__( 'Checklist dismissed successfully.', 'rewardswp' ) ] );
	}

	/**
	 * Handles AJAX request to show the checklist again.
	 */
	public function handle_ajax_show_checklist() {
		check_ajax_referer( 'rewardswp-nonce', '_ajax_nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Permission denied.', 'rewardswp' ) ], 403 );
		}

		delete_user_meta( get_current_user_id(), 'rewardswp_setup_tasks_dismissed' );

		wp_send_json_success( [ 'message' => esc_html__( 'Checklist restored successfully.', 'rewardswp' ) ] );
	}

	/**
	 * Handles AJAX request to mark widget settings as explored.
	 */
	public function handle_ajax_mark_widget_explored() {
		check_ajax_referer( 'rewardswp-nonce', '_ajax_nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Permission denied.', 'rewardswp' ) ], 403 );
		}

		$completed_tasks = get_option( 'rewardswp_setup_tasks_completed', [] );
		if ( ! is_array( $completed_tasks ) ) {
			$completed_tasks = [];
		}

		if ( ! in_array( 'explore_widget_settings', $completed_tasks, true ) ) {
			$completed_tasks[] = 'explore_widget_settings';
			update_option( 'rewardswp_setup_tasks_completed', $completed_tasks );
		}

		wp_send_json_success();
	}

	/**
	 * Gets the checklist tasks with their current status.
	 *
	 * @return array Array of checklist tasks.
	 */
	private function get_checklist_tasks() {
		// Get completed tasks from options (tasks that have been done at least once).
		$completed_tasks = get_option( 'rewardswp_setup_tasks_completed', [] );
		if ( ! is_array( $completed_tasks ) ) {
			$completed_tasks = [];
		}

		// Check current program states.
		$points_enabled    = (bool) get_option_value( PointsEnabledOption::class );
		$referrals_enabled = (bool) get_option_value( ReferralsEnabledOption::class );

		// Mark tasks as complete if they're configured now (one-time completion).
		$tasks_updated = false;

		if ( $points_enabled && ! in_array( 'enable_points_program', $completed_tasks, true ) ) {
			$completed_tasks[] = 'enable_points_program';
			$tasks_updated     = true;
		}

		if ( $referrals_enabled && ! in_array( 'enable_referral_program', $completed_tasks, true ) ) {
			$completed_tasks[] = 'enable_referral_program';
			$tasks_updated     = true;
		}

		// Update option only if there were changes.
		if ( $tasks_updated ) {
			update_option( 'rewardswp_setup_tasks_completed', $completed_tasks );
		}

		$tasks = [
			[
				'id'          => 'enable_points_program',
				'title'       => __( 'Enable your points program', 'rewardswp' ),
				'description' => __( 'Let customers earn and redeem points for purchases', 'rewardswp' ),
				'status'      => in_array( 'enable_points_program', $completed_tasks, true ) ? 'complete' : 'incomplete',
				'action'      => [
					'label' => __( 'Review & Enable', 'rewardswp' ),
					'url'   => admin_url( 'admin.php?page=rewardswp-settings&tab=points#points-status' ),
				],
			],
			[
				'id'          => 'enable_referral_program',
				'title'       => __( 'Enable your referral program', 'rewardswp' ),
				'description' => __( 'Review rewards and activate your referral program', 'rewardswp' ),
				'status'      => in_array( 'enable_referral_program', $completed_tasks, true ) ? 'complete' : 'incomplete',
				'action'      => [
					'label' => __( 'Review & Enable', 'rewardswp' ),
					'url'   => admin_url( 'admin.php?page=rewardswp-settings&tab=referrals#program-status' ),
				],
			],
			[
				'id'          => 'explore_widget_settings',
				'title'       => __( 'Explore the rewards widget', 'rewardswp' ),
				'description' => __( 'Customize the launcher button, position, and more to match your brand', 'rewardswp' ),
				'status'      => in_array( 'explore_widget_settings', $completed_tasks, true ) ? 'complete' : 'incomplete',
				'action'      => [
					'label' => __( 'Explore Settings', 'rewardswp' ),
					'url'   => admin_url( 'admin.php?page=rewardswp-settings&tab=rewards_widget' ),
				],
			],
		];

		return $tasks;
	}

	/**
	 * Resets the checklist (useful for testing or re-onboarding).
	 * Can be called via: wp eval "( new \Awesomemotive\Rewardswp\Controllers\Admin\DashboardAdminController() )->reset_checklist();"
	 */
	public function reset_checklist() {
		delete_option( 'rewardswp_setup_tasks_completed' );
		delete_user_meta( get_current_user_id(), 'rewardswp_setup_tasks_dismissed' );
		return true;
	}
}
