<?php
/**
 * Plugin Name: Kadence Pattern Hub - SureCart Licensing
 * Plugin URI:  https://www.kadencewp.com/kadence-cloud/
 * Description: Extends the licensing to work with SureCart.
 * Version:     1.0.4
 * Author:      Kadence WP
 * Author URI:  https://www.kadencewp.com/
 * License:     GPL2
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Domain Path: /languages
 * Text Domain: kadence-cloud-surecart-license
 *
 * @package Kadence Cloud SureCart License
 */

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

define( 'KADENCE_CLOUD_SC_LICENSE_PATH', realpath( plugin_dir_path( __FILE__ ) ) . DIRECTORY_SEPARATOR );
define( 'KADENCE_CLOUD_SC_LICENSE_URL', plugin_dir_url( __FILE__ ) );
define( 'KADENCE_CLOUD_SC_LICENSE_VERSION', '1.0.4' );


/**
 * Load Plugin
 */
function kadence_cloud_surecart_license_init() {
	require_once KADENCE_CLOUD_SC_LICENSE_PATH . 'kadence-cloud-surecart-license-client.php';
	add_action( 'after_setup_theme', 'kadence_cloud_surecart_add_sections', 30 );
}
add_action( 'plugins_loaded', 'kadence_cloud_surecart_license_init', 20 );

/**
 * Load Settings
 */
function kadence_cloud_surecart_add_sections() {
	if ( ! class_exists( 'Kadence_Cloud_Settings' ) || ! class_exists( 'Kadence_Settings_Engine' ) ) {
		return;
	}
	Kadence_Settings_Engine::set_section(
		'kadence_cloud',
		array(
			'id'     => 'sc_keys',
			'title'  => __( 'SureCart', 'kadence-cloud' ),
			'long_title'  => __( 'SureCart License Products', 'kadence-cloud' ),
			'desc'   => '',
			'fields' => array(
				array(
					'id'       => 'sc_license_public_token',
					'type'     => 'text',
					'title'    => __( 'Add SureCart Public Token', 'kadence-cloud' ),
					'help'     => __( 'Get your public token here', 'kadence-cloud' ),
					'helpLink' => 'https://app.surecart.com/api_tokens/',
				),
				array(
					'id'         => 'sc_license_products',
					'type'       => 'text_repeater_expanded',
					'title'      => __( 'License Products', 'kadence-cloud' ),
					'label'      => __( 'Product ID', 'kadence-cloud' ),
					'add_button' => __( 'Add Product', 'kadence-cloud' ),
					'note_label' => __( 'Product Name', 'kadence-cloud' ),
					'editable'   => true,
					'content'    => 'empty',
				),
			),
		)
	);
}

/**
 * Set access to a specific cloud library collection.
 *
 * @param array  $args the query args for retrieving items.
 * @param string $key the access key.
 * @param array  $request_extras the extra args for the request.
 * @return array with updated query args.
 */
function kadence_cloud_surecart_kadence_cloud_query_args( $args, $key, $request_extras ) {
	$settings = json_decode( get_option( 'kadence_cloud' ), true );
	$products = array();
	if ( isset( $settings['sc_license_products'] ) && ! empty( $settings['sc_license_products'] ) && is_array( $settings['sc_license_products'] ) ) {
		if ( isset( $settings['sc_license_products'][0] ) && is_array( $settings['sc_license_products'][0] ) ) {
			$public_token  = '';
			if ( ! empty( $settings['sc_license_public_token'] ) ) {
				$public_token = $settings['sc_license_public_token'];
			} else {
				$public_token = class_exists( '\SureCart' ) ? \SureCart::account()->public_token : '';
				if ( empty( $public_token ) ) {
					$private_token = ( class_exists( '\SureCart\Models\ApiToken' ) ? \SureCart\Models\ApiToken::get() : '' );
					if ( ! empty( $private_token ) ) {
						$public_token = kadence_pattern_hub_get_public_token( $private_token );
					}
				}
			}
			if ( ! empty( $public_token ) ) {
				$client = new \KadencePatternHub\SureCart\Licensing\Custom\Client( $public_token );
				// Get the product for the license.
				$license_object = $client->validate( $key );
				if ( ! $license_object ) {
					return $args;
				}
				$product_id = isset( $license_object->product ) ? $license_object->product : '';
				if ( empty( $product_id ) ) {
					return $args;
				}
				$valid_product = false;
				$product_name  = '';
				foreach ( $settings['sc_license_products'] as $the_key => $the_products ) {
					if ( $the_products['key'] === $product_id ) {
						if ( isset( $the_products['collections'] ) && ! empty( $the_products['collections'] ) ) {
							$args['tax_query'] = array(
								array(
									'taxonomy' => 'kadence-cloud-collections',
									'field' => 'id',
									'terms' => explode( ',', $the_products['collections'] ),
								),
							);
						}
						break;
					}
				}
			}
		}
	}
	return $args;
}
add_filter( 'kadence_cloud_template_query_args', 'kadence_cloud_surecart_kadence_cloud_query_args', 10, 3 );

/**
 * Set name based on collection.
 *
 * @param array  $info the info for the collection.
 * @param object  $request the request.
 * @return array with updated info.
 */
function kadence_cloud_surecart_kadence_cloud_library_info_args( $info , $request ) {
	$settings = json_decode( get_option( 'kadence_cloud' ), true );
	$key      = $request->get_param( 'key' );
	$products = array();
	if ( isset( $settings['sc_license_products'] ) && ! empty( $settings['sc_license_products'] ) && is_array( $settings['sc_license_products'] ) ) {
		if ( isset( $settings['sc_license_products'][0] ) && is_array( $settings['sc_license_products'][0] ) ) {
			$public_token  = '';
			if ( ! empty( $settings['sc_license_public_token'] ) ) {
				$public_token = $settings['sc_license_public_token'];
			} else {
				$public_token = class_exists( '\SureCart' ) ? \SureCart::account()->public_token : '';
				if ( empty( $public_token ) ) {
					$private_token = ( class_exists( '\SureCart\Models\ApiToken' ) ? \SureCart\Models\ApiToken::get() : '' );
					if ( ! empty( $private_token ) ) {
						$public_token = kadence_pattern_hub_get_public_token( $private_token );
					}
				}
			}
			if ( ! empty( $public_token ) ) {
				$client = new \KadencePatternHub\SureCart\Licensing\Custom\Client( $public_token );
				// Get the product for the license.
				$license_object = $client->validate( $key );
				if ( ! $license_object ) {
					return $info;
				}
				$product_id = isset( $license_object->product ) ? $license_object->product : '';
				if ( empty( $product_id ) ) {
					return $info;
				}
				$valid_product = false;
				$product_name  = '';
				foreach ( $settings['sc_license_products'] as $the_key => $the_products ) {
					if ( $the_products['key'] === $product_id ) {
						if ( isset( $the_products['useAsPatternHubName'] ) && ! empty( $the_products['collections'][0] ) && $the_products['useAsPatternHubName'] === true ) {
							$collection = get_term_by( 'id', $the_products['collections'][0], 'kadence-cloud-collections' );
							if ( isset( $collection->name ) && ! empty( $collection->name ) ) {
								$info['name'] = $collection->name;
							}
						}
						break;
					}
				}
			}
		}
	}
	return $info;
}
add_filter( 'kadence_cloud_library_info_args', 'kadence_cloud_surecart_kadence_cloud_library_info_args', 10, 2 );

/**
 * Validates license with license manager for SureCart
 *
 * @param Boolean         $access true or false based on access.
 * @param String          $key the access key.
 * @param WP_REST_Request $request full details about the request.
 * @return Boolean based on if access should be granted.
 */
function kadence_cloud_surecart_check_cloud_access( $access, $key, $request ) {
	// If true the key matches with settings in Kadence Cloud. Let that pass for testing purposes.
	if ( $access ) {
		return $access;
	}
	// class must exist.
	if ( ! class_exists( 'KadencePatternHub\SureCart\Licensing\Custom\Client' ) ) {
		return $access;
	}
	$settings = json_decode( get_option( 'kadence_cloud' ), true );
	$products = array();
	if ( isset( $settings['sc_license_products'] ) && ! empty( $settings['sc_license_products'] ) && is_array( $settings['sc_license_products'] ) ) {
		if ( isset( $settings['sc_license_products'][0] ) && is_array( $settings['sc_license_products'][0] ) ) {
			foreach ( $settings['sc_license_products'] as $the_key => $the_products ) {
				$products[] = array(
					'name' => ! empty( $the_products['note'] ) ? $the_products['note'] : 'Cloud Access',
					'id'   => $the_products['key'],
				);
			}
		}
	}
	if ( empty( $products ) ) {
		return $access;
	}
	$public_token  = '';
	$fingerprint   = preg_replace( '(^https?://)', '', $request->get_param( 'site' ) );
	$valid_license = false;
	if ( ! empty( $settings['sc_license_public_token'] ) ) {
		$public_token = $settings['sc_license_public_token'];
	} else {
		$public_token = class_exists( '\SureCart' ) ? \SureCart::account()->public_token : '';
		if ( empty( $public_token ) ) {
			$private_token = ( class_exists( '\SureCart\Models\ApiToken' ) ? \SureCart\Models\ApiToken::get() : '' );
			if ( ! empty( $private_token ) ) {
				$public_token = kadence_pattern_hub_get_public_token( $private_token );
			}
		}
	}
	if ( empty( $public_token ) ) {
		return $access;
	}
	$client = new \KadencePatternHub\SureCart\Licensing\Custom\Client( $public_token );
	// Get the product for the license.
	$license_object = $client->validate( $key );
	if ( ! $license_object ) {
		return false;
	}
	$product_id = isset( $license_object->product ) ? $license_object->product : '';
	if ( empty( $product_id ) ) {
		return false;
	}
	$valid_product = false;
	$product_name  = '';
	foreach ( $products as $product ) {
		if ( $product['id'] === $product_id ) {
			$valid_product = true;
			$product_name  = $product['name'];
			break;
		}
	}
	if ( ! $valid_product ) {
		return false;
	}
	// is the license activated yet or can it be activated?
	$activated = $client->is_active( $license_object->id, $fingerprint, $product_name );

	// does not activate.
	if ( ! $activated ) {
		// handle response.
		return false;
	}
	// handle response.
	return true;
}
add_filter( 'kadence_cloud_rest_request_access', 'kadence_cloud_surecart_check_cloud_access', 10, 3 );

/**
 * Get the public token from the private token.
 *
 * @param string $private_token the private token.
 */
function kadence_pattern_hub_get_public_token( $private_token ) {
	$public_token = '';
	$response = wp_safe_remote_get(
		'https://api.surecart.com/v1/account',
		array(
			'headers' => array(
				'accept' => 'application/json',
				'authorization' => 'Bearer ' . $private_token,
			),
			'timeout' => 20,
		)
	);
	if ( is_wp_error( $response ) ) {
		return '';
	}
	// Get the CSS from our response.
	$contents = json_decode( wp_remote_retrieve_body( $response ), true );
	// Early exit if there was an error.
	if ( is_array( $contents ) && ! empty( $contents['public_token'] ) ) {
		// update settings and return public token.
		$settings = json_decode( get_option( 'kadence_cloud' ), true );
		$settings['sc_license_public_token'] = $contents['public_token'];
		update_option( 'kadence_cloud', wp_json_encode( $settings ) );
		return $contents['public_token'];
	}
	return '';
}
/**
 * Load the plugin textdomain
 */
function kadence_cloud_surecart_lang() {
	load_plugin_textdomain( 'kadence-cloud-surecart-license', false, basename( dirname( __FILE__ ) ) . '/languages' );
}
add_action( 'init', 'kadence_cloud_surecart_lang' );

/**
 * Plugin Updates.
 */
function kadence_cloud_surecart_updating() {
	require KADENCE_CLOUD_SC_LICENSE_PATH . 'kadence-update-checker/kadence-update-checker.php';
	$kadence_cloud_surecart_update_checker = Kadence_Update_Checker::buildUpdateChecker(
		'https://kernl.us/api/v1/updates/63c1ee0aaeb640cc9adc7bb8/',
		__FILE__,
		'kadence-cloud-surecart-license'
	);
}
add_action( 'after_setup_theme', 'kadence_cloud_surecart_updating', 1 );
