<?php
/**
 * Plugin Lifecycle Handler
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage Handlers
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\Handlers;

use MOWCPS\Common\Constants\Constants;

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

/**
 * Class Plugin_Lifecycle_Handler
 *
 * Handles plugin lifecycle operations (activation, deactivation, uninstall)
 */
class Plugin_Lifecycle_Handler {

	/**
	 * Handle plugin activation
	 *
	 * @return void
	 */
	public function handle_activation() {
	}

	/**
	 * Handle plugin deactivation
	 *
	 * @return void
	 */
	public function handle_deactivation() {
		$this->cleanup_user_data();
		$this->cleanup_mowcps_crons();
	}

	/**
	 * Handle plugin uninstall
	 *
	 * @return void
	 */
	public function handle_uninstall() {
	}

	/**
	 * Clean up user-related data on deactivation
	 *
	 * @return void
	 */
	private function cleanup_user_data() {
		$namespace    = strpos( Constants::MOWCPS_PLAN_NAME, 'standard' ) ? 'Standard' : MOWCPS_PLAN_NAMESPACE;
		$user_handler = 'MOWCPS\\' . $namespace . '\\Handlers\\Rest_API\\User_Handler';
		$user_handler::delete_user_details();
	}

	/**
	 * Clean up all cron jobs starting with 'mowcps' on plugin deactivation
	 *
	 * @return void
	 */
	private function cleanup_mowcps_crons() {
		$cron_array = _get_cron_array();

		if ( ! is_array( $cron_array ) ) {
			return;
		}

		foreach ( $cron_array as $timestamp => $cron_jobs ) {
			foreach ( $cron_jobs as $hook_name => $hook_data ) {
				// Check if the hook name starts with 'mowcps'.
				if ( 0 === strpos( $hook_name, 'mowcps' ) ) {
					foreach ( $hook_data as $hash => $cron_job ) {
						$args = isset( $cron_job['args'] ) ? $cron_job['args'] : array();
						wp_clear_scheduled_hook( $hook_name, $args );
					}
				}
			}
		}
	}
}
