<?php

namespace HulkPlugins\Woo\AccountPages\Admin\Controllers;

use HulkPlugins\Woo\AccountPages\Admin\Services\AccountPagesService;
use HulkPlugins\Woo\AccountPages\Core\BaseController;
use HulkPlugins\Woo\AccountPages\Core\SingletonTrait;
use function HulkPlugins\Woo\AccountPages\hulk_woo_ap_fs;
use const HulkPlugins\Woo\AccountPages\DOCUMENTATION;
use const HulkPlugins\Woo\AccountPages\SUPPORT;

defined( 'ABSPATH' ) || exit;

class PluginController extends BaseController {

    use SingletonTrait;

	public function init_hooks(): void {
		add_filter( 'plugin_row_meta', [ $this, 'plugin_row_meta' ], 10, 2 );
		add_action( 'activated_plugin', [ $this, 'activated' ] );
		hulk_woo_ap_fs()->add_action( 'after_uninstall', [ $this, 'after_uninstall' ] );
	}

	/**
	 * Add plugin meta
	 *
	 * @param $links
	 * @param $file
	 *
	 * @return array|mixed
	 */
	public function plugin_row_meta( $links, $file ) {

		if ( strpos( $file, 'hulk-account-pages-for-woocommerce.php' ) !== false ) {

			$row_meta['docs'] = sprintf(
			/** @lang text */                '<a target="_blank" href="%1$s">%2$s</a>',
				esc_url( DOCUMENTATION ),
				esc_html__( 'Docs', 'hulk-account-pages-for-woocommerce' )
			);

			$row_meta['settings'] = sprintf(
			/** @lang text */                '<a href="%1$s">%2$s</a>',
				admin_url( 'edit.php?post_type=hulk_woo_ap_page' ),
				esc_html__( 'Settings', 'hulk-account-pages-for-woocommerce' )
			);

			$row_meta['support'] = sprintf(
			/** @lang text */                '<a target="_blank" href="%1$s">%2$s</a>',
				esc_url( SUPPORT ),
				esc_html__( 'Help &amp; Support', 'hulk-account-pages-for-woocommerce' )
			);

			$links = array_merge( $links, $row_meta );
		}

		return $links;
	}

	/**
	 * Hooked into the 'activated_plugin' action to redirect to the settings page when the plugin is activated.
	 *
	 * @param $plugin `The path to the plugin file relative to the plugins directory.`
	 */
	public function activated( $plugin ): void {
		if ( $plugin === 'hulk-account-pages-for-woocommerce/hulk-account-pages-for-woocommerce.php' ) {

			// Redirect to settings page
			$settingsPageUrl = add_query_arg(
				[
					'post_type' => 'hulk_woo_ap_page',
				],
				admin_url( 'edit.php' )
			);

			wp_safe_redirect( $settingsPageUrl );
			exit();
		}
	}

	/**
	 * Set the activation hook for a plugin.
	 * @return void
	 */
	public static function activate(): void {

		// Refresh permalinks
		update_option( 'hulk_woo_ap_needs_flush', 1 );
	}

	/**
	 * Clean up logic goes here
	 */
	public function after_uninstall(): void {
		$accountPageService = AccountPagesService::getInstance();
		$accountPageService->delete_all_posts( true );
		delete_option( 'hulk_woo_ap_needs_flush' );
	}
}
