<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://onexgen.com
 * @since      1.0.0
 *
 * @package    Mpwa_Notifications
 * @subpackage Mpwa_Notifications/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    Mpwa_Notifications
 * @subpackage Mpwa_Notifications/admin
 * @author     Magd Almuntaser <info@onexgen.com>
 */

class Mpwa_Notifications_Admin {

	private $mpwa_notifications;

	private $version;
    private $loader;

    private $page_url;
    private $menu_title;

    private $mpwa_db;

	public function __construct( $mpwa_notifications, $version, $loader ) {

		$this->mpwa_notifications = $mpwa_notifications;
		$this->version = $version;
        $this->loader = $loader;
        $this->page_url = 'mpwa-notifications';
        $this->menu_title = 'MPWA Notify';

        include_once plugin_dir_path( __FILE__ ) . 'class-mpwa-notifications-admin-db.php';
        $mpwa_db = new Mpwa_Notifications_Admin_Db( $mpwa_notifications, $version );
        $this->mpwa_db = $mpwa_db;
	}

	public function enqueue_styles() {
		wp_enqueue_style('dashicons');
		wp_enqueue_style( $this->mpwa_notifications, plugin_dir_url( __FILE__ ) . 'css/mpwa-notifications-admin.css', array(), $this->version, 'all' );

	}

	public function enqueue_scripts() {
		$base = plugin_dir_url(__FILE__) . 'js/';

		wp_register_script('mpwa-emoji-picker', $base . 'emoji/picker.min.js', array(), $this->version, true);
		wp_register_script('mpwa-notifications-admin', $base . 'mpwa-notifications-admin.js', array('jquery', 'mpwa-emoji-picker'), $this->version, true);

		add_filter('script_loader_tag', array($this, 'script_type_module'), 10, 3);

		wp_enqueue_script('mpwa-emoji-picker');
		wp_enqueue_script('mpwa-notifications-admin');

		wp_localize_script('mpwa-notifications-admin', 'mpwa_ajax_obj', array(
			'ajax_url' => admin_url('admin-ajax.php'),
			'nonce' => wp_create_nonce('mpwa_ajax_nonce')
		));
	}

	public function script_type_module($tag, $handle, $src) {
		if ('mpwa-emoji-picker' === $handle) {
			$tag = str_replace(' src=', ' type="module" src=', $tag);
		}
		return $tag;
	}

    private function get_menu_title($menu) {
        return $menu . ' - ' . $this->menu_title;
    }

    private function get_menu_url($menu = null) {
        switch ($menu) {
            case 'options':
                return $this->page_url . '-options';
                break;

            default:
                return $this->page_url;
                break;
        }
    }

    private function get_template_contents() {
        $templates = [
            [
                'title' => 'Order Pending',
                'code' => 'WC_ORDER_PENDING'
            ],
            [
                'title' => 'Order Processing',
                'code' => 'WC_ORDER_PROCESSING'
            ],
            [
                'title' => 'Order On Hold',
                'code' => 'WC_ORDER_ON_HOLD'
            ],
            [
                'title' => 'Order Completed',
                'code' => 'WC_ORDER_COMPLETED'
            ],
            [
                'title' => 'Order Canceled',
                'code' => 'WC_ORDER_CANCELED'
            ],
            [
                'title' => 'Order Refunded',
                'code' => 'WC_ORDER_REFUNDED'
            ],
            [
                'title' => 'Order Failed',
                'code' => 'WC_ORDER_FAILED'
            ]
        ];

        return $templates;
    }

    function callback_menu_main_view() {

        $req_edit_template_code = '';
		if ( isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'mpwa_edit_template') ) {
			$req_edit_template_code = isset($_GET['template_code']) ? sanitize_text_field(wp_unslash($_GET['template_code'])) : '';
		}
        $template_contents = $this->get_template_contents();

        if (!empty($req_edit_template_code)) {
            $current_content = array_filter($template_contents, function($val) use ($req_edit_template_code) {
                return $val['code'] == $req_edit_template_code;
            });
            $current_content = array_shift($current_content);
            $current_content_db = $this->mpwa_db->get_content($req_edit_template_code);

            include_once plugin_dir_path( __FILE__ ) . 'class-mpwa-notifications-admin-shortcode.php';
            $shortcode = new Mpwa_Notifications_Admin_Shortcode( $this->mpwa_notifications, $this->version );
            $wc_shortcodes = $shortcode->get_wc_shortcodes();

            if ( is_file( plugin_dir_path( __FILE__ ) . 'partials/page_edit_template.php' ) ) {
                include_once plugin_dir_path( __FILE__ ) . 'partials/page_edit_template.php';
            }
        }else{
            $mpwa_db = $this->mpwa_db;
            $mpwa_options = get_option( 'mpwa_notifications_options' );
            if ( is_file( plugin_dir_path( __FILE__ ) . 'partials/menu_main.php' ) ) {
                include_once plugin_dir_path( __FILE__ ) . 'partials/menu_main.php';
            }
        }
    }

    public function register_menu_page() {
        add_menu_page(
            'MPWA WP Notif',
            $this->menu_title,
            'manage_options',
            $this->get_menu_url(),
            array($this, 'callback_menu_main_view'),
            'dashicons-whatsapp',
            null
        );
    }

    public function register_submenu_main_page() {
        add_submenu_page(
            $this->page_url,
            $this->get_menu_title('General'),
            'General',
            'manage_options',
            $this->get_menu_url(),
            array($this, "callback_menu_main_view"),
            null
        );
    }

    function callback_submenu_options_view() {
        if ( is_file( plugin_dir_path( __FILE__ ) . 'partials/menu_options.php' ) ) {
            include_once plugin_dir_path( __FILE__ ) . 'partials/menu_options.php';
        }
    }

    public function register_submenu_options_page() {
        add_submenu_page(
            $this->page_url,
            $this->get_menu_title('Options'),
            'Options',
            'manage_options',
            $this->get_menu_url('options'),
            array($this, 'callback_submenu_options_view')
        );
    }
	
	public function sanitize_options($options){
		$sanitized = array();

		if (isset($options['mpwa_notifications_field_secret_key'])) {
			$sanitized['mpwa_notifications_field_secret_key'] = sanitize_text_field($options['mpwa_notifications_field_secret_key']);
		}
		if (isset($options['mpwa_notifications_field_sender_number'])) {
			$sanitized['mpwa_notifications_field_sender_number'] = sanitize_text_field($options['mpwa_notifications_field_sender_number']);
		}
		if (isset($options['mpwa_notifications_field_api_link'])) {
			$sanitized['mpwa_notifications_field_api_link'] = esc_url_raw($options['mpwa_notifications_field_api_link']);
		}
		if (isset($options['mpwa_notifications_field_footer'])) {
			$sanitized['mpwa_notifications_field_footer'] = sanitize_text_field($options['mpwa_notifications_field_footer']);
		}

		add_settings_error('mpwa_notifications_main_messages','mpwa_notifications_updated',__('Settings Saved','mpwa-notifications'),'updated');
		return $sanitized;
	}

    public function form_options_init() {

        register_setting(
			'mpwa_notifications_form_options',
			'mpwa_notifications_options',
			array(
				'sanitize_callback' => array($this, 'sanitize_options')
			)
		);

        add_settings_section(
            'mpwa_notifications_section_credential',
            __( 'Configuration Credential', 'mpwa-notifications' ),
            array($this, 'mpwa_notifications_section_credential_callback'),
            $this->get_menu_url('options')
        );

        add_settings_field(
            'mpwa_notifications_field_secret_key', 
            __( 'API Key', 'mpwa-notifications' ), 
            array($this, 'mpwa_notifications_field_secret_key_cb'),
            $this->get_menu_url('options'),
            'mpwa_notifications_section_credential', 
            array(
                'label_for'         => 'mpwa_notifications_field_secret_key',
                'class'             => 'mpwa_notifications_row',
                'mpwa_notifications_custom_data' => 'custom',
            )
        );
		
		add_settings_field(
			'mpwa_notifications_field_sender_number',
			__( 'Sender Number', 'mpwa-notifications' ),
			array($this, 'mpwa_notifications_field_sender_number_cb'),
			$this->get_menu_url('options'),
			'mpwa_notifications_section_credential',
			array(
				'label_for' => 'mpwa_notifications_field_sender_number',
				'class' => 'mpwa_notifications_row',
				'mpwa_notifications_custom_data' => 'custom',
			)
		);

		add_settings_field(
			'mpwa_notifications_field_api_link',
			__( 'API Link (MPWA)', 'mpwa-notifications' ),
			array($this, 'mpwa_notifications_field_api_link_cb'),
			$this->get_menu_url('options'),
			'mpwa_notifications_section_credential',
			array(
				'label_for' => 'mpwa_notifications_field_api_link',
				'class' => 'mpwa_notifications_row',
				'mpwa_notifications_custom_data' => 'custom',
			)
		);

		add_settings_field(
			'mpwa_notifications_field_footer',
			__( 'Footer', 'mpwa-notifications' ),
			array($this, 'mpwa_notifications_field_footer_cb'),
			$this->get_menu_url('options'),
			'mpwa_notifications_section_credential',
			array(
				'label_for' => 'mpwa_notifications_field_footer',
				'class' => 'mpwa_notifications_row',
				'mpwa_notifications_custom_data' => 'custom',
			)
		);
    }

    public function mpwa_notifications_section_credential_callback($args) {
        ?>
            <p id="<?php echo esc_attr( $args['id'] ); ?>">
                <?php esc_html_e( 'Please enter the Api Key from your (MPWA) site. If you do not have one, please register and set up your WhatsApp account as the message sender.', 'mpwa-notifications' ); ?>
            </p>
        <?php
    }

    public function mpwa_notifications_field_secret_key_cb( $args ) {

        $options = get_option( 'mpwa_notifications_options' );
        $options_value = !empty($options) ? $options[ $args['label_for'] ] : null;

        ?>
        <input
            type="text"
            id="<?php echo esc_attr( $args['label_for'] ); ?>"
            data-custom="<?php echo esc_attr( $args['mpwa_notifications_custom_data'] ); ?>"
            name="mpwa_notifications_options[<?php echo esc_attr( $args['label_for'] ); ?>]"
            value="<?php echo esc_attr( $options_value )  ?>"
            style="width: 50%"
        >
        <p class="description" style="font-size: 12px; padding: 0 0 0 3px;">
            Get the Api Key from the <b>Setting</b> -> <b>API Key</b> In the right menu at the top of your (MPWA) site.
        </p>
        <?php
    }
	
	public function mpwa_notifications_field_sender_number_cb( $args ) {
		$options = get_option( 'mpwa_notifications_options' );
		$value = !empty($options) ? @$options['mpwa_notifications_field_sender_number'] : '';
		?>
		<input type="text" id="mpwa_notifications_field_sender_number" name="mpwa_notifications_options[mpwa_notifications_field_sender_number]" value="<?php echo esc_attr($value); ?>" style="width: 50%" placeholder="+62">
		<?php
	}

	public function mpwa_notifications_field_api_link_cb( $args ) {
		$options = get_option( 'mpwa_notifications_options' );
		$value = !empty($options) ? @$options['mpwa_notifications_field_api_link'] : '';
		?>
		<input type="text" id="mpwa_notifications_field_api_link" name="mpwa_notifications_options[mpwa_notifications_field_api_link]" value="<?php echo esc_attr($value); ?>" style="width: 50%" placeholder="https://mpwa.yoursite.com">
		<?php
	}

	public function mpwa_notifications_field_footer_cb( $args ) {
		$options = get_option( 'mpwa_notifications_options' );
		$value = !empty($options) ? @$options['mpwa_notifications_field_footer'] : '';
		?>
		<input type="text" id="mpwa_notifications_field_footer" name="mpwa_notifications_options[mpwa_notifications_field_footer]" value="<?php echo esc_attr($value); ?>" style="width: 50%" placeholder="Ex: --Bot">
		<?php
	}

    public function register_handle_form_template(){
        include_once plugin_dir_path( __FILE__ ) . 'class-mpwa-notifications-admin-form-template.php';

        $form_template = new Mpwa_Notifications_Admin_Form_Template( $this->mpwa_notifications, $this->version );
        $form_template->handle_submit_edit_template();
    }

    public function mpwa_notifications_admin_notices() {
		if (
			isset($_GET['mpwa_notifications_status'], $_GET['_wpnonce']) &&
			'success' === sanitize_text_field(wp_unslash($_GET['mpwa_notifications_status'])) &&
			wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'mpwa_edit_template')
		) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Options saved successfully.', 'mpwa-notifications') . '</p></div>';
		}
	}

    public function register_handle_ajax_status_template(){
        include_once plugin_dir_path( __FILE__ ) . 'class-mpwa-notifications-admin-form-template.php';

        $form_template = new Mpwa_Notifications_Admin_Form_Template( $this->mpwa_notifications, $this->version );
        $form_template->handle_ajax_status_template();
    }

    public function register_wc_hooks(){
        include_once plugin_dir_path( __FILE__ ) . 'class-mpwa-notifications-admin-wc-hook.php';

        $wc = new Mpwa_Notifications_Admin_Wc_Hook( $this->mpwa_notifications, $this->version, $this->loader, $this->mpwa_db );
        $wc->register_hooks();
    }
}