<?php
/**
 * Rivio AI Cart Recovery & Marketing Email Automation Admin Controller.
 *
 * This class handles all admin-related functionality for the Pixelio Cart Abandon
 * Recovery plugin, including menu registration, page rendering, asset enqueues,
 * admin notices, update checks, and plugin action/meta links.
 *
 * @package PixelioCartAbandonRecoveryMore\Admin\Controllers
 * @since 1.0.0
 */

namespace PixelioCartAbandonRecoveryMore\Admin\Controllers;

use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Enqueuer_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Link_Builder_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Notice_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Submenu_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Update_Service;
use PixelioCartAbandonRecoveryMore\Admin\Views\Pixelio_Cart_Abandon_Recovery_More_Dashboard_Page;
use PixelioCartAbandonRecoveryMore\Admin\Views\Pixelio_Cart_Abandon_Recovery_More_First_Config_Page;
use PixelioCartAbandonRecoveryMore\Admin\Views\Pixelio_Cart_Abandon_Recovery_More_Update_Renderer;
use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

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

/**
 * Rivio AI Cart Recovery & Marketing Email Automation Admin Controller.
 *
 * This class handles all admin-related functionality for the Pixelio Cart Abandon
 * Recovery plugin, including menu registration, page rendering, asset enqueues,
 * admin notices, update checks, and plugin action/meta links.
 *
 * @package PixelioCartAbandonRecoveryMore\Admin\Controllers
 * @since 1.0.0
 */
class Pixelio_Cart_Abandon_Recovery_More_Admin_Controller
{


	/**
	 * Submenu pages array.
	 *
	 * @var array
	 */
	private $submenu;
	private Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util;
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper;
	private Pixelio_Cart_Abandon_Recovery_More_Update_Service $pixelio_update_service;
	private Pixelio_Cart_Abandon_Recovery_More_Update_Renderer $pixelio_update_popup_renderer;
	private Pixelio_Cart_Abandon_Recovery_More_Notice_Service $pixelio_notice;

	/**
	 * Constructor.
	 *
	 * Initializes hooks, menu pages, filters, admin notices, and update checks.
	 */
	public function __construct(Pixelio_Cart_Abandon_Recovery_More_Util              $pixelio_util,
								Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper,
								Pixelio_Cart_Abandon_Recovery_More_Update_Service    $pixelio_update_service,
								Pixelio_Cart_Abandon_Recovery_More_Update_Renderer   $pixelio_update_popup_renderer,
								Pixelio_Cart_Abandon_Recovery_More_Notice_Service    $pixelio_notice)
	{
		$this->pixelio_util = $pixelio_util;
		$this->pixelio_wordpress_wrapper = $pixelio_wordpress_wrapper;
		$this->pixelio_update_service = $pixelio_update_service;
		$this->pixelio_update_popup_renderer = $pixelio_update_popup_renderer;
		$this->pixelio_notice = $pixelio_notice;

		$this->pixelio_wordpress_wrapper->pixelio_add_action('admin_menu', array($this, 'pixelio_cart_abandon_recovery_more_add_abandon_menu'));
		$this->pixelio_wordpress_wrapper->pixelio_add_filter('plugin_action_links_' . Pixelio_Cart_Abandon_Recovery_More_Util::$plugin_base_name, array($this, 'pixelio_cart_abandon_recovery_more_action_links'));
		$this->pixelio_wordpress_wrapper->pixelio_add_filter('plugin_row_meta', array($this, 'pixelio_cart_abandon_recovery_more_meta_links'),10,2);
		$this->pixelio_wordpress_wrapper->pixelio_add_action('admin_notices', array($this, 'pixelio_cart_abandon_recovery_more_if_plugins_are_or_not_active'));
		$this->pixelio_cart_abandon_recovery_more_check_update();
		$this->pixelio_cart_abandon_recovery_more_show_update_popup();
		$submenu_service = new Pixelio_Cart_Abandon_Recovery_More_Submenu_Service($this->pixelio_wordpress_wrapper);
		$this->submenu = $submenu_service->get_submenu();
		$this->pixelio_wordpress_wrapper->pixelio_add_action('admin_init', array($this, 'pixelio_cart_abandon_recovery_more_init'));
	}

	/**
	 * Checks for available plugin updates and sets internal flags.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_check_update(): void
	{
		$result = $this->pixelio_update_service->check_for_updates();

		Pixelio_Cart_Abandon_Recovery_More_Util::$update_available = $result->pixelio_is_available();
		Pixelio_Cart_Abandon_Recovery_More_Util::$force_update = $result->pixelio_is_forced();
		Pixelio_Cart_Abandon_Recovery_More_Util::$changelog = $result->pixelio_get_changelog();
	}

	/**
	 * Displays update popup on admin pages when update is available.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_show_update_popup(): void
	{
		$page = $this->pixelio_wordpress_wrapper->pixelio_get_current_admin_page();
		if (!$page || !str_contains($page, 'rivio-ai-cart-recovery')) {
			return;
		}

		echo $this->pixelio_wordpress_wrapper->pixelio_wp_kses($this->pixelio_update_popup_renderer->render(), Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_cart_abandon_recovery_more_allowed_html);
	}


	/**
	 * Displays first configuration page.
	 *
	 * @return void
	 */
	public function pixelio_first_config_page(): void
	{
		$this->pixelio_cart_abandon_recovery_more_admin_enqueue_script();
		$first_config_page = new Pixelio_Cart_Abandon_Recovery_More_First_Config_Page();

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Safe: all output is already sanitized in the generated HTML (admin-only view).
		echo $this->pixelio_wordpress_wrapper->pixelio_wp_kses($first_config_page->pixelio_cart_abandon_recovery_more_get_views(), Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_cart_abandon_recovery_more_allowed_html);
	}


	/**
	 * Enqueues all necessary CSS & JS for admin pages.
	 *
	 * @param bool $is_dashboard Include chart.js assets for dashboard pages.
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_admin_enqueue_script(bool $is_dashboard = false): void
	{

		$enqueue_service = new Pixelio_Cart_Abandon_Recovery_More_Enqueuer_Service($this->pixelio_util, $this->pixelio_wordpress_wrapper);
		$enqueue_service->enqueue_common_styles();

		if (!isset($_GET['page'])) {
			return;
		}

		$page = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
			$this->pixelio_wordpress_wrapper->pixelio_wp_unslash($_GET['page'])
		);

		if ($is_dashboard) {
			$enqueue_service->enqueue_dashboard_scripts();
		}

		switch (true) {
			case str_contains($page, 'integrations'):
				$enqueue_service->enqueue_integrations_scripts();
				break;

			case str_contains($page, 'faq'):
				$enqueue_service->enqueue_faq_scripts();
				break;
			case str_contains($page, 'rgpd'):
				$enqueue_service->enqueue_rgpd_scripts();
				break;
			case str_contains($page, 'settings'):
				$enqueue_service->enqueue_settings_scripts();
				break;
			case str_contains($page, 'first'):
				$enqueue_service->enqueue_first_config_scripts();
				break;
			case str_contains($page, 'email'):
				$enqueue_service->enqueue_email_scripts();
				break;
		}

		$enqueue_service->enqueue_header_script();

		if (!str_contains($page, 'first-config')) {
			$this->pixelio_wordpress_wrapper->pixelio_delete_option('pixelio-first-config-temporary');
		}
	}

	/**
	 * Initializes plugin after activation (redirect if first install).
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_init(): void
	{
		$this->pixelio_notice->pixelio_cart_abandon_recovery_more_init();
	}


	/**
	 * Displays admin notice if WooCommerce or caching plugins are not active.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_if_plugins_are_or_not_active(): void
	{
		if (!class_exists('WooCommerce')) {
			echo $this->pixelio_wordpress_wrapper->pixelio_esc_html('<div class="notice notice-warning is-dismissible">');
			echo $this->pixelio_wordpress_wrapper->pixelio_esc_html('<p>') . $this->pixelio_wordpress_wrapper->pixelio_esc_html('Woocommerce is not active, this plugin may not work correctly.') . $this->pixelio_wordpress_wrapper->pixelio_esc_html('</p>');
			echo $this->pixelio_wordpress_wrapper->pixelio_esc_html('</div>');
		}
		$this->pixelio_cart_abandon_recovery_more_show_cache_notice();
	}

	/**
	 * Displays admin notice if caching plugins are active.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_show_cache_notice(): void
	{
		if ($this->pixelio_wordpress_wrapper->pixelio_is_plugin_active('wp-super-cache/wp-cache.php') || $this->pixelio_wordpress_wrapper->pixelio_is_plugin_active('w3-total-cache/w3-total-cache.php') || $this->pixelio_wordpress_wrapper->pixelio_is_plugin_active('jetpack/jetpack.php')) {
			?>
			<div class="notice notice-warning is-dismissible">
				<p><?php $this->pixelio_wordpress_wrapper->pixelio_esc_html_e('It seems that you are using a caching plugin which can cause some troubleshooting with the Rivio – Cart Recovery & AI Emails . We will implement a solution to this in the future version. Thank you for your understanding.', 'rivio-ai-cart-recovery-marketing-email-automation'); ?></p>
			</div>
			<?php
		}
	}

	/**
	 * Adds documentation and support links to the plugin row meta.
	 *
	 * @param array $links Array of existing links.
	 * @param string $file Plugin base file.
	 * @return array Updated array of links.
	 */
	public function pixelio_cart_abandon_recovery_more_meta_links($links, $file): array
	{
		if (Pixelio_Cart_Abandon_Recovery_More_Util::$plugin_base_name === $file) {
			$link_builder = new Pixelio_Cart_Abandon_Recovery_More_Link_Builder_Service($this->pixelio_wordpress_wrapper);
			$links[] = $link_builder->build_plugin_link('https://www.rivio.be', 'Documentation', true);
			$links[] = $link_builder->build_plugin_link('admin.php?page=pixelio-cart-abandon-recovery-more-faq', 'Support');
		}
		return $links;
	}

	/**
	 * Adds settings and dashboard links in the plugin action links.
	 *
	 * @param array $links Current plugin action links.
	 * @return array Updated plugin action links.
	 */
	public function pixelio_cart_abandon_recovery_more_action_links($links): array
	{
		$settings_link = '<a href="' . $this->pixelio_wordpress_wrapper->pixelio_admin_url('admin.php?page=' . Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_slug . '-settings') . '">' . $this->pixelio_wordpress_wrapper->pixelio_translate('Settings', 'rivio-ai-cart-recovery-marketing-email-automation') . '</a>';
		$dashboard_link = '<a href="' . $this->pixelio_wordpress_wrapper->pixelio_admin_url('admin.php?page=' . Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_slug) . '">' . $this->pixelio_wordpress_wrapper->pixelio_translate('Dashboard', 'rivio-ai-cart-recovery-marketing-email-automation') . '</a>';
		array_push($links, $dashboard_link, $settings_link);
		return $links;
	}


	/**
	 * Registers the main plugin menu and all submenu pages.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_add_abandon_menu(): void
	{

		add_menu_page(
			$this->pixelio_wordpress_wrapper->pixelio_translate('Rivio - Dashboard', 'rivio-ai-cart-recovery-marketing-email-automation'),
			$this->pixelio_wordpress_wrapper->pixelio_translate('Rivio - Dashboard', 'rivio-ai-cart-recovery-marketing-email-automation'),
			'manage_options',
			Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_slug,
			array($this, 'pixelio_cart_abandon_recovery_more_admin_dashboard_page'),
			$this->pixelio_wordpress_wrapper->pixelio_plugins_url('../assets/img/pixelio-cart-abandon-recovery-more-logo-white-36px.svg', __FILE__),
			68
		);

		$configured = $this->pixelio_wordpress_wrapper->pixelio_esc_html(get_option('pixelio_first_config_done', false));
		$temp = $this->pixelio_wordpress_wrapper->pixelio_esc_html(get_option('pixelio-first-config-temporary', false));
		if (!$configured || '1' === $temp) {

			add_submenu_page(
				Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_slug,
				'First configuration',
				'First configuration',
				'manage_options',
				'rivio-first-config',
				array($this, 'pixelio_first_config_page'),
			);
		}
		foreach ($this->submenu as $key => $value) {
			add_submenu_page(
				Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_slug,
				$value['page_title'],
				$value['menu_title'],
				'manage_options',
				$value['menu_slug'],
				array($this, $value['callback'])
			);
		}
	}

	/**
	 * Displays the main admin dashboard page.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_admin_dashboard_page(): void
	{

		$this->pixelio_cart_abandon_recovery_more_admin_enqueue_script(true);
		$views = new Pixelio_Cart_Abandon_Recovery_More_Dashboard_Page();
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Safe: all output is already sanitized in the generated HTML (admin-only view).
		echo $this->pixelio_wordpress_wrapper->pixelio_wp_kses($views->pixelio_cart_abandon_recovery_more_get_views(), Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_cart_abandon_recovery_more_allowed_html);
	}

	/**
	 * Loads and renders the appropriate admin page view for the plugin.
	 *
	 * This method checks the current admin page slug (from the $_GET['page'] parameter)
	 * and matches it against the plugin's registered submenu pages. If a match is found,
	 * it enqueues the necessary CSS and JS assets for that page and renders the view.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_all_page(): void
	{
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- safe admin-only GET check for plugin page slug.
		if (isset($_GET['page'])) {
			foreach ($this->submenu as $key => $value) {
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- safe admin submenu to load correct js.
				if (sanitize_text_field(wp_unslash($_GET['page'])) === $value['menu_slug']) {
					$this->pixelio_cart_abandon_recovery_more_admin_enqueue_script();

					$views = new $value['class']();
					// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Safe: all output is already sanitized in the generated HTML (admin-only view).
					echo $this->pixelio_wordpress_wrapper->pixelio_wp_kses($views->pixelio_cart_abandon_recovery_more_get_views(), Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_cart_abandon_recovery_more_allowed_html);
				}
			}
		}
	}
}

