<?php

namespace HulkPlugins\Woo\ProductDescriptionInLoop\Admin\Controllers;

use HulkPlugins\Woo\ProductDescriptionInLoop\Core\BaseController;
use HulkPlugins\Woo\ProductDescriptionInLoop\Core\SingletonTrait;
use function HulkPlugins\Woo\ProductDescriptionInLoop\hulk_woo_pdil_fs;
use const HulkPlugins\Woo\ProductDescriptionInLoop\DOCUMENTATION;
use const HulkPlugins\Woo\ProductDescriptionInLoop\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_pdil_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, 'product-description-in-loop-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', 'product-description-in-loop-for-woocommerce' )
			);

			$row_meta['settings'] = sprintf(
			/** @lang text */                '<a href="%1$s">%2$s</a>',
				admin_url( 'admin.php?page=hulk_woo_pdil_settings' ),
				esc_html__( 'Settings', 'product-description-in-loop-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', 'product-description-in-loop-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 === 'product-description-in-loop-for-woocommerce/product-description-in-loop-for-woocommerce.php' ) {

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

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

	/**
	 * Clean up logic goes here
	 */
	public function after_uninstall(): void {
		delete_option( 'hulk_woo_pdil_enabled_pages' );
		delete_option( 'hulk_woo_pdil_description_position' );
		delete_option( 'hulk_woo_pdil_description_content' );
		delete_option( 'hulk_woo_pdil_word_limit' );
		delete_option( 'hulk_woo_pdil_enable_style' );
		delete_option( 'hulk_woo_pdil_text_align' );
		delete_option( 'hulk_woo_pdil_font_size' );
		delete_option( 'hulk_woo_pdil_text_color' );
		delete_post_meta_by_key( 'hulk_woo_pdil_loop_desc' );
	}
}
