<?php

class TTF_Product_Central_Settings {

	private static $instance;
	private $pages = array();
	private $notice = false;

	public static function instance() {
		if ( is_null( self::$instance ) )
			self::$instance = new self();

		return self::$instance;
	}

	public function __construct() {
		add_action( 'admin_init', array( $this, 'admin_init' ) );
	}

	public function admin_menu() {
		$products = ttf_product_central_updater()->get_products();

		foreach ( $products as $product ) {
			$hook = add_submenu_page(
				$product->menu_id,
				__( 'Register', 'ttf-updates' ),
				__( 'Register', 'ttf-updates' ) . $this->get_register_badge( $product ),
				'manage_options',
				$product->page,
				array( $this, 'render_page' )
			);
		}
	}

	public function admin_init() {
		$products = ttf_product_central_updater()->get_products();

		foreach ( $products as $product ) {
			$this->pages[$product->page] = $product;
		}

		if ( isset( $_POST['action'] ) ) {
			if ( 'ttf-updates-authorize' === $_POST['action'] ) {
				$this->authorize();
			} else if ( 'ttf-updates-deauthorize' === $_POST['action'] ) {
				$this->deauthorize();
			}
		}
	}

	public function authorize( $page = '' ) {
		$page = empty( $page ) ? $_GET['page'] : $page;

		if ( ! check_admin_referer( $page ) ) {
			return;
		}

		if ( ! isset( $_POST['email'] ) || ! isset( $_POST['password'] ) ) {
			return;
		}

		$email = $_POST['email'];
		$password = $_POST['password'];
		$domain = str_replace( array( 'http://', 'https://' ), array( '', '' ), get_option( 'siteurl' ) );
		$product = $this->pages[$page];
		$authorized = $product->authorize( $email, $password, $domain );

		if ( is_wp_error( $authorized ) ) {
			$this->notice = array(
				'type' => 'error',
				'message' => $authorized->get_error_message(),
			);
		}
	}

	public function deauthorize( $page = '' ) {
		$page = empty( $page ) ? $_GET['page'] : $page;
		$product = $this->pages[$page];
		$product->deauthorize();
	}

	public function render_page( $page = '' ) {
		$page = empty( $page ) ? $_GET['page'] : $page;
		$product = $this->pages[$page];
		$notice = $this->notice;
		$template_path = apply_filters( 'ttf_product_central_settings_template', 'template-settings.php' );

		require_once( $template_path );
	}

	public function get_register_badge( $product ) {
		$badge = '';

		if ( ! $product->is_authorized() ) {
			$badge = ' <span class="awaiting-mod count-1"><span class="pending-count">1</span></span>';
		}

		return $badge;
	}

}

if ( ! function_exists( 'ttf_product_central_settings' ) ) :

function ttf_product_central_settings() {
	return TTF_Product_Central_Settings::instance();
}

endif;

ttf_product_central_settings();