<?php
/**
 * Setup menus in emc admin.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

if ( ! class_exists( 'emc_admin_notices' ) ) :

/**
 * emc_admin_notices Class
 */
class emc_admin_notices {
    
    /**
	 * Stores notices.
	 * @var array
	 */
	private static $notices = array();
    
    /**
	 * Array of notices - name => callback.
	 * @var array
	 */
	private static $core_notices = array(
		'install' => 'show_install_notice',
		'update' => 'show_update_notice',
	);
    
	/**
	 * Constructor.
	 */
	public static function init() {
        self::$notices = get_option( 'EMC_NOTICES', array() );
        
		add_action( 'shutdown', array( __CLASS__, 'store_notices' ) );

        add_action( 'admin_print_styles', array( __CLASS__, 'add_notices' ) );
        
        add_action( 'wp_ajax_hide_notice', array( __CLASS__, 'hide_notice_callback'));
	}
    
    /**
	 * Store notices to DB
	 */
	public static function store_notices() {
		update_option( 'EMC_NOTICES', self::get_notices() );
	}
    
    /**
	 * Get notices
	 * @return array
	 */
	public static function get_notices() {
		return self::$notices;
	}
    
    /**
	 * Get 'news' type notices only
	 * @return array
	 */
	public static function get_news() {
        $notices = self::get_notices();
        $news = array();
        
        foreach ($notices as $id) {
            if ( empty( self::$core_notices[ $id ] ) ) {
                $notice = get_option("EMC_NOTICE_".$id);
                if ($notice['type'] == 'news') {
                    $news[$id] = $notice;
                }
            }
        }
        
		return $news;
	}
	
	/**
	 * Remove all notices except news.
	 */
	public static function remove_all_notices() {
        foreach (self::$notices as $id) {
            if ( empty( self::$core_notices[ $id ] ) ) {
                $notice = get_option('EMC_NOTICE_'.$id);
                if (false !== $notice && isset($notice['type']) && $notice['type'] != 'news') {
                    unset(self::$notices[$id]);
                }
            } else {
                unset(self::$notices[$id]);
            }
        }
	}

    /**
	 * Show a notice.
	 * @param string $id unique identifier such as core notice key or md5 for custom notices
	 */
	public static function add_notice( $id ) {
		self::$notices = array_unique( array_merge( self::get_notices(), array( $id ) ) );
	}
	
    /**
	 * Remove a notice from being displayed.
	 * @param string $id unique identifier such as core notice key or md5 for custom notices
	 */
	public static function remove_notice( $id ) {
		self::$notices = array_diff( self::get_notices(), array( $id ) );
		delete_option( 'EMC_NOTICE_' . $id );
	}
    
    /**
	 * See if a notice is being shown.
	 * @param  string  $name
	 * @return boolean
	 */
	public static function has_notice( $name ) {
		return in_array( $name, self::get_notices() );
	}
    
    /**
	 * Add notices + styles if needed.
	 */
	public static function add_notices() {
		$notices = self::get_notices();

		if ( ! empty( $notices ) ) {
			foreach ( $notices as $notice ) {
				if ( ! empty( self::$core_notices[ $notice ] ) ) {
					add_action( 'admin_notices', array( __CLASS__, self::$core_notices[ $notice ] ) );
				} else {
					add_action( 'admin_notices', array( __CLASS__, 'output_custom_notices' ) );
				}
			}
		}
	}
    
    /**
	 * Add a custom notice.
	 * @param string $id a unique identifier (md5 for custom notices)
	 * @param string $notice_html
	 */
	public static function update_custom_notice( $id, $notice ) {
		update_option( 'EMC_NOTICE_' . $id, $notice );
	}
    
    /**
	 * Updates a custom notice.
	 * @param string $id a unique identifier (md5 for custom notices)
	 * @param string $notice_html
	 */
	public static function add_custom_notice( $id, $notice ) {
        self::add_notice( $id );
		update_option( 'EMC_NOTICE_' . $id, $notice );
	}
    
    /**
	 * Output any stored custom notices.
	 */
	public static function output_custom_notices() {
        global $pagenow;
        global $post_type;
        
		$notices = self::get_notices();

		if ( ! empty( $notices ) ) {
			foreach ( $notices as $id ) {
				if ( empty( self::$core_notices[ $id ] ) ) {
                    $notice = get_option("EMC_NOTICE_".$id);
                    
                    if (!isset($notice['type'])) {
                        continue;
                    }
                    
					switch ($notice['type']) {
                        case 'news':
                            // news will only appear on order pages and module pages
                            if($post_type == 'shop_order'
                                || ($pagenow == 'admin.php' && isset($_GET['page'])
                                && ($_GET['page'] == 'envoimoinscher-settings' || ($_GET['page'] == 'wc-settings' && isset($_GET['tab']) && $_GET['tab'] == 'shipping')))) {
                                
                                // if not same language, continue
                                $language = get_locale();
                                if ($notice['language'] != $language) {
                                    break;
                                }
                                
                                // if dismissed, continue
                                if ($notice['show'] === false) {
                                    break;
                                }
                                
                                // get EMC logo if language is french, otherwise get boxtal logo
                                if (strtolower(substr($language, 0, 2)) == 'fr') {
                                    $img = '/assets/img/logo_fr.png';
                                } else {
                                    $img = '/assets/img/logo_oth.png';
                                }

                                $logo = (isset($_GET['page']) && 'envoimoinscher-settings' == $_GET['page']) ? false : true;
                            
                                include( EMC()->plugin_path() . '/assets/views/html-notice-'.$notice['type'].'.php' );
                            }
                            break;
                        
                        default:
                            include( EMC()->plugin_path() .'/assets/views/html-notice-'.$notice['type'].'.php' );
                            break;
                    }
                    
                    // autodestruct means that notices will only be shown once
                    if (isset($notice['autodestruct']) && $notice['autodestruct'] == 1) {
                        self::remove_notice($id);
                    }
				}
			}
		}
	}
    
    /**
	 * If we need to update, include a message with the update button.
	 */
	public static function show_update_notice() {
        $language = get_locale();

        // get EMC logo if language is french, otherwise get boxtal logo
        if (strtolower(substr($language, 0, 2)) == 'fr') {
            $img = '/assets/img/logo_fr.png';
        } else {
            $img = '/assets/img/logo_oth.png';
        }

        $logo = (isset($_GET['page']) && 'envoimoinscher-settings' == $_GET['page']) ? false : true;

		if ( version_compare( get_option( 'EMC_DB_VERSION' ), EMC_VERSION, '<' ) ) {
			$updater = new EMC_Background_Updater();
			if ( $updater->is_updating() || ! empty( $_GET['do_update_envoimoinscher'] ) ) {
				include( EMC()->plugin_path() . '/assets/views/html-notice-updating.php' );
			} else {
                include( EMC()->plugin_path() . '/assets/views/html-notice-update.php' );
			}
		} else {
            include( EMC()->plugin_path() . '/assets/views/html-notice-updated.php' );
            
		}
	}
    
    /**
	 * If we have just installed, show a message with the install pages button.
	 */
	public static function show_install_notice() {
		include( EMC()->plugin_path() .  '/assets/views/html-notice-install.php' );
	}
    
    /**
	 * Get 'news' unique identifier
	 * @return array
	 */
	public static function get_news_md5($news_item) {
		return md5($news_item['type'].$news_item['message'].$news_item['message_short']);
	}
    
    /**
     * Ajax callback to hide a notice
     */
    public static function hide_notice_callback() {
        check_ajax_referer( 'boxtale_emc', 'security' );
        $id = $_POST['id'];
        self::hide_notice($id);
        echo json_encode(true);
        wp_die();
    }
    
    /**
	 * hides (but does not remove) a notice based on unique identifier
     * @param array $notice
	 */
    public static function hide_notice($id) {
        
        if (isset( self::$core_notices[ $id ] )) {
            self::remove_notice( $id );
        } else {
            $notices = self::get_notices();
        
            if ( ! empty( $notices ) ) {
                foreach ( $notices as $notice_md5 ) {
                    if ( $notice_md5 = $id ) {
                        $notice = get_option('EMC_NOTICE_'.$notice_md5);
                        if (is_array($notice)) {
                            $notice['show'] = false;
                            self::update_custom_notice($notice_md5, $notice);
                        }
                    }
                }
            }
        }
    }
}

endif;

emc_admin_notices::init();
