<?php
/**
 * The admin-specific functionality of the plugin.
 *
 * @package    Expandable_Paywall
 * @subpackage Expandable_Paywall/admin
 * @author     Pramadillo <support@pramadillo.com>
 */

namespace Emoxie\Expandable_Paywall;

use WP_Error;

class Expandable_Paywall_Admin {

	/**
	 * Function is called by Core admin_init action
	 */
	public function init() {

		$this->create_paid_user_role();
		$this->create_options();
		$this->maybe_create_logging_tables();
	}

	public function enqueue_styles() {
		wp_register_style( EXPANDABLE_PAYWALL_SLUG . '_admin', EXPANDABLE_PAYWALL_URL . 'admin/css/expandable-paywall-admin.css', [], EXPANDABLE_PAYWALL_VERSION );
		wp_register_style( EXPANDABLE_PAYWALL_SLUG . '_select2_css', EXPANDABLE_PAYWALL_URL . 'vendor/select2/select2/dist/css/select2.min.css', [], EXPANDABLE_PAYWALL_VERSION );
		wp_register_style( EXPANDABLE_PAYWALL_SLUG . '_datatables_core', 'https://cdn.datatables.net/v/dt/dt-1.13.8/b-2.4.2/b-colvis-2.4.2/sp-2.2.0/sl-1.7.0/sr-1.3.0/datatables.min.css' );

	}

	public function enqueue_scripts() {
		wp_register_script( EXPANDABLE_PAYWALL_SLUG . '_admin', EXPANDABLE_PAYWALL_URL . 'admin/js/expandable-paywall-admin.js', [ 'jquery' ], EXPANDABLE_PAYWALL_VERSION, false );
		wp_register_script( EXPANDABLE_PAYWALL_SLUG . '_select2_js', EXPANDABLE_PAYWALL_URL . 'vendor/select2/select2/dist/js/select2.min.js', [ 'jquery' ], EXPANDABLE_PAYWALL_VERSION, true );
		wp_register_script( EXPANDABLE_PAYWALL_SLUG . '_datatables_core', 'https://cdn.datatables.net/v/dt/dt-1.13.8/b-2.4.2/b-colvis-2.4.2/sp-2.2.0/sl-1.7.0/sr-1.3.0/datatables.min.js', [ 'jquery' ] );
		wp_localize_script( EXPANDABLE_PAYWALL_SLUG . '_datatables_core', 'datatablesajax',
			[
				'url'              => admin_url( 'admin-ajax.php' ),
				'nonce'            => wp_create_nonce( 'exp_get_logs' ),
				'clear_logs_nonce' => wp_create_nonce( 'exp_clear_logs' ),
			] );

		wp_register_script( EXPANDABLE_PAYWALL_SLUG . '_datatables', EXPANDABLE_PAYWALL_URL . 'admin/js/expandable-paywall-datatables.js', [ 'jquery', EXPANDABLE_PAYWALL_SLUG . '_datatables_core' ] );

	}


	/**
	 * @return void
	 */
	public function maybe_create_logging_tables() {
		$version = '1.5';
		$check   = get_option( EXPANDABLE_PAYWALL_SLUG . '_logging_database_present' );

		if ( $version !== $check ) {
			global $wpdb;

			$table_name      = $wpdb->prefix . "expandable_paywall_log";
			$charset_collate = $wpdb->get_charset_collate();

			$sql = "CREATE TABLE $table_name (
                          id bigint(14) NOT NULL AUTO_INCREMENT,
                          post_id bigint(14) DEFAULT NULL,
                          user_id bigint(14) DEFAULT NULL,
                          action varchar(255) NOT NULL,
                          data text DEFAULT NULL,
                          user_agent text DEFAULT NULL,
                          created_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
                          PRIMARY KEY  (id)
                        ) $charset_collate;";

			require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
			$insert = dbDelta( $sql );

			if ( $insert ) {
				update_option( EXPANDABLE_PAYWALL_SLUG . '_logging_database_present', $version );
			}

		}

	}


	/**
	 * Handles all sidebar menus
	 */
	public function add_menu() {

		// Add main menu page
		add_menu_page(
			__('Expandable Paywall', 'expandable-paywall'),
			__('Expandable <br>Paywall', 'expandable-paywall'),
			'manage_options', EXPANDABLE_PAYWALL_SLUG,
			[$this, 'create_options_page'],
			'dashicons-vault', 99
		);

		// Add settings submenu page
		add_submenu_page(
			EXPANDABLE_PAYWALL_SLUG,
			__('Settings', 'expandable-paywall'),
			__('Settings', 'expandable-paywall'),
			'manage_options',
			EXPANDABLE_PAYWALL_SLUG . '-settings',
			[$this, 'create_options_page']
		);

		// Add log submenu page if logging is enabled
		if (Logger::enable_logging()) {
			add_submenu_page(
				EXPANDABLE_PAYWALL_SLUG,
				__('Expandable Paywall Log', 'expandable-paywall'),
				__('Log', 'expandable-paywall'),
				'manage_options',
				EXPANDABLE_PAYWALL_SLUG . '-log',
				[$this, 'create_log_page']
			);
		}

		// Add a separator
		add_submenu_page(
			EXPANDABLE_PAYWALL_SLUG,
			'',
			'<span class="emoxie-admin-separator-container"><span class="emoxie-admin-separator-title">' . __('Account Info', 'expandable-paywall') . '</span><span class="emoxie-admin-separator"></span></span>',
			'manage_options',
			'#'
		);

		// Remove the automatically added submenu
		remove_submenu_page(EXPANDABLE_PAYWALL_SLUG, EXPANDABLE_PAYWALL_SLUG);
	}

	public function admin_menu_separator_styles() {
		?>
        <style>
            .emoxie-admin-separator-container{display:flex;height:12px;align-items:center;margin:0 -10px 0 0;}.emoxie-admin-separator-container .emoxie-admin-separator-title{font-size:.68em;text-transform:uppercase;font-weight:700;margin-right:10px;color:hsla(0,0%,100%,.25);}.emoxie-admin-separator-container .emoxie-admin-separator{display:block;flex:1;padding:0;height:1px;line-height:1px;background:hsla(0,0%,100%,.125);}
        </style>
		<?php
	}

	public function create_options_page() {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html( 'You do not have sufficient permissions to access this page.' ) );
		}
		wp_enqueue_style( EXPANDABLE_PAYWALL_SLUG . '_admin' );
		wp_enqueue_style( EXPANDABLE_PAYWALL_SLUG . '_select2_css' );
		wp_enqueue_script( EXPANDABLE_PAYWALL_SLUG . '_admin' );
		wp_enqueue_script( EXPANDABLE_PAYWALL_SLUG . '_select2_js' );

		require_once EXPANDABLE_PAYWALL_PATH . 'admin/partials/settings.php';
	}

	public function create_log_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html( 'You do not have sufficient permissions to access this page.' ) );
		}
		wp_enqueue_style( EXPANDABLE_PAYWALL_SLUG . '_admin' );
		wp_enqueue_style( EXPANDABLE_PAYWALL_SLUG . '_datatables_core' );
		wp_enqueue_script( EXPANDABLE_PAYWALL_SLUG . '_datatables_core' );
		wp_enqueue_script( EXPANDABLE_PAYWALL_SLUG . '_datatables' );
		require_once EXPANDABLE_PAYWALL_PATH . 'admin/partials/log.php';
	}


	public function plugin_settings_link($links) {
		$links[] = '<a href="' . admin_url( 'admin.php?page=' . EXPANDABLE_PAYWALL_SLUG . '-settings' ) . '">' . __( 'Settings', 'expandable-paywall' ) . '</a>';
		return $links;
	}

	public function prefix_plugin_update_message( $data, $response ) {
		if ( isset( $data['upgrade_notice'] ) ) {
			printf( '<div class="update-message">%s</div>', esc_html( wpautop( $data['upgrade_notice'] ) ) );
		}
	}

	/**
	 * Called by using the expandable-paywall_authentication_roles action
	 */
	public function output_authentication_roles() {
		require_once EXPANDABLE_PAYWALL_PATH . 'admin/partials/settings-authentication-roles.php';
	}

	public function output_paywall_settings() {
		$paywall_type = get_option( EXPANDABLE_PAYWALL_SLUG . '_paywall_type' );
		if ( Helper::$default_paywall_type === $paywall_type ) {
			require_once EXPANDABLE_PAYWALL_PATH . 'admin/partials/settings-paywall-basic.php';
		}
	}

	private function create_options() {
		register_setting( EXPANDABLE_PAYWALL_SLUG . '_options', EXPANDABLE_PAYWALL_SLUG . '_paywall_type', [ 'type' => 'string', 'default' => 'basic' ] );
		register_setting( EXPANDABLE_PAYWALL_SLUG . '_options', EXPANDABLE_PAYWALL_SLUG . '_authentication_type', [ 'type' => 'string', 'default' => 'wordpress' ] );
		register_setting( EXPANDABLE_PAYWALL_SLUG . '_options', EXPANDABLE_PAYWALL_SLUG . '_enabled', [ 'type' => 'boolean', 'default' => 0 ] );

		register_setting( EXPANDABLE_PAYWALL_SLUG . '_paywall', EXPANDABLE_PAYWALL_SLUG . '_paywall_basic_include_categories' );
		register_setting( EXPANDABLE_PAYWALL_SLUG . '_paywall', EXPANDABLE_PAYWALL_SLUG . '_paywall_basic_paywall_content', [ 'type' => 'string', 'default' => _x( 'To continue reading this article you must become a subscriber.', 'expandable-paywall' ) ] );
		register_setting( EXPANDABLE_PAYWALL_SLUG . '_paywall', EXPANDABLE_PAYWALL_SLUG . '_paywall_basic_post_types' );
		register_setting( EXPANDABLE_PAYWALL_SLUG . '_paywall', EXPANDABLE_PAYWALL_SLUG . '_paywall_show_locks', [ 'default' => 0 ] );
		register_setting( EXPANDABLE_PAYWALL_SLUG . '_paywall', EXPANDABLE_PAYWALL_SLUG . '_paywall_show_fade', [ 'default' => 0 ] );
		register_setting( EXPANDABLE_PAYWALL_SLUG . '_paywall', EXPANDABLE_PAYWALL_SLUG . '_paywall_enable_structured_data', [ 'default' => 0 ] );

		register_setting( EXPANDABLE_PAYWALL_SLUG . '_authentication', EXPANDABLE_PAYWALL_SLUG . '_authentication_role_non_paid' );
		register_setting( EXPANDABLE_PAYWALL_SLUG . '_authentication', EXPANDABLE_PAYWALL_SLUG . '_authentication_role_paid', [ 'type' => 'string', 'default' => 'subscriber' ] );

		register_setting( EXPANDABLE_PAYWALL_SLUG . '_advanced', EXPANDABLE_PAYWALL_SLUG . '_enable_debug', [ 'default' => 0 ] );

	}

	private function create_paid_user_role() { //TODO this needs to be fixed and only add this role when using metered paywall or when an addon specifies it.  I.E this should be removed from core and added to addons only.
		add_role( 'paid_subscriber', __( 'Paid Subscriber', 'expandable-paywall' ), [
			'read'    => true,
			'level_0' => true,
		] );
	}

	protected function all_post_types(): array {
		return get_post_types( [ 'public' => true ] );
	}

	/**
	 * @return bool
     * @deprecated 2.0.20 Use Emoxie\Expandable_Paywall\Helper\is_admin_user()
 */
	public function is_admin(): bool {
		_deprecated_function( __FUNCTION__, '2.1.0', 'Emoxie\Expandable_Paywall\Helper\is_admin_user()' );
		return Helper::is_admin_user();
	}

	/**
	 * @return array
     * @deprecated 2.0.20 Use Emoxie\Expandable_Paywall\Helper\get_admin_users()
 */
	private function get_admin_users(): array {
		_deprecated_function( __FUNCTION__, '2.1.0', 'Emoxie\Expandable_Paywall\Helper\get_admin_users()' );
		return Helper::get_admin_users();

	}


	/**
	 * Function performs local authentication.
	 *
	 * @deprecated 2.0.20 Use Emoxie\Expandable_Paywall\Helper\local_authentication()
	 */
    public function local_authentication() {
		_deprecated_function( __FUNCTION__, '2.1.0', 'Emoxie\Expandable_Paywall\Helper\local_authentication()' );
        return Helper::local_authentication();
	}

	public function setup_bypass_link_meta_box() {
		add_action( 'add_meta_boxes', [ $this, 'add_bypass_link_meta_box' ] );
		add_action( 'save_post', [ $this, 'handle_bypass_link_save_post' ] );
	}

	public function add_bypass_link_meta_box() {
		add_meta_box(
			'bypass_link',      // Unique ID
			esc_html__( 'Paywall Bypass Link', 'expandable-paywall' ),
			[ $this, 'display_meta_box' ],
			'post',
			'side',
			'default'
		);
	}

	public function handle_bypass_link_save_post( $post_id ) {
		if ( get_post_type( $post_id ) !== 'post' ) {
			return;
		}

		$meta_key    = 'bypass_code';
		$bypass_code = get_post_meta( $post_id, $meta_key );

		if ( count( $bypass_code ) > 0 ) {
			return;
		}

		$unique_bypass_code = uniqid();
		add_post_meta( $post_id, $meta_key, $unique_bypass_code, true );
	}


	public function display_meta_box( $object ) {
		$bypass_code = get_post_meta( $object->ID, 'bypass_code', true );

		if ( empty( $bypass_code ) ) {
			echo '<p>You need to save this post before a bypass link will be generated.</p>';

			return;
		}

		$link          = get_the_permalink( $object->ID ) . '?bypass=' . $bypass_code;
		$messageFormat = '<p>The link for this post to bypass the paywall is: <br>' .
		                 '<pre style="overflow:auto; border:1px dashed #ccc; padding:3px;">%s</pre></p>';

		printf( $messageFormat, esc_html( $link ) );
	}

	public function my_ajax_getpostsfordatatables() {
		global $wpdb;
		$table_name = $wpdb->prefix . 'expandable_paywall_log';

		$items_per_page = 50;
		$total          = $wpdb->get_var( "SELECT COUNT(1) FROM " . $table_name );
		$page           = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;

		// Calculate offset
		$offset = ( $page * $items_per_page ) - $items_per_page;

		// Adjust items per page if total is less than items per page
		$items_per_page = min( $items_per_page, $total );

		$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `%s` ORDER BY `id` DESC LIMIT %d, %d", $table_name, $offset, $items_per_page ) );

		$return_json = $rows;

		echo json_encode( [ 'data' => $return_json ] );
		wp_die();
	}

	public function ajax_getlogs() {
		if ( ! check_ajax_referer( 'exp_get_logs', 'nonce' ) ) {
			wp_send_json_error( 'Invalid security token sent.' );
		}

		global $wpdb;

		$table   = $wpdb->prefix . 'expandable_paywall_log';
		$columns = [
			[ 'db' => 'id', 'dt' => 0 ],
			[ 'db' => 'post_id', 'dt' => 1 ],
			[ 'db' => 'user_id', 'dt' => 2 ],
			[ 'db' => 'action', 'dt' => 3 ],
			[ 'db' => 'data', 'dt' => 4 ],
			[ 'db' => 'user_agent', 'dt' => 5 ],
			[ 'db' => 'created_at', 'dt' => 6 ],
		];

		$sql_details = [
			'user'    => DB_USER,
			'pass'    => DB_PASSWORD,
			'db'      => DB_NAME,
			'host'    => str_replace( 'p:', '', DB_HOST ),
			'charset' => 'utf8',
		];

		$response = SSP::simple( $_GET, $sql_details, $table, 'id', $columns );

		wp_send_json( $response ); // This function handles both echoing the result and wp_die().
	}

	public function ajax_clear_logs() {
		if ( ! check_ajax_referer( 'exp_clear_logs', 'nonce' ) ) {
			wp_send_json_error( 'Invalid security token sent.' );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'You do not have permission to perform this action.' );
		}

		global $wpdb;

		$table = $wpdb->prefix . 'expandable_paywall_log';
		$wpdb->query( "TRUNCATE TABLE $table" );

		wp_send_json( 'success', 200 );
	}


}