<?php
/**
 * Spacetree setup
 *
 * @package Spacetree
 * @since   2.1.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * Main WooCommerce Class.
 *
 * @class WooCommerce
 */
final class Spacetree {

	/**
	 * Spacetree version.
	 *
	 * @var string
	 */
	public $version = '3.0.0.2'; // v3.0.0  - migration plugin
	public $fix_version = '3.0.0.2';
	
	/**
	 * Database schema version.
	 * 
	 * @var string
	 * @since 2.1.0
	 */
	public $db_version = '3.0'; // v1.0 = optimized submissions table architecture

    protected static $_instance = null;

    /**
	 * Main Spacetree Instance.
	 *
	 * Ensures only one instance of Spacetree is loaded or can be loaded.
	 *
	 * @since 1.0
	 * @static
	 * @see ST()
	 * @return Spacetree - Main instance.
	 */
	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

    /**
	 * Spacetree Constructor.
	 */
	public function __construct() {
		$this->define_constants();
		$this->define_globals();
		$this->define_site_keys();
		$this->update_version();
		$this->includes();
		
	}

    /**
	 * Define ST Constants.
	 */
	private function define_constants() {
		$this->define('ST_ROOT_ENDPOINT', 'https://v1.proqyz.com');
		$this->define('ST_CDN_ENDPOINT', 'd2sbwnybl91fb1.cloudfront.net');
		$this->define('ST_OLD_CDN_ENDPOINT', 'client-server-dashboard.s3.ap-south-1.amazonaws.com');
		$this->define( 'ST_ABSPATH', dirname( ST_PLUGIN_FILE ) . '/' );
		$this->define( 'ST_PLUGIN_BASENAME', plugin_basename( ST_PLUGIN_FILE ) );
		$this->define( 'ST_TEMPLATE_DIR', ST_ABSPATH . 'includes/templates' );
		$this->define( 'ST_VERSION', $this->version );
		$this->define( 'ST_MAINTENANCE_VERSION', $this->fix_version );
		$this->define( 'ST_DB_VERSION', $this->db_version ); // Database schema version
		$this->define( 'ST_SLUG', 'st');
		$this->define( 'ST_MAIN_ENDPOINT', ST_ROOT_ENDPOINT .'/v2/wp-client'); // api endpoint for spacetree
		$this->define( 'ST_UPDATE_URL', ST_ROOT_ENDPOINT.'/wp-plugin/proqyz/v3/latest'); // plugin repository endpoint
		$this->define( 'ST_ADDONS_ENDPOINT', 'https://plugin.proqyz.com/addons' );
		$this->define( 'ST_TUTORIALS_ENDPOINT', 'https://plugin.proqyz.com/tutorials' );
		$this->define( 'ST_CHANGELOG_ENDPOINT', 'http://proqyz.spacetree.org' );
		# aditional addon license manager
		$this->define( 'ST_PROQYZ_LICENSE_MAIN_ENDPOINT', ST_ROOT_ENDPOINT.'/wp-business' );

	}

	private function define_globals(){
		global $wpdb, $table_st_oauth;
		$table_st_oauth = $wpdb->prefix.'st_oauth';

		global $st_version_key, $st_maintenance_key, $st_db_version_key;
		$st_version_key = 'ST_VERSION';
		$st_maintenance_key = 'ST_MAINTENANCE_VERSION';
		$st_db_version_key = 'ST_DB_VERSION'; // Database schema version option key
	}

    /**
	 * Register custom tables within $wpdb object.
	 */
	private function define_tables() { 
		global $wpdb;
		// nothing for now
	}
	

	private function define_site_keys() {
		# get unique identity token
        // Define your option key
        $option_key = 'st_site-unique-identity';

        // Get the value of the option
        $option_value = get_option($option_key, false);
        if( $option_value !== false ) {
            
        } else {
            $randomPassword = $this->generateRandomString();
            $hashedPassword = password_hash($randomPassword, PASSWORD_DEFAULT);
            update_option($option_key, $hashedPassword);
        }
	}

    /**
	 * Define constant if not already set.
	 *
	 * @param string      $name  Constant name.
	 * @param string|bool $value Constant value.
	 */
	private function define( $name, $value ) {
		if ( ! defined( $name ) ) {
			define( $name, $value );
		}
	}

	/**
	 * Include required core files used in admin and on the frontend.
	 */
	public function includes() {
		/**
		 * Class autoloader.
		 */
		include_once ST_ABSPATH . 'includes/class-st-posts.php';
		include_once ST_ABSPATH . 'includes/class-st-private.php';
		include_once ST_ABSPATH . 'includes/class-st-oauth.php';
		include_once ST_ABSPATH . 'includes/class-st-rest-api.php';
		include_once ST_ABSPATH . 'includes/class-st-changelog.php';
		/**
		 * Class ST_Admin
		 */
		include_once ST_ABSPATH . 'includes/admin/class-st-admin.php';

		/**
		 * Migration menu (root level)
		 * @since 2.1.0
		 */
		if ( is_admin() ) {
			include_once ST_ABSPATH . 'includes/admin/class-st-admin-menus.php';
		}

		/**
		 * libs loader - conditional based on migration status
		 * @since 2.1.0
		 */
		$this->load_proqyz_lib();
		/**
		 * 'libs/proqyz-license-manager/proqyz-license-manager.php';
		 *
		 */

		/**
		 * class ST_Private
		 * for debugging reports
		 */
		$private_auth = new ST_Private();

		/**
		 * class auto_update for ST
		 */
		include_once ST_ABSPATH . 'includes/class-st-autoupdate.php';
		
		// Get plugin name from plugin header (read directly to avoid translation loading)
		$plugin_name = 'Spacetree'; // Default fallback
		if (file_exists(ST_PLUGIN_FILE)) {
			$plugin_file_content = file_get_contents(ST_PLUGIN_FILE);
			if (preg_match('/Plugin Name:\s*(.+)/i', $plugin_file_content, $matches)) {
				$plugin_name = trim($matches[1]);
			}
		}
		
		$autoupdate = new ST_Autoupdate(
			ST_SLUG, 
			$plugin_name, 
			$this->version, 
			$this->db_version, 
			ST_UPDATE_URL,
			ST_PLUGIN_BASENAME
		);

	}

	public function update_version(){
		global $st_version_key, $st_maintenance_key, $st_db_version_key;
		update_option($st_version_key, $this->version);
		update_option($st_maintenance_key, $this->fix_version);
		update_option($st_db_version_key, $this->db_version);
	}

	/**
	 * Check if plugin is currently usable
	 * 
	 * @return bool True if plugin can be used, false if migration required
	 * @since 2.1.0
	 */
	public static function is_plugin_usable() {
		return defined('ST_PLUGIN_DISABLED') && ST_PLUGIN_DISABLED === false;
	}

	/**
	 * Load ProQyz library
	 * 
	 * SIMPLIFIED APPROACH:
	 * - Always loads from libs/proqyz/ (current version in this plugin package)
	 * - No dynamic switching between folders
	 * - Features are controlled via ST_PLUGIN_DISABLED constant, not file paths
	 * - When user updates to v2.1.0+, WordPress replaces entire plugin with new code
	 * 
	 * This prevents 404 errors and complexity during migration transition period.
	 * 
	 * @since 2.1.0
	 */
	private function load_proqyz_lib() {
		/**
		 * ALWAYS load from libs/proqyz/ - no folder switching!
		 * 
		 * Migration process:
		 * 1. Before migration: libs/proqyz/ with v1 code (unlocked)
		 * 2. After migration: libs/proqyz/ with v1 code (locked via ST_PLUGIN_DISABLED)
		 * 3. After plugin update: libs/proqyz/ with v2 code (unlocked)
		 * 
		 * The libs/proqyz/ folder never changes location - only its CONTENTS change
		 * when user updates the plugin via WordPress update system.
		 */
		require_once ST_ABSPATH . 'libs/proqyz/proqyz.php';
	}

	private function generateRandomString($length = 20) {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$charactersLength = strlen($characters);
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, $charactersLength - 1)];
		}
		return $randomString;
	}



}