<?php

namespace EasyContentManager\Admin;

use RuntimeException;
use SE_License_SDK_Client;
use SE_License_SDK_License;
use stdClass;

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


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

	private 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 EASY_CONTENT_MANAGER_ROOT_DIR_PATH . 'library/storeengine/init.php';

		if ( ! did_action( 'plugins_loaded' ) ) {
			add_action( 'plugins_loaded', [ $this, 'get_sdk' ] );
		} else {
			$this->get_sdk();
		}
	}

	public function get_sdk(): SE_License_SDK_Client {
		if ( null === self::$sdk_client ) {
			self::$sdk_client = se_license_init( [
				'package_file'        => EASY_CONTENT_MANAGER_PLUGIN_FILE,
				'package_name'        => 'Easy Content Manager (ECM) Pro', // translation remove due to load too early
				'product_id'          => 202,
				'is_free'             => false,
				'use_update'          => true,
				'slug'                => 'easy-content-manager-pro',
				'basename'            => EASY_CONTENT_MANAGER_PLUGIN_BASENAME,
				'package_type'        => 'plugin',
				'package_version'     => EASY_CONTENT_MANAGER_VERSION,
				'allow_local'         => true,
				'menu'                => admin_url( 'admin.php?page=easy-content-manager-settings&path=manage_pro' ),
				'init_restapi'        => true,
				'script_handler'      => 'easy-content-manager-admin-scripts',
				'license_server'      => 'https://store.kodezen.com/',
				'purchase_url'        => 'https://easycontentmanager.pro/',
				'product_logo'        => defined( 'EASY_CONTENT_MANAGER_ASSETS_URI' ) ? EASY_CONTENT_MANAGER_ASSETS_URI . 'images/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( 'easy_content_manager_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.', 'easy-content-manager' ) );
		}

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

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