<?php

/*
 * this class should be used to work with the administrative side of wordpress
 */
class Dahm_Admin
{

    protected static $instance = null;
    private $shared = null;

    private $screen_id_connections = null;
	private $screen_id_wizard = null;
    private $screen_id_import = null;
    private $screen_id_export = null;
	private $screen_id_maintenance = null;
	private $screen_id_help = null;
    private $screen_id_options = null;

	public $menu_options = null;

    private function __construct()
    {

        //assign an instance of the plugin info
        $this->shared = Dahm_Shared::get_instance();

        //Load admin stylesheets and JavaScript
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_styles'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));

	    //Write in back end head
	    add_action('admin_head', array($this, 'wr_admin_head'));

        //Add the admin menu
        add_action('admin_menu', array($this, 'me_add_admin_menu'));

        //Load the options API registrations and callbacks
        add_action('admin_init', array($this, 'op_register_options'));

	    //Require and instantiate the class used to register the menu options
	    require_once( $this->shared->get( 'dir' ) . 'admin/inc/class-dahm-menu-options.php' );
	    $this->menu_options = new Dahm_Menu_Options( $this->shared );

        //Add the meta box
        add_action('add_meta_boxes', array($this, 'create_meta_box'));

        //Save the meta box
        add_action( 'save_post', array($this, 'save_meta_box') );

        //this hook is triggered during the creation of a new blog
        add_action('wpmu_new_blog', array($this, 'new_blog_create_options_and_tables'), 10, 6);

        //this hook is triggered during the deletion of a blog
        add_action('delete_blog', array($this, 'delete_blog_delete_options_and_tables'), 10, 1);

        //Fires before a post is sent to the trash
        add_action( 'wp_trash_post', array($this, 'delete_post_connection'));

        //Export XML controller
        add_action('init', array($this, 'export_xml_controller'));

    }

    /*
     * return an instance of this class
     */
    public static function get_instance()
    {

        if (null == self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;

    }

	/*
     * write in the admin head
     */
	public function wr_admin_head()
	{

		echo '<script type="text/javascript">';
		echo 'window.dahmAjaxUrl = "' . admin_url('admin-ajax.php') . '";';
		echo 'window.dahmNonce = "' . wp_create_nonce("dahm") . '";';
		echo 'window.dahmAdminUrl ="' . get_admin_url() . '";';
		echo '</script>';

	}

    public function enqueue_admin_styles()
    {

        $screen = get_current_screen();

        //menu connnections
        if ($screen->id == $this->screen_id_connections) {
            wp_enqueue_style($this->shared->get('slug') . '-framework-menu', $this->shared->get('url') . 'admin/assets/css/framework/menu.css', array(), $this->shared->get('ver'));
            wp_enqueue_style($this->shared->get('slug') . '-menu-connections', $this->shared->get('url') . 'admin/assets/css/menu-connections.css', array(), $this->shared->get('ver'));
            wp_enqueue_style($this->shared->get('slug') . '-chosen', $this->shared->get('url') . 'admin/assets/inc/chosen/chosen-min.css', array(), $this->shared->get('ver'));
            wp_enqueue_style($this->shared->get('slug') . '-chosen-custom', $this->shared->get('url') . 'admin/assets/css/chosen-custom.css', array(), $this->shared->get('ver'));

	        //jQuery UI Tooltip
	        wp_enqueue_style($this->shared->get('slug') . '-jquery-ui-tooltip',
		        $this->shared->get('url') . 'admin/assets/css/jquery-ui-tooltip.css', array(),
		        $this->shared->get('ver'));

        }

	    //menu wizard
	    if ($screen->id == $this->screen_id_wizard) {

		    wp_enqueue_style($this->shared->get('slug') . '-framework-menu', $this->shared->get('url') . 'admin/assets/css/framework/menu.css', array(), $this->shared->get('ver'));
		    wp_enqueue_style($this->shared->get('slug') . '-menu-wizard', $this->shared->get('url') . 'admin/assets/css/menu-wizard.css', array(), $this->shared->get('ver'));

		    //Handsontable
		    wp_enqueue_style($this->shared->get('slug') . '-handsontable-full',
			    $this->shared->get('url') . 'admin/assets/inc/handsontable/handsontable.full.min.css', array(),
			    $this->shared->get('ver'));

	    }

	    //menu maintenance
	    if ($screen->id == $this->screen_id_maintenance) {

		    //Framework Menu
		    wp_enqueue_style($this->shared->get('slug') . '-framework-menu',
			    $this->shared->get('url') . 'admin/assets/css/framework/menu.css', array(), $this->shared->get('ver'));

		    //jQuery UI Dialog
		    wp_enqueue_style($this->shared->get('slug') . '-jquery-ui-dialog',
			    $this->shared->get('url') . 'admin/assets/css/jquery-ui-dialog.css', array(),
			    $this->shared->get('ver'));
		    wp_enqueue_style($this->shared->get('slug') . '-jquery-ui-dialog-custom',
			    $this->shared->get('url') . 'admin/assets/css/jquery-ui-dialog-custom.css', array(),
			    $this->shared->get('ver'));

		    //jQuery UI Tooltip
		    wp_enqueue_style($this->shared->get('slug') . '-jquery-ui-tooltip',
			    $this->shared->get('url') . 'admin/assets/css/jquery-ui-tooltip.css', array(),
			    $this->shared->get('ver'));

		    //Chosen
		    wp_enqueue_style($this->shared->get('slug') . '-chosen',
			    $this->shared->get('url') . 'admin/assets/inc/chosen/chosen-min.css', array(),
			    $this->shared->get('ver'));
		    wp_enqueue_style($this->shared->get('slug') . '-chosen-custom',
			    $this->shared->get('url') . 'admin/assets/css/chosen-custom.css', array(), $this->shared->get('ver'));

	    }

        //menu options
        if ($screen->id == $this->screen_id_options) {
            wp_enqueue_style($this->shared->get('slug') . '-framework-options', $this->shared->get('url') . 'admin/assets/css/framework/options.css', array(), $this->shared->get('ver'));
            wp_enqueue_style($this->shared->get('slug') . '-jquery-ui-tooltip', $this->shared->get('url') . 'admin/assets/css/jquery-ui-tooltip.css', array(), $this->shared->get('ver'));
            wp_enqueue_style($this->shared->get('slug') . '-chosen', $this->shared->get('url') . 'admin/assets/inc/chosen/chosen-min.css', array(), $this->shared->get('ver'));
            wp_enqueue_style($this->shared->get('slug') . '-chosen-custom', $this->shared->get('url') . 'admin/assets/css/chosen-custom.css', array(), $this->shared->get('ver'));
            wp_enqueue_style($this->shared->get('slug') . '-menu-options', $this->shared->get('url') . 'admin/assets/css/menu-options.css', array(), $this->shared->get('ver'));
        }

        $meta_box_post_types = preg_replace('/\s+/', '', get_option( $this->shared->get('slug') . '_meta_box_post_types' ));
        $meta_box_post_types_a = explode(',', $meta_box_post_types);
        if(in_array($screen->id, $meta_box_post_types_a)){
            wp_enqueue_style( $this->shared->get('slug') .'-meta-box', $this->shared->get('url') . 'admin/assets/css/meta-box.css', array(), $this->shared->get('ver') );
            wp_enqueue_style($this->shared->get('slug') . '-chosen', $this->shared->get('url') . 'admin/assets/inc/chosen/chosen-min.css', array(), $this->shared->get('ver'));
            wp_enqueue_style($this->shared->get('slug') . '-chosen-custom', $this->shared->get('url') . 'admin/assets/css/chosen-custom.css', array(), $this->shared->get('ver'));
        }

    }

    /*
     * enqueue admin-specific javascript
     */
    public function enqueue_admin_scripts()
    {

	    $wp_localize_script_data = array(
		    'deleteText'         => esc_attr__('Delete', 'dahm'),
		    'cancelText'         => esc_attr__('Cancel', 'dahm'),
	    );

        $screen = get_current_screen();

        //menu connnections
        if ($screen->id == $this->screen_id_connections) {
	        wp_enqueue_script('jquery-ui-tooltip');
	        wp_enqueue_script( $this->shared->get('slug') . '-jquery-ui-tooltip-init', $this->shared->get('url') . 'admin/assets/js/jquery-ui-tooltip-init.js', 'jquery', $this->shared->get('ver') );
            wp_enqueue_script($this->shared->get('slug') . '-chosen', $this->shared->get('url') . 'admin/assets/inc/chosen/chosen-min.js', array('jquery'), $this->shared->get('ver'));
            wp_enqueue_script($this->shared->get('slug') . '-connections-menu', $this->shared->get('url') . 'admin/assets/js/connections-menu.js', array('jquery'), $this->shared->get('ver'));
        }

	    //menu wizard
	    if ($screen->id == $this->screen_id_wizard) {

		    //Wizard Menu
		    wp_enqueue_script($this->shared->get('slug') . '-menu-wizard',
			    $this->shared->get('url') . 'admin/assets/js/menu-wizard.js', 'jquery', $this->shared->get('ver'));

		    //Handsontable
		    wp_enqueue_script($this->shared->get('slug') . '-handsontable-full',
			    $this->shared->get('url') . 'admin/assets/inc/handsontable/handsontable.full.min.js', array('jquery'),
			    $this->shared->get('ver'));

	    }

	    //menu maintenance
	    if ($screen->id == $this->screen_id_maintenance) {

		    wp_enqueue_script('jquery-ui-tooltip');
		    wp_enqueue_script( $this->shared->get('slug') . '-jquery-ui-tooltip-init', $this->shared->get('url') . 'admin/assets/js/jquery-ui-tooltip-init.js', 'jquery', $this->shared->get('ver') );
		    wp_enqueue_script($this->shared->get('slug') . '-chosen', $this->shared->get('url') . 'admin/assets/inc/chosen/chosen-min.js', array('jquery'), $this->shared->get('ver'));

            //Maintenance Menu
            wp_enqueue_script($this->shared->get('slug') . '-maintenance-menu',
                $this->shared->get('url') . 'admin/assets/js/maintenance-menu.js', array('jquery', 'jquery-ui-dialog'),
                $this->shared->get('ver'));
		    wp_localize_script($this->shared->get('slug') . '-maintenance-menu', 'objectL10n',
			    $wp_localize_script_data);

	    }

	    //Menu Help
	    if ( $screen->id == $this->screen_id_help ) {

		    wp_enqueue_style( $this->shared->get( 'slug' ) . '-menu-help',
			    $this->shared->get( 'url' ) . 'admin/assets/css/menu-help.css', array(), $this->shared->get( 'ver' ) );

	    }
        
	    //menu options
	    if ($screen->id == $this->screen_id_options) {
		    wp_enqueue_script('jquery-ui-tooltip');
		    wp_enqueue_script( $this->shared->get('slug') . '-jquery-ui-tooltip-init', $this->shared->get('url') . 'admin/assets/js/jquery-ui-tooltip-init.js', 'jquery', $this->shared->get('ver') );
		    wp_enqueue_script($this->shared->get('slug') . '-chosen', $this->shared->get('url') . 'admin/assets/inc/chosen/chosen-min.js', array('jquery'), $this->shared->get('ver'));
		    wp_enqueue_script($this->shared->get('slug') . '-options-menu', $this->shared->get('url') . 'admin/assets/js/options-menu.js', array('jquery'), $this->shared->get('ver'));
	    }

        $meta_box_post_types = preg_replace('/\s+/', '', get_option( $this->shared->get('slug') . '_meta_box_post_types' ));
        $meta_box_post_types_a = explode(',', $meta_box_post_types);
        if(in_array($screen->id, $meta_box_post_types_a)){
            wp_enqueue_script($this->shared->get('slug') . '-chosen', $this->shared->get('url') . 'admin/assets/inc/chosen/chosen-min.js', array('jquery'), $this->shared->get('ver'));
            wp_enqueue_script($this->shared->get('slug') . '-meta-box', $this->shared->get('url') . 'admin/assets/js/meta-box.js', array('jquery'), $this->shared->get('ver'));
        }

    }

    /*
     * plugin activation
     */
    public function ac_activate($networkwide)
    {

        /*
         * delete options and tables for all the sites in the network
         */
        if (function_exists('is_multisite') and is_multisite()) {

            /*
             * if this is a "Network Activation" create the options and tables
             * for each blog
             */
            if ($networkwide) {

                //get the current blog id
                global $wpdb;
                $current_blog = $wpdb->blogid;

                //create an array with all the blog ids
                $blogids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");

                //iterate through all the blogs
                foreach ($blogids as $blog_id) {

                    //swith to the iterated blog
                    switch_to_blog($blog_id);

                    //create options and tables for the iterated blog
                    $this->ac_initialize_options();
                    $this->ac_create_database_tables();
	                $this->schedule_cron_event();

                }

                //switch to the current blog
                switch_to_blog($current_blog);

            } else {

                /*
                 * if this is not a "Network Activation" create options and
                 * tables only for the current blog
                 */
                $this->ac_initialize_options();
                $this->ac_create_database_tables();
	            $this->schedule_cron_event();

            }

        } else {

            /*
             * if this is not a multisite installation create options and
             * tables only for the current blog
             */
            $this->ac_initialize_options();
            $this->ac_create_database_tables();
	        $this->schedule_cron_event();

        }

    }

    //create the options and tables for the newly created blog
    public function new_blog_create_options_and_tables($blog_id, $user_id, $domain, $path, $site_id, $meta)
    {

        global $wpdb;

        /*
         * if the plugin is "Network Active" create the options and tables for
         * this new blog
         */
        if (is_plugin_active_for_network('hreflang-manager/init.php')) {

            //get the id of the current blog
            $current_blog = $wpdb->blogid;

            //switch to the blog that is being activated
            switch_to_blog($blog_id);

            //create options and database tables for the new blog
            $this->ac_initialize_options();
            $this->ac_create_database_tables();
	        $this->schedule_cron_event();

            //switch to the current blog
            switch_to_blog($current_blog);

        }

    }

    //delete options and tables for the deleted blog
    public function delete_blog_delete_options_and_tables($blog_id)
    {

        global $wpdb;

        //get the id of the current blog
        $current_blog = $wpdb->blogid;

        //switch to the blog that is being activated
        switch_to_blog($blog_id);

        //create options and database tables for the new blog
        $this->un_delete_options();
        $this->un_delete_database_tables();

        //switch to the current blog
        switch_to_blog($current_blog);

    }

    /*
     * initialize plugin options
     */
    private function ac_initialize_options()
    {

	    foreach($this->shared->get('options') as $key => $value){
		    add_option($key, $value);
	    }

    }

    /*
     * create the plugin database tables
     */
    private function ac_create_database_tables()
    {

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        //check database version and create the database
        if (intval(get_option($this->shared->get('slug') . '_database_version'), 10) < 6) {

            global $wpdb;
            $table_name = $wpdb->prefix . "da_hm_connect";
            $sql = "CREATE TABLE $table_name (
                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                url_to_connect TEXT DEFAULT '' NOT NULL,
                url MEDIUMTEXT DEFAULT '' NOT NULL,
                language MEDIUMTEXT DEFAULT '' NOT NULL,
                script MEDIUMTEXT DEFAULT '' NOT NULL,
                locale MEDIUMTEXT DEFAULT '' NOT NULL,
                inherited TINYINT(1) DEFAULT 0 NOT NULL
            )
            COLLATE = utf8_general_ci
            ";

            dbDelta($sql);

	        /**
	         * Add to the database, in the four fields created in the previous query, the serialized data of url,
             * language, script, and locale.
	         *
	         * Specifically, the data are retrieved from url[1-100], language[1-100], script[1-100], and locale[1-100]
             * and added as serialized strings to the url, language, script, and locale fields.
	         */

	        //Iterate over all the records in the database
	        global $wpdb;
	        $table_name = $wpdb->prefix . $this->shared->get( 'slug' ) . "_connect";
	        $connect_a  = $wpdb->get_results( "SELECT * FROM $table_name ORDER BY id ASC", ARRAY_A );

	        foreach ( $connect_a as $connect ) {

		        //Put the data in 4 arrays
		        for ( $i = 1; $i <= 100; $i ++ ) {

			        $url[ $i ]      = $connect[ 'url' . $i ];
			        $language[ $i ] = $connect[ 'language' . $i ];
			        $script[ $i ]   = $connect[ 'script' . $i ];
			        $locale[ $i ]   = $connect[ 'locale' . $i ];

		        }

		        //Serialize the 4 arrays
		        $url_json      = json_encode( $url );
		        $language_json = json_encode( $language );
		        $script_json   = json_encode( $script );
		        $locale_json   = json_encode( $locale );

		        //Save the 4 serialized fields in the record with the iterated id
		        $safe_sql = $wpdb->prepare( "UPDATE $table_name SET
                         url = %s,
                         language = %s,
                         script = %s,
                         locale = %s
                        WHERE id = %d",
			        $url_json,
			        $language_json,
			        $script_json,
			        $locale_json,
			        $connect['id'] );

		        $wpdb->query( $safe_sql );

	        }

            //Update database version
            update_option('da_hm_database_version', "6");

        }

    }

    /*
     * plugin delete
     */
    static public function un_delete()
    {

        /*
         * delete options and tables for all the sites in the network
         */
        if (function_exists('is_multisite') and is_multisite()) {

            //get the current blog id
            global $wpdb;
            $current_blog = $wpdb->blogid;

            //create an array with all the blog ids
            $blogids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");

            //iterate through all the blogs
            foreach ($blogids as $blog_id) {

                //swith to the iterated blog
                switch_to_blog($blog_id);

                //create options and tables for the iterated blog
                Dahm_Admin::un_delete_options();
                Dahm_Admin::un_delete_database_tables();

            }

            //switch to the current blog
            switch_to_blog($current_blog);

        } else {

            /*
             * if this is not a multisite installation delete options and
             * tables only for the current blog
             */
            Dahm_Admin::un_delete_options();
            Dahm_Admin::un_delete_database_tables();

        }

    }

    /*
     * delete plugin options
     */
    static public function un_delete_options()
    {

	    //assign an instance of Dahm_Shared
	    $shared = Dahm_Shared::get_instance();

	    foreach($shared->get('options') as $key => $value){
		    delete_option($key);
	    }

    }

    /*
     * delete plugin database tables
     */
    static public function un_delete_database_tables()
    {

        //assign an instance of Dahm_Shared
        $shared = Dahm_Shared::get_instance();

        global $wpdb;

        $table_name = $wpdb->prefix . $shared->get('slug') . "_connect";
        $sql = "DROP TABLE $table_name";
        $wpdb->query($sql);

    }

    //meta box -----------------------------------------------------------------
    public function create_meta_box()
    {

        //verify the capability
        if(current_user_can(get_option($this->shared->get('slug') . "_meta_box_capability"))){

	        $post_types = preg_replace('/\s+/', '', get_option( $this->shared->get('slug') . '_meta_box_post_types' ));
	        $post_types_a = explode(',', $post_types);

	        foreach ($post_types_a as $key => $post_type) {
		        $post_type = trim($post_type);
		        add_meta_box('da-hm-meta',
                    'Hreflang Manager',
                    array($this, 'meta_box_callback'),
                    $post_type,
                    'normal',
                    'high',

                    /*
                     * Reference:
                     *
                     * https://make.wordpress.org/core/2018/11/07/meta-box-compatibility-flags/
                     */
                    array(

                        /*
                         * It's not confirmed that this meta box works in the block editor.
                         */
                        '__block_editor_compatible_meta_box' => false,

                        /*
                         * This meta box should only be loaded in the classic editor interface, and the block editor
                         * should not display it.
                         */
                        '__back_compat_meta_box' => true

                    )

                );
	        }

        }

    }

    //display the Hreflang Manager meta box content
    public function meta_box_callback($post)
    {

        ?>

        <table class="form-table table-hreflang-manager">

            <tbody>

            <?php


            /*
             * activate the 'disabled="disabled"' attribute when the post status is not:
             * - publish
             * - future
             * - pending
             * - private
             */
            $post_status = get_post_status();
            if($post_status != 'publish' and $post_status != 'future' and $post_status != 'pending' and $post_status != 'private'){
                $input_disabled = 'disabled="disabled"';
            }else{
                $input_disabled = '';
            }

            /*
             * Look for a connection that has as a url_to_connect value the permalink value of this post
             *
             * If there is already a connection:
             * - show the form with the field already filled with the value from the database
             * If there is no connection:
             * - show the form with empty fields
             */

            //get the number of connections that should be displayed in the menu
            $connections_in_menu = intval(get_option('da_hm_connections_in_menu'), 10);

            $permalink = $this->shared->get_permalink(get_the_ID(), true);

            //look for $permalink in the url_to_connect field of the da_hm_connect database table
            global $wpdb;
            $table_name = $wpdb->prefix . "da_hm_connect";
            $safe_sql = $wpdb->prepare("SELECT * FROM $table_name WHERE url_to_connect = %s", $permalink);
            $permalink_connections = $wpdb->get_row($safe_sql);

            if ($permalink_connections === null) {

                //default empty form
                for ($i = 1; $i <= $connections_in_menu; $i++) {

                    ?>

                    <!-- url -->
                    <tr valign="top">
                        <th scope="row"><label for="url<?php echo esc_attr($i); ?>"><?php esc_html_e('URL', 'dahm'); ?> <?php echo esc_html($i); ?></label></th>
                        <td><input autocomplete="off" <?php echo $input_disabled; ?> type="text" id="url<?php echo esc_attr($i); ?>" maxlength="2083" name="url<?php echo esc_attr($i); ?>" class="regular-text dahm-url"/></td>
                    </tr>

                    <!-- Language -->
                    <tr valign="top">
                        <th scope="row"><label for="language<?php echo esc_attr($i); ?>"><?php esc_html_e('Language', 'dahm'); ?> <?php echo esc_html($i); ?></label></th>
                        <td>
                            <select <?php echo $input_disabled; ?> id="language<?php echo esc_attr($i); ?>" class="dahm-language" name="language<?php echo esc_attr($i); ?>">
                                <?php

                                $array_language = get_option('da_hm_language');
                                foreach ($array_language as $key => $value) {
                                    echo '<option value="' . esc_attr($value) . '" ' . selected(get_option("da_hm_default_language_" . $i), $value, false) . '>' . esc_html($value) . " - " . esc_html($key) . '</option>';
                                }

                                ?>
                            </select>
                        </td>
                    </tr>

                    <!-- Script -->
                    <tr valign="top">
                        <th scope="row"><label for="script<?php echo esc_attr($i); ?>"><?php esc_html_e('Script', 'dahm'); ?> <?php echo esc_html($i); ?></label></th>
                        <td>
                            <select <?php echo $input_disabled; ?> id="script<?php echo esc_attr($i); ?>" class="dahm-script" name="script<?php echo esc_attr($i); ?>">
                                <option value=""><?php esc_html_e('Not Assigned', 'dahm'); ?></option>
                                <?php

                                $array_language = get_option('da_hm_script');
                                foreach ($array_language as $key => $value) {
                                    echo '<option value="' . esc_attr($value) . '" ' . selected(get_option("da_hm_default_script_" . $i), $value, false) . '>' . esc_html($value) . " - " . esc_html($key) . '</option>';
                                }

                                ?>
                            </select>
                        </td>
                    </tr>
                    
                    <!-- Locale -->
                    <tr valign="top">
                        <th scope="row"><label for="locale<?php echo $i; ?>"><?php esc_html_e('Locale', 'dahm'); ?> <?php echo $i; ?></label></th>
                        <td>
                            <select <?php echo $input_disabled; ?> id="locale<?php echo esc_attr($i); ?>" class="dahm-locale" name="locale<?php echo esc_attr($i); ?>">
                                <option value=""><?php esc_html_e('Not Assigned', 'dahm'); ?></option>
                                <?php

                                $array_language = get_option('da_hm_locale');
                                foreach ($array_language as $key => $value) {
                                    echo '<option value="' . esc_attr($value) . '" ' . selected(get_option("da_hm_default_locale_" . $i), $value, false) . '>' . esc_html($value) . " - " . esc_html($key) . '</option>';
                                }

                                ?>
                            </select>
                        </td>
                    </tr>

                    <?php

                }

            } else {

                //Decode the connection data
                $permalink_connections->url = json_decode($permalink_connections->url);
                $permalink_connections->language = json_decode($permalink_connections->language);
                $permalink_connections->script = json_decode($permalink_connections->script);
                $permalink_connections->locale = json_decode($permalink_connections->locale);

                //form with data retrieved form the database
                for ($i = 1; $i <= $connections_in_menu; $i++) {

                    ?>

                    <!-- url -->
                    <tr valign="top">
                        <th scope="row"><label for="url<?php echo esc_attr($i); ?>"><?php esc_html_e('URL', 'dahm'); ?> <?php echo esc_html($i); ?></label></th>
                        <td><input autocomplete="off" type="text" value="<?php echo esc_attr(stripslashes($permalink_connections->url->{$i})); ?>" id="url<?php echo esc_attr($i); ?>" maxlength="2083" name="url<?php echo esc_attr($i); ?>" class="regular-text dahm-url"/></td>

                    </tr>

                    <!-- Language <?php echo intval($i, 10); ?> -->
                    <tr valign="top">
                        <th scope="row"><label for="language<?php echo esc_attr($i); ?>"><?php esc_html_e('Language', 'dahm'); ?> <?php echo esc_html($i); ?></label></th>
                        <td>
                            <select id="language<?php echo esc_attr($i); ?>" class="dahm-language" name="language<?php echo esc_attr($i); ?>">
                                <?php

                                $array_language = get_option('da_hm_language');
                                foreach ($array_language as $key => $value) {
                                    echo '<option value="' . esc_attr($value) . '" ' . selected($permalink_connections->language->{$i}, $value, false) . '>' . esc_html($value) . " - " . esc_html($key) . '</option>';
                                }

                                ?>
                            </select>
                        </td>
                    </tr>

                    <!-- Script <?php echo intval($i, 10); ?> -->
                    <tr valign="top">
                        <th scope="row"><label for="script<?php echo esc_attr($i); ?>"><?php esc_html_e('Script', 'dahm'); ?> <?php echo esc_html($i); ?></label></th>
                        <td>
                            <select id="script<?php echo esc_attr($i); ?>" class="dahm-script" name="script<?php echo esc_attr($i); ?>">
                                <option value=""><?php esc_html_e('Not Assigned', 'dahm'); ?></option>
                                <?php

                                $array_language = get_option('da_hm_script');
                                foreach ($array_language as $key => $value) {
                                    echo '<option value="' . esc_attr($value) . '" ' . selected($permalink_connections->script->{$i}, $value, false) . '>' . esc_html($value) . " - " . esc_html($key) . '</option>';
                                }

                                ?>
                            </select>
                        </td>
                    </tr>
                    
                    <!-- Locale <?php echo intval($i, 10); ?> -->
                    <tr valign="top">
                        <th scope="row"><label for="locale<?php echo esc_attr($i); ?>"><?php esc_html_e('Locale', 'dahm'); ?> <?php echo esc_html($i); ?></label></th>
                        <td>
                            <select id="locale<?php echo esc_attr($i); ?>" class="dahm-locale" name="locale<?php echo esc_attr($i); ?>">
                                <option value=""><?php esc_html_e('Not Assigned', 'dahm'); ?></option>
                                <?php

                                $array_language = get_option('da_hm_locale');
                                foreach ($array_language as $key => $value) {
                                    echo '<option value="' . esc_attr($value) . '" ' . selected($permalink_connections->locale->{$i}, $value, false) . '>' . esc_html($value) . " - " . esc_html($key) . '</option>';
                                }

                                ?>
                            </select>
                        </td>
                    </tr>

                    <?php

                }

            }

            ?>

            </tbody>

        </table>

        <?php

        // Use nonce for verification
        wp_nonce_field(plugin_basename(__FILE__), 'da_hm_nonce');

    }

    public function save_meta_box( $post_id ) {

        //verify the capability
        if(!current_user_can(get_option($this->shared->get('slug') . "_meta_box_capability"))){return;}

        /* --- security verification --- */

        // verify if this is an auto save routine.
        // If it is our form has not been submitted, so we dont want to do anything
        if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

	    // verify this came from the our screen and with proper authorization,
	    // because save_post can be triggered at other times
        if(isset( $_POST['da_hm_nonce'])){
            $nonce = sanitize_text_field($_POST['da_hm_nonce']);
            if(!wp_verify_nonce( $nonce, plugin_basename( __FILE__ ) )){
                return;
            }
        }else{
            return;
        }

        /* - end security verification - */

        /*
         * Return ( do not save ) if the post status is not:
         * - publish
         * - future
         * - pending
         * - private
         */
        $post_status = get_post_status();
        if($post_status != 'publish' and $post_status != 'future' and $post_status != 'pending' and $post_status != 'private'){return;}

        //Init vars
	    $url = [];
	    $language = [];
	    $script = [];
	    $locale = [];

        //initialize the variables that include the URLs, the languages and the locale
        for($i=1;$i<=100;$i++){

            if( isset($_POST['url' . $i]) and strlen(trim($_POST['url' . $i])) > 0 ) {
                $url[$i] = esc_url_raw($_POST['url' . $i]);
                $at_least_one_url = true;
            }else {
                $url[$i] = '';
            }

            if( isset($_POST['language' . $i]) ){
                $language[$i] = sanitize_text_field($_POST['language' . $i]);
            }else{
                $language[$i] = get_option($this->shared->get('slug') . '_default_language_' . $i);
            }

            if( isset($_POST['script' . $i]) ){
                $script[$i] = sanitize_text_field($_POST['script' . $i]);
            }else{
                $script[$i] = get_option($this->shared->get('slug') . '_default_script_' . $i);
            }
            
            if( isset($_POST['locale' . $i]) ){
                $locale[$i] = sanitize_text_field($_POST['locale' . $i]);
            }else{
                $locale[$i] = get_option($this->shared->get('slug') . '_default_locale_' . $i);
            }

        }

        //json encode for the serialized field of the database
	    $url_json = json_encode($url);
	    $language_json = json_encode($language);
	    $script_json = json_encode($script);
	    $locale_json = json_encode($locale);

        /*
         * save the fields in the da_hm_connect database table:
         *
         * - if a row with the da_hm_connect equal to the current permalink already exists update the row
         *
         * - if a row with the da_hm_connect equal to the current permalink doesn't exists create a new row
         */
	    $permalink = $this->shared->get_permalink(get_the_ID(), true);

        //look for $permalink in the url_to_connect field of the da_hm_connect database table
        global $wpdb;
        $table_name = $wpdb->prefix . "da_hm_connect";
        $safe_sql = $wpdb->prepare("SELECT * FROM $table_name WHERE url_to_connect = %s", $permalink);
        $permalink_connections = $wpdb->get_row($safe_sql);

        if($permalink_connections !== null){

            //update an existing connection
            $safe_sql = $wpdb->prepare("UPDATE $table_name SET
                 url = %s,
                 language = %s,
                 script = %s,
                 locale = %s
                WHERE url_to_connect = %s ",
	            $url_json,
	            $language_json,
	            $script_json,
	            $locale_json,
                $permalink);
            $wpdb->query( $safe_sql );

        }else{

            //Return ( do not create a new connection ) if there are not a single url defined
            if(!isset($at_least_one_url)){return;}

            //add a new connection into the database
            $safe_sql = $wpdb->prepare("INSERT INTO $table_name SET url_to_connect = %s ,
                  url = %s,
                 language = %s,
                 script = %s,
                 locale = %s",
                $permalink,
	            $url_json,
	            $language_json,
	            $script_json,
	            $locale_json);
            $wpdb->query( $safe_sql );

        }

    }

    /*
     * register the admin menu
     */
    public function me_add_admin_menu() {

        add_menu_page(
            'HM',
            'Hreflang',
            get_option($this->shared->get('slug') . "_connections_menu_capability"),
            $this->shared->get('slug') . '_connections',
            array( $this, 'me_display_menu_connections'),
            'dashicons-admin-site'
        );

        $this->screen_id_connections = add_submenu_page(
            $this->shared->get('slug') . '_connections',
            esc_html__('HM - Connections', 'dahm'),
	        esc_html__('Connections', 'dahm'),
            get_option($this->shared->get('slug') . "_connections_menu_capability"),
            $this->shared->get('slug') . '_connections',
            array( $this, 'me_display_menu_connections')
        );

	    $this->screen_id_wizard = add_submenu_page(
		    $this->shared->get('slug') . '_connections',
		    esc_html__('HM - Wizard', 'dahm'),
		    esc_html__('Wizard', 'dahm'),
		    get_option($this->shared->get('slug') . "_wizard_menu_capability"),
		    $this->shared->get('slug') . '_wizard',
		    array( $this, 'me_display_menu_wizard')
	    );

        $this->screen_id_import = add_submenu_page(
            $this->shared->get('slug') . '_connections',
	        esc_html__('HM - Import', 'dahm'),
	        esc_html__('Import', 'dahm'),
            get_option($this->shared->get('slug') . "_import_menu_capability"),
            $this->shared->get('slug') . '_import',
            array( $this, 'me_display_menu_import')
        );

        $this->screen_id_export = add_submenu_page(
            $this->shared->get('slug') . '_connections',
	        esc_html__('HM - Export', 'dahm'),
	        esc_html__('Export', 'dahm'),
            get_option($this->shared->get('slug') . "_export_menu_capability"),
            $this->shared->get('slug') . '_export',
            array( $this, 'me_display_menu_export')
        );

	    $this->screen_id_maintenance = add_submenu_page(
		    $this->shared->get('slug') . '_connections',
		    esc_html__('HM - Maintenance', 'dahm'),
		    esc_html__('Maintenance', 'dahm'),
		    get_option($this->shared->get('slug') . "_maintenance_menu_capability"),
		    $this->shared->get('slug') . '_maintenance',
		    array( $this, 'me_display_menu_maintenance')
	    );

	    $this->screen_id_help = add_submenu_page(
		    $this->shared->get('slug') . '_connections',
		    esc_html__('HM - Help', 'dahm'),
		    esc_html__('Help', 'dahm'),
		    'manage_options',
		    $this->shared->get('slug') . '_help',
		    array( $this, 'me_display_menu_help')
	    );
        
        $this->screen_id_options = add_submenu_page(
            $this->shared->get('slug') . '_connections',
	        esc_html__('HM - Options', 'dahm'),
	        esc_html__('Options', 'dahm'),
            'manage_options',
            $this->shared->get('slug') . '_options',
            array( $this, 'me_display_menu_options')
        );

    }

    /*
     * includes the connections view
     */
    public function me_display_menu_connections() {
        include_once( 'view/connections.php' );
    }

	/*
     * includes the wizard view
     */
	public function me_display_menu_wizard() {
		include_once( 'view/wizard.php' );
	}

    /*
     * includes the import view
     */
    public function me_display_menu_import() {
        include_once( 'view/import.php' );
    }

    /*
     * includes the export view
     */
    public function me_display_menu_export() {
        include_once( 'view/export.php' );
    }

	/*
     * includes the maintenance view
     */
	public function me_display_menu_maintenance() {
		include_once( 'view/maintenance.php' );
	}

	/*
     * includes the help view
     */
	public function me_display_menu_help() {
		include_once( 'view/help.php' );
	}
    
    /*
     * includes the options view
     */
    public function me_display_menu_options() {
        include_once( 'view/options.php' );
    }

	/*
     * register options
     */
	public function op_register_options() {

		$this->menu_options->register_options();

	}

    /**
     * Deletes a connection by using the permalink of the trashed post. Note that this operation is performed only if
     * the 'Auto Delete' option is enabled.
     */
    public function delete_post_connection($post_id){

        if(intval(get_option($this->shared->get('slug') . '_auto_delete'), 10) == 1){

            $permalink = get_the_permalink($post_id, false);

            global $wpdb;
            $table_name = $wpdb->prefix . 'da_hm_connect';
            $safe_sql = $wpdb->prepare("DELETE FROM $table_name WHERE url_to_connect = %s", $permalink);
            $wpdb->query($safe_sql);

        }

    }

    /*
     * The click on the "Export" button available in the "Export" menu is intercepted and the
     * method that generates the downloadable XML file is called
     */
    public function export_xml_controller()
    {

        /*
         * Intercept requests that come from the "Export" button of the
         * "Hreflang Export -> Export" menu and generate the downloadable XML file
         */
        if (isset($_POST['dahm_export'])) {

            //verify capability
            if (!current_user_can(get_option($this->shared->get('slug') . "_export_menu_capability"))) {
                wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'dahm'));
            }

            //get the data from the 'connect' db
            global $wpdb;
            $table_name = $wpdb->prefix . $this->shared->get('slug') . "_connect";
            $connect_a = $wpdb->get_results("SELECT * FROM $table_name ORDER BY id ASC", ARRAY_A);

            //if there are data generate the csv header and the content
            if (count($connect_a) > 0) {

                //generate the header of the XML file
                header('Content-Encoding: UTF-8');
                header('Content-type: text/xml; charset=UTF-8');
                header("Content-Disposition: attachment; filename=hreflang-manager-" . time() . ".xml");
                header("Pragma: no-cache");
                header("Expires: 0");

                //generate initial part of the XML file
                $out = '<?xml version="1.0" encoding="UTF-8" ?>';
                $out .= '<root>';

                //set column content
                foreach ($connect_a as $connect) {

                    $out .= "<connect>";

                    //get all the indexes of the $table array
                    $table_keys = array_keys($connect);

                    //cycle through all the indexes of $connect and create all the tags related to this record
                    foreach ($table_keys as $key) {

                        $out .= "<" . $key . ">" . esc_attr($connect[$key]) . "</" . $key . ">";

                    }

                    $out .= "</connect>";

                }

                //generate the final part of the XML file
                $out .= '</root>';

            } else {
                return false;
            }

            echo $out;
            die();

        }

    }

	/**
	 * Schedule the 'da_hm_cron_hook" action hook with the frequency defined with the Sync -> Frequency option.
	 */
	public function schedule_cron_event() {

        //Get the sync frequency from the plugin options
		$sync_frequency = intval(get_option($this->shared->get('slug') . "_sync_frequency"), 10);

        //Find the corresponding recurrence value
        $recurrence = null;
        switch($sync_frequency){

            case 0:
                $recurrence = 'hourly';
                break;

	        case 1:
		        $recurrence = 'twicedaily';
		        break;

	        case 2:
		        $recurrence = 'daily';
		        break;

	        case 3:
		        $recurrence = 'weekly';
		        break;

        }

        //Clear the existing scheduled hook "da_hm_cron_hook"
		wp_clear_scheduled_hook( 'da_hm_cron_hook' );

        //Schedule the hook "da_hm_cron_hook" with the defined frequency
        wp_schedule_event( time(), $recurrence, 'da_hm_cron_hook' );

	}

	/*
     * plugin deactivation
     */
	public function dc_deactivate( $networkwide ) {
		wp_clear_scheduled_hook( 'da_hm_cron_hook' );
	}

	/**
	 * Echo all the dismissible notices based on the values of the $notices array.
	 *
	 * @param $notices
	 */
	public function dismissible_notice($notices){

		foreach($notices as $notice){
			echo '<div class="' . esc_attr($notice['class']) . ' settings-error notice is-dismissible below-h2"><p>' . esc_html($notice['message']) . '</p></div>';
		}

	}

}