<?php

namespace HulkPlugins\Woo\ProductConditionManager;

use HulkPlugins\Woo\ProductConditionManager\Models\ProductModel;
use HulkPlugins\Woo\ProductConditionManager\Models\SettingsModel;
use HulkPlugins\Woo\ProductConditionManager\Traits\SingletonTrait;

defined( 'ABSPATH' ) || exit;

class Base {
	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_pcm_fs()->add_action( 'after_uninstall', [ $this, 'uninstall' ] );
	}

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

		if ( strpos( $file, 'product-condition-manager-for-woocommerce.php' ) !== false ) {

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

			$row_meta['settings'] = sprintf(
			/** @lang text */                '<a href="%1$s">%2$s</a>',
				admin_url( 'admin.php?page=wc-settings&tab=products&section=hulk_woo_pcm' ),
				esc_html__( 'Settings', 'product-condition-manager-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-condition-manager-for-woocommerce/product-condition-manager-for-woocommerce.php' ) {

			// Redirect to settings page
			$settingsPageUrl = add_query_arg(
				[
					'page'    => 'wc-settings',
					'tab'     => 'products',
					'section' => 'hulk_woo_pcm',
				],
				admin_url( 'admin.php' )
			);

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

	/**
	 * Freemius uninstall hook
	 * @return void
	 */
	public function uninstall(): void {

		// Cleanup
		SettingsModel::getInstance()->deleteSettings();
		ProductModel::getInstance()->deleteAllMeta();
	}
}
