<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://autoserve.io
 * @since      1.0.0
 *
 * @package    Messageflow
 * @subpackage Messageflow/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    Messageflow
 * @subpackage Messageflow/admin
 * @author     Autoserve <support@autoserve.io>
 */
class Messageflow_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;

	/**
	 * The helper functions.
	 *
	 * @since   1.0.4
	 * @access  private
	 * @var     string      $utils      The helper functions of this plugin
	 */
	private $utils;

	/**
	 * MessageFlow API functions.
	 *
	 * @since   1.1.2.2
	 * @access  private
	 * @var     string      $utils      The helper functions of this plugin
	 */
    private $api;

	/**
	 * 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.
	 */
	public function __construct( $plugin_name, $version, $utils, $api ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;
		$this->utils = $utils;
        $this->api = $api;

		add_filter( 'admin_footer_text', '__return_empty_string', 11 );
		add_filter( 'update_footer', '__return_empty_string', 11 );
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/messageflow-admin.css' );

	}

	/**
	 * Enqueue scripts for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {
		$screen = get_current_screen();

		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/messageflow-admin.js', array( 'jquery' ), $this->version, false );

		$account_sid = get_option( 'messageflow-settings-account-sid' );
		$auth_token = get_option( 'messageflow-settings-auth-token' );
		$from_phone = get_option( 'messageflow-settings-from-phone' );

		$user_id = get_option( 'messageflow-user-id' );

		if ( is_object( $screen ) ) {
			$is_valid_account = $this->api->check_account_status( $user_id );

			if ( $screen->post_type === 'shop_order' ) {
				$order_id = get_the_ID();
				$order = wc_get_order( $order_id );

				if ( $order ) {
					$billing_first_name = $order->get_billing_first_name();
					$billing_last_name = $order->get_billing_last_name();
					$billing_phone = $order->get_billing_phone();

					$this->enqueue_react_files(
						'order-sms-app',
						true,
						'adminOrderSmsAppContext',
						array(
							'billingFirstName'      => $billing_first_name,
							'billingLastName'       => $billing_last_name,
							'billingPhone'          => $billing_phone,
							'orderNumber'           => $order_id,
							'nonce'                 => wp_create_nonce( 'wp_rest' ),
							'accountSid'            => $account_sid,
							'authToken'             => $auth_token,
							'fromPhone'             => $from_phone,
                            'isValidAccount'        => $is_valid_account
						),
						'messageflow-admin-order-sms-'
					);
				}
			}

			$this->enqueue_react_files(
				'admin-ui',
				true,
				'adminUiAppContext',
				array(
					'accountSid'            => $account_sid,
					'authToken'             => $auth_token,
					'version'               => MESSAGEFLOW_VERSION,
					'shopName'              => $this->utils->get_site_name(),
					'fromPhone'             => $from_phone,
					'orderStatuses'         => $this->utils->woocommerce_get_all_order_statuses(),
					'nonce'                 => wp_create_nonce( 'wp_rest' ),
					'roles'                 => $this->utils->get_all_roles(),
					'isValidAccount'        => $is_valid_account
				),
				'messageflow-admin-ui-'
			);
		}
	}

	/**
	 * Enqueue React scripts and styles
	 *
	 * @since    1.0.3
	 */
    private function enqueue_react_files( $app_dir, $has_localize_script, $localized_script_name, $localized_script_data, $file_name_prefixes ) {
	    $manifest_path = MESSAGEFLOW_PLUGIN_PATH . '/admin/apps/' . $app_dir . '/asset-manifest.json';

	    $request = file_get_contents( $manifest_path );

	    if ( ! $request ) {
		    add_settings_error( 'failed-to-load', '', 'App failed to render. Cannot get content.' , 'error' );
		    settings_errors( 'failed-to-load' );
		    return false;
	    }

	    $files_data = json_decode( $request );
	    if ( $files_data === null ) {
		    return;
	    }

	    if (! property_exists( $files_data, 'entrypoints' )) {
		    return false;
	    }

	    $assets_files = $files_data->entrypoints;

	    $js_files = array_filter( $assets_files, array( $this, 'filter_js_files' ) );
	    $css_files = array_filter( $assets_files, array( $this, 'filter_css_files' ) );

	    // Load css files.
	    foreach ($css_files as $index => $css_file){
		    wp_enqueue_style( $file_name_prefixes.$index, plugin_dir_url( __FILE__ ) . 'apps/' . $app_dir . '/' . $css_file );
	    }

	    // Load js files.
	    foreach ($js_files as $index => $js_file){
		    wp_enqueue_script( $file_name_prefixes.$index, plugin_dir_url( __FILE__ ) . 'apps/' . $app_dir . '/' . $js_file, array(), null, true );
	    }

	    // window object to store Twilio credentials
	    if ($has_localize_script && is_admin() && user_can_access_admin_page()) {
		    wp_localize_script( $file_name_prefixes . '0', $localized_script_name, $localized_script_data );
		    wp_localize_script( $file_name_prefixes . '1', $localized_script_name, $localized_script_data );
	    }
    }

	/**
	 * Get js files from assets array
	 *
	 * @since    1.0.3
	 */
	private function filter_js_files ( $file_string ) {
		return pathinfo( $file_string, PATHINFO_EXTENSION ) === 'js';
	}

	/**
	 * Get css files from assets array
	 *
	 * @since    1.0.3
	 */
	private function filter_css_files ( $file_string ) {
		return pathinfo( $file_string, PATHINFO_EXTENSION ) === 'css';
	}

	/**
	 * Create admin menu tabs and sub-tabs
	 *
	 * @since    1.0.0
	 */
	public function messageflow_init_menu() {
		$tab_icon = MESSAGEFLOW_PLUGIN_URL . 'assets/WooSent-logo.svg';

		add_menu_page( 'MessageFlow', 'MessageFlow', 'can_view_messageflow', 'messageflow', array( $this, 'messageflow_admin_react_page' ), $tab_icon, 65 );
		add_submenu_page( 'messageflow', 'Settings', 'Settings', 'can_view_messageflow', 'messageflow', array( $this, 'messageflow_admin_react_page' ) );
		add_submenu_page( 'messageflow', 'Campaigns', 'Campaigns', 'can_view_messageflow', 'messageflow_campaigns', array( $this, 'messageflow_admin_react_page' ) );
	}

	/**
	 * Template callback function for React Admin UI
	 *
	 * @since    1.0.0
	 */
	public function messageflow_admin_react_page() {
		printf(
			'<div class="%1$s"><div id="%2$s"></div></div>',
			esc_attr( 'wrap' ),
			esc_html( 'messageflow-react-app' )
		);
	}

	/**
	 * Action callback function to hide admin notices on plugin's screens
	 *
	 * @since    1.0.6
	 */
	public function messageflow_hide_admin_notices() {
		$screen = get_current_screen();

		// Check whether the admin screen belongs to this plugin
		if ( strpos( $screen->base, 'messageflow' ) !== false ) {
			?>
				<style>
					.notice{display:none !important}
				</style>
			<?php
		}
	}

	/**
	 * Action callback function to add capability to view the plugin on admin init
	 *
	 * @since    1.0.7
	 */
public function messageflow_init() {
		$visibility_permission = get_option( 'messageflow-settings-visibility-permission' );

		$roles = $this->utils->get_all_roles();
		$roles_slug = array_keys( $roles );

		foreach ( $roles_slug as $slug ) {
			$role = get_role( $slug );

			if ( in_array( $slug, $visibility_permission ) ) {
				$role->add_cap( 'can_view_messageflow', true );
			} else {
				$role->remove_cap( 'can_view_messageflow' );
			}
		}
	}

	/**
	 * Filter callback function to enable order notification by default on manual order creation
	 *
	 * @since    1.0.9
	 */
	public function messageflow_insert_post( $post_id, $post, $update ) {
		if ( $update ) {
			return;
		}

		$post_type = get_post_type( $post_id );

		if ( $post_type === 'shop_order' ) {
			update_post_meta( $post_id, 'messageflow_order_noti_is_subscribed', 1 );
		}
	}

	/**
	 * Action callback function to render admin notice when test mode is ON
	 *
	 * @since    1.0.9
	 */
	public function messageflow_admin_notices() {
		$is_test_mode_enabled = get_option( 'messageflow-settings-enable-test-mode' );

		if ( $is_test_mode_enabled === 'true' ) {
			printf(
				'<div class="%1$s"><p><b>%2$s</b>%3$s<a href="%4$s" target="_blank" rel="noreferrer">%5$s</a></p></div>',
				esc_attr( 'notice notice-warning is-dismissible' ),
				esc_html( 'Important: ' ),
				esc_html( 'MessageFlow is currently in test mode. A real SMS message will not be sent when test mode is on. ' ),
				esc_url( 'https://messageflow.co' ),
				esc_html( 'Read More' )
			);
		}
	}

}
