<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://revivedesignstudios.com
 * @since      1.0.0
 *
 * @package    Rds_Bt50_Scorecard
 * @subpackage Rds_Bt50_Scorecard/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Rds_Bt50_Scorecard
 * @subpackage Rds_Bt50_Scorecard/admin
 * @author     Revive Design Studios <connect@revivedesignstudios.com>
 */
class Rds_Bt50_Scorecard_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 * @param      Bt50DataClient    $dataClient    The data client.
	 */
	public function __construct( $plugin_name, $version, $dataClient  ) {
		$this->plugin_name = $plugin_name;
		$this->version = $version;
		$this->dataClient = $dataClient;
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles($hook) {
		if($hook != 'settings_page_' . $this->plugin_name) { return; }
		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . '../public/css/bt50-scorecard-admin.css', array(), $this->version, 'all' );
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts($hook) {
		if($hook != 'settings_page_' . $this->plugin_name) { return; }
		// wp_enqueue_script( 'tinymce_js', includes_url( 'js/tinymce/' ) . 'tinymce.min.js', array( 'jquery' ), false, true ); // wp included version
		wp_enqueue_script(
			'tinymce_js',
			plugin_dir_url( __FILE__ ) . 'js/tinymce/tinymce.min.js',
			array( 'jquery' ),
			false,
			true
		);
		wp_enqueue_script(
			$this->plugin_name . 'bt50-common',
			plugin_dir_url( __FILE__ ) . '../public/js/bt50-scorecard-common.js',
			array( 'jquery' ),
			$this->version,
			true
		);
		wp_enqueue_script(
			$this->plugin_name. '-adminjs',
			plugin_dir_url( __FILE__ ) . 'js/rds-bt50-scorecard-admin.js',
			array( 'jquery', $this->plugin_name . 'bt50-common' ),
			$this->version,
			true
		);
		wp_enqueue_script(
			$this->plugin_name. '-admin',
			plugin_dir_url( __FILE__ ) . '../public/js/bt50-scorecard-admin.js',
			array( 'jquery', $this->plugin_name . 'bt50-common' ),
			$this->version,
			true
		);
	}

	/**
	 * Register the administration menu for this plugin into the WordPress Dashboard menu.
	 *
	 * @since    1.0.0
	 */
	public function add_plugin_admin_menu() {
		// Administration Menus: http://codex.wordpress.org/Administration_Menus
		// https://codex.wordpress.org/Function_Reference/add_options_page
		add_options_page(
			'BillTrack50 Scorecard Settings',
			'BillTrack50 Scorecard',
			'manage_options',
			$this->plugin_name,
			array($this, 'display_plugin_setup_page')
		);
	}

	public function alert_invalid_bt50_api_key() {
		$linkToSettings = '<a href="' . admin_url( 'options-general.php?page=' . $this->plugin_name ) . '">Configure here!</a>';
		$msg = 'You need to configure a valid API key for your BillTrack50 scorecard.';
		?>
		<div class="notice notice-warning">
			<p><?php echo $msg . ' ' . $linkToSettings; ?></p>
		</div>
		<?php
	}

	// public function bt50_connection_valid_alert() {
	// 	$bt50ConnectionValid = $this->dataClient->bt50ConnectionValid();
	// 	if (!$bt50ConnectionValid) {
	// 		add_action( 'admin_notices', array($this, 'alert_invalid_bt50_api_key') );
	// 	} else {
	// 		remove_action( 'admin_notices', array($this, 'alert_invalid_bt50_api_key') );
	// 	}
	// }

	public function display_alerts() {
		// TODO: validate bt50 api connection, but not on every admin load
		// $this->bt50_connection_valid_alert();
	}

	/**
	* Add settings action link to the plugins page.
	*
	* @since    1.0.0
	*/
	public function add_action_links( $links ) {
		// Documentation : https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)
		$settings_link = array(
		 '<a href="' . admin_url( 'options-general.php?page=' . $this->plugin_name ) . '">' . __('Settings', $this->plugin_name) . '</a>',
		);
		return array_merge(  $settings_link, $links );
	}

	public function try_update_option($key, $data){
		if (!isset($data[$key]) || empty($data[$key])) {
			return false;
		}
		update_option($key, $data[$key]);
		return true;
	}

	public function update_options($data) {
		$this->try_update_option('score_license_key', $data);
		$this->try_update_option('score_bt50_api_key', $data);
		$this->try_update_option('score_id', $data);

		if (!$this->try_update_option('score_header_img', $data)) {
			$assetPath = "/wp-content/plugins/rds-bt50-scorecard/public/assets/";
			$score_header_img = $assetPath . '61723a75f62d8ba744536ae17cb712a5.png';
			update_option('score_header_img', $score_header_img);
		}

		if (!$this->try_update_option('score_header', $data)) {
			update_option('score_header', 'Our State Legislative Scorecard');
		}

		if (!$this->try_update_option('score_info', $data)) {
			update_option('score_info', 'Learn more about something. This is a place where you can add information about your scorecard to the list view of Legislators below the Filters.');
		}

		if (!$this->try_update_option('score_membership', $data)) {
			update_option('score_membership', 0);
		}

		if (!isset($data['score_type']) || empty($data['score_type'])) {
			update_option('rds_bt50_blendedscore_enabled', 0);
		} else {
			if ($data['score_type'] == 'blended') {
				update_option('rds_bt50_blendedscore_enabled', 1);
			} else {
				update_option('rds_bt50_blendedscore_enabled', 0);
			}
		}
	}

	/**
	* Render the settings page for this plugin.
	*
	* @since    1.0.0
	*/
	public function display_plugin_setup_page() {
		if ($_POST) {
			$this->update_options($_POST);
		}

		$score_license_key = get_option('score_license_key');
		$score_bt50_api_key = get_option('score_bt50_api_key');
		$score_os_api_key = get_option('score_os_api_key');
		$score_id = get_option('score_id');
		$score_header_img = get_option('score_header_img');
		$score_header = get_option('score_header');
		$score_info = get_option('score_info');
		$score_membership = get_option('score_membership');
		$score_blendedscore_enabled = get_option('rds_bt50_blendedscore_enabled') == 1;

		$bt50Client = new Bt50ApiClient($score_bt50_api_key);
		$openstatesClient = new OpenStatesApiClient($score_os_api_key);
		$dataClient = new Bt50DataClient($bt50Client, $openstatesClient);
		$bt50ConnectionValid = $dataClient->bt50ConnectionValid();

		if (!$score_bt50_api_key || !$bt50ConnectionValid) {
			$scorecards_loaded_successfully = false;
		} else {
			$scorecards = $dataClient->scorecards();
			if (!$score_id && sizeof($scorecards) > 0) {
				update_option('score_id', $scorecards[0]['ScorecardID']);
				$score_id = $scorecards[0]['ScorecardID'];
			}
			$scorecards_loaded_successfully = !is_wp_error($scorecards);
		}

		$assetPath = "/wp-content/plugins/rds-bt50-scorecard/public/assets/";
		include_once( 'partials/rds-bt50-scorecard-admin-display.php' );
	}

	public function validate($input) {
		$valid = array();
		$valid['score_bt50_api_key'] = (isset($input['score_bt50_api_key']) && !empty($input['score_bt50_api_key'])) ? 1 : 0;
		return $valid;
 	}

	public function options_update() {
		// register_setting WP API https://developer.wordpress.org/reference/functions/register_setting/
		register_setting($this->plugin_name, $this->plugin_name, array($this, 'validate'));
	}
}
