<?php
/**
 * Main Plugin Class
 *
 * @package VendorTasksDokanClickUp
 */

use Automattic\WooCommerce\Utilities\FeaturesUtil;

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

class Vendor_Tasks_Dokan_ClickUp {

	/**
	 * Singleton instance
	 *
	 * @var self|null
	 */
	private static ?self $instance = null;

	/**
	 * Plugin version
	 *
	 * @var string
	 */
	public string $version = VENDOR_TASKS_DOKAN_CLICKUP_VERSION;

	/**
	 * ClickUp API handler instance
	 *
	 * @var ?VendorTasksDokanClickUp\API\ClickUpClient
	 */
	private ?VendorTasksDokanClickUp\API\ClickUpClient $clickup_client = null;

	/**
	 * Plan Manager instance
	 *
	 * @var ?VendorTasksDokanClickUp\Licensing\PlanManager
	 */
	private ?VendorTasksDokanClickUp\Licensing\PlanManager $plan_manager = null;

	public static function get_instance(): self {
		return self::$instance ??= new self();
	}

	public function init(): void {
		// Migrate legacy DB keys from the pre-rebrand prefix before anything reads settings.
		( new VendorTasksDokanClickUp\Migration\KeyMigrator() )->maybe_migrate();

		register_activation_hook( VENDOR_TASKS_DOKAN_CLICKUP_FILE, array( $this, 'activate' ) );
		register_deactivation_hook( VENDOR_TASKS_DOKAN_CLICKUP_FILE, array( $this, 'deactivate' ) );

		add_action( 'before_woocommerce_init', array( $this, 'declare_woocommerce_feature_compatibility' ) );
		add_action( 'admin_notices', array( $this, 'dependency_notice' ) );
		add_action( 'dokan_loaded', array( $this, 'init_components' ) );
	}

	/**
	 * Initialize plugin components
	 */
	public function init_components(): void {
		// Initialize ClickUp API client
		$this->clickup_client = new VendorTasksDokanClickUp\API\ClickUpClient();

		// Initialize Plan Manager
		$this->plan_manager = new VendorTasksDokanClickUp\Licensing\PlanManager();

		// Initialize REST API
		new VendorTasksDokanClickUp\Rest\ConnectivityController();
		new VendorTasksDokanClickUp\Rest\SettingsController();
		new VendorTasksDokanClickUp\Rest\OverviewController();

		if ( is_admin() ) {
			// Initialize settings management
			new VendorTasksDokanClickUp\Settings\Menu();
			new VendorTasksDokanClickUp\Settings\Assets();
			new VendorTasksDokanClickUp\Settings\PluginLinks();

			// Admin profile integration (per-vendor button + bulk action)
			new VendorTasksDokanClickUp\Admin\VendorProfile();
		}

		// Initialize vendor registration hooks
		new VendorTasksDokanClickUp\VendorIntegration\Registration();

		// Initialize vendor deletion handler (F-21)
		new VendorTasksDokanClickUp\VendorIntegration\DeletionHandler();

		// Vendor status change triggers (approved / disabled)
		new VendorTasksDokanClickUp\VendorIntegration\StatusTriggers();

		// Email notification when task creation permanently fails
		new VendorTasksDokanClickUp\Notifications\EmailNotifier();

		// Initialize retry queue scheduler
		new VendorTasksDokanClickUp\Queue\RetryScheduler();

		// Initialize GDPR personal data eraser (F-17)
		new VendorTasksDokanClickUp\Privacy\PersonalDataEraser();

		/**
		 * Fires after all core components are initialized, deferred to `init` so
		 * that add-ons bootstrapped on `plugins_loaded` can register callbacks first.
		 * Priority 5 ensures it runs before `rest_api_init` (priority 99).
		 */
		add_action(
			'init',
			static function () {
				do_action( 'vendor_tasks_dokan_clickup_loaded' );
			},
			5
		);
	}

	/**
	 * Check if WooCommerce is active
	 */
	public function is_woocommerce_active(): bool {
		return is_plugin_active( 'woocommerce/woocommerce.php' );
	}

	/**
	 * Check if Dokan is active
	 */
	public function is_dokan_active(): bool {
		return is_plugin_active( 'dokan-lite/dokan.php' );
	}

	/**
	 * Check plugin dependencies
	 */
	private function check_dependencies(): bool {
		return $this->is_woocommerce_active() && $this->is_dokan_active();
	}

	/**
	 * Show dependency notice
	 */
	public function dependency_notice(): void {
		if ( $this->check_dependencies() ) {
			return;
		}

		$missing = array();
		if ( ! $this->is_woocommerce_active() ) {
			$missing[] = 'WooCommerce';
		}

		if ( ! $this->is_dokan_active() ) {
			$missing[] = 'Dokan';
		}

		printf(
			'<div class="notice notice-error"><p>%s</p></div>',
			sprintf(
				/* translators: %s: List of missing plugin dependencies */
				esc_html__( 'Alamin Vendor Tasks for Dokan with ClickUp requires: %s', 'alamin-vendor-tasks-dokan-clickup' ),
				esc_html( implode( ', ', $missing ) )
			)
		);
	}

	/**
	 * Declare WooCommerce HPOS compatibility
	 */
	public function declare_woocommerce_feature_compatibility(): void {
		if ( ! class_exists( FeaturesUtil::class ) ) {
			return;
		}

		$features = array(
			'custom_order_tables',
			'cart_checkout_blocks',
			'analytics',
			'marketplace',
			'order_attribution',
			'site_visibility_badge',
			'remote_logging',
			'email_improvements',
			'blueprint',
		);

		foreach ( $features as $feature ) {
			FeaturesUtil::declare_compatibility( $feature, VENDOR_TASKS_DOKAN_CLICKUP_FILE, true );
		}
	}

	/**
	 * Plugin activation
	 */
	public function activate(): void {
		// Check dependencies before activation
		if ( ! $this->check_dependencies() ) {
			wp_die(
				esc_html__( 'Alamin Vendor Tasks for Dokan with ClickUp requires WooCommerce and Dokan.', 'alamin-vendor-tasks-dokan-clickup' ),
				esc_html__( 'Plugin Activation Error', 'alamin-vendor-tasks-dokan-clickup' ),
				array( 'back_link' => true )
			);
		}

		// Set default options
		$this->set_default_options();

		// Flush rewrite rules
		flush_rewrite_rules();

		// Schedule retry cron
		( new VendorTasksDokanClickUp\Queue\RetryScheduler() )->schedule_cron();

		// Set activation flag
		update_option( 'vendor_tasks_dokan_clickup_activated', true );

		do_action( 'vendor_tasks_dokan_clickup_activated' );
	}

	/**
	 * Plugin deactivation
	 */
	public function deactivate(): void {
		// Unschedule retry cron
		( new VendorTasksDokanClickUp\Queue\RetryScheduler() )->unschedule_cron();

		// Flush rewrite rules
		flush_rewrite_rules();

		do_action( 'vendor_tasks_dokan_clickup_deactivated' );
	}

	/**
	 * Set default plugin options
	 */
	private function set_default_options(): void {
		if ( ! get_option( 'vendor_tasks_dokan_clickup_settings' ) ) {
			$default_settings = array(
				'api_token'                      => '',
				'workspace_id'                   => '',
				'list_id'                        => '',
				'task_priority'                  => 3,
				'task_name_format'               => 'New Vendor: {vendor_name}',
				'task_description_type'          => 'normal',
				'description_template'           => '',
				'task_status'                    => '',
				'task_assignees'                 => array(),
				'task_due_date_offset'           => 0,
				'withdraw_request_action'        => 'none',
				'reverse_withdrawal_alert'       => false,
				'first_sale_comment'             => false,
				'payment_method_check'           => false,
				'first_product_published_status' => '',
				'order_comment_enabled'          => false,
				'commission_change_comment'      => false,
				'trust_status_tag'               => false,
				'trigger_vendor_approved'        => false,
				'trigger_vendor_approved_status' => '',
				'trigger_vendor_disabled'        => false,
				'trigger_vendor_disabled_status' => '',
				'sync_on_profile_update'         => false,
				'product_review_action'          => 'none',
				'enable_webhook'                 => false,
				'webhook_secret'                 => '',
				'webhook_status_mappings'        => array(),
				'enable_list_routing'            => false,
				'routing_rules'                  => array(),
				'slack_webhook_url'              => '',
				'slack_notify_task_created'      => false,
				'slack_notify_task_failed'       => false,
				'failure_notify_email'           => '',
				'enable_logging'                 => true,
				'retry_failed_tasks'             => true,
				'max_retry_attempts'             => 3,
			);
			update_option( 'vendor_tasks_dokan_clickup_settings', $default_settings );
		}
	}

	/**
	 * Get ClickUp client instance
	 *
	 * @return VendorTasksDokanClickUp\API\ClickUpClient
	 */
	public function get_clickup_client(): ?VendorTasksDokanClickUp\API\ClickUpClient {
		return $this->clickup_client;
	}

	/**
	 * Get the Plan Manager instance.
	 *
	 * @since 1.4.0
	 *
	 * @return VendorTasksDokanClickUp\Licensing\PlanManager
	 */
	public function plan_manager(): VendorTasksDokanClickUp\Licensing\PlanManager {
		if ( null === $this->plan_manager ) {
			$this->plan_manager = new VendorTasksDokanClickUp\Licensing\PlanManager();
		}
		return $this->plan_manager;
	}

	/**
	 * Get plugin settings
	 *
	 * @return array
	 */
	public function get_settings(): array {
		return get_option( 'vendor_tasks_dokan_clickup_settings', array() );
	}

	/**
	 * Get specific setting value
	 *
	 * @param string $key Setting key.
	 * @param mixed  $default_value Default value.
	 * @return mixed
	 */
	public function get_setting( string $key, $default_value = '' ) {
		$settings = $this->get_settings();
		return $settings[ $key ] ?? $default_value;
	}

	/**
	 * Log message to debug log if logging is enabled
	 *
	 * @param string $message Log message.
	 * @param string $level Log level (error, warning, info).
	 */
	public function log( string $message, string $level = 'info' ): void {
		if ( ! $this->get_setting( 'enable_logging', true ) ) {
			return;
		}

		if ( function_exists( 'wc_get_logger' ) ) {
			$logger  = wc_get_logger();
			$context = array( 'source' => 'alamin-vendor-tasks-dokan-clickup' );

			if ( ! $logger instanceof WC_Logger ) {
				return;
			}

			switch ( $level ) {
				case 'error':
					$logger->error( $message, $context );
					break;
				case 'warning':
					$logger->warning( $message, $context );
					break;
				default:
					$logger->info( $message, $context );
					break;
			}
		} else {
			// Fallback to error_log
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
			error_log( sprintf( '[Alamin Vendor Tasks for Dokan with ClickUp] %s: %s', strtoupper( $level ), $message ) );
		}
	}
}
