<?php
namespace QuizPress;

use SE_License_SDK_Client;
use SE_License_SDK_License;


if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class SeLicense {
	protected static ?SeLicense $instance = null;

	protected static ?SE_License_SDK_Client $sdk_client = null;
	
	public static function get_instance(): SeLicense {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}


		return self::$instance;
	}

	protected function __construct() {
		require_once QUIZPRESS_ROOT_DIR_PATH . 'library/storeengine/init.php';

		if ( ! did_action( 'plugins_loaded' ) ) {
			add_action( 'plugins_loaded', [ __CLASS__, 'get_sdk' ], 5 );
		} else {
			self::get_sdk();
		}
	}

	public static function get_sdk(): SE_License_SDK_Client {
		if ( null === self::$sdk_client ) {
			self::$sdk_client = se_license_init( [
				'package_file'        => QUIZPRESS_PLUGIN_FILE,
				'package_name'        => 'QuizPress Pro', // translation remove due to load too early
				'product_id'          => 206,
				'is_free'             => false,
				'use_update'          => true,
				'slug'                => 'quizpress-pro',
				'basename'            => QUIZPRESS_PLUGIN_BASENAME,
				'package_type'        => 'plugin',
				'package_version'     => QUIZPRESS_VERSION,
				'allow_local'         => true,
				// Pass `menu` as a URL string ( not an array ) so the SDK does
				// NOT register its own admin page. The license UI is rendered
				// inside QuizPress's own Settings screen ( React License tab ),
				// and this URL is only used as the post-activation redirect.
				'menu'                => admin_url( 'admin.php?page=quizpress-settings&path=license' ),
				'init_restapi'        => true,
				'script_handler'      => 'quizpress-admin-scripts',
				'license_server'      => 'https://store.kodezen.com/',
				'purchase_url'        => 'https://quizpress.pro/',
				'product_logo'        => defined( 'QUIZPRESS_ASSETS_URI' ) ? QUIZPRESS_ASSETS_URI . 'images/quizpress-logo.svg' : '',
				'store_dashboard_url' => 'https://store.kodezen.com/dashboard/license-keys/',
				'terms_url'           => 'https://kodezen.com/terms-and-conditions/',
				'privacy_policy_url'  => 'https://store.kodezen.com/privacy-policy/',
				'ticket_recipient'    => 'support@kodezen.com',
				'primary_color'       => '#006BFF',
				'first_install_time'  => get_option( 'quizpress_first_install_time' ),
				'optin_notice_delay'  => 3 * DAY_IN_SECONDS,
			] );
		}

		return self::$sdk_client;
	}

	public static function get_license(): SE_License_SDK_License {
		if ( ! self::$sdk_client ) {
			throw new \RuntimeException( 'Trying to get license data before SDK initialization.' );
		}

		return self::$sdk_client->license();
	}

	public static function is_pro() {
		return self::get_license()->is_valid();
	}
}

// End of file se-license.php.
