<?php
namespace Nahiro\InteractiveMap\Model;

class MapPostType {
    public function __construct() {
        // Cargar el text-domain
        add_action('plugins_loaded', array($this, 'load_textdomain'));
        add_action('init', array($this, 'nahiroimap_register_post_type'));
        add_filter('manage_nahiroimap-maps_posts_columns', array($this, 'nahiroimap_modify_columns'));
        add_action('manage_nahiroimap-maps_posts_custom_column', array($this, 'nahiroimap_columns_content'), 10, 2);
        add_filter('manage_edit-nahiroimap-maps_sortable_columns', array($this, 'nahiroimap_sortable_columns'));
        add_action('pre_get_posts', array($this, 'nahiroimap_custom_orderby'));
        add_action('admin_init', array($this, 'nahiroimap_settings_init'));
        add_action('admin_menu', array($this, 'nahiroimap_settings_submenu'));
        add_action('admin_menu', array($this, 'nahiroimap_products_plugin_submenu'));
    }

    /**
     * Cargar el text-domain para las traducciones.
     */
    public function load_textdomain() {
        load_plugin_textdomain('store-locations-map', false, dirname(plugin_basename(__FILE__)) . '/languages');
    }

    /**
     * Crea el tipo de publicación "nahiroimap".
     *
     * @return void
     */
    public function nahiroimap_register_post_type() {
        $labels = array(
            'name'               => _x('Maps', 'post type general name', 'store-locations-map'),
            'singular_name'      => _x('Map', 'post type singular name', 'store-locations-map'),
            'menu_name'          => _x('Store Locations Map', 'admin menu', 'store-locations-map'),
            'name_admin_bar'     => _x('Map', 'add new on admin bar', 'store-locations-map'),
            'add_new'            => _x('Add New', 'map', 'store-locations-map'),
            'add_new_item'       => __('Add New Map', 'store-locations-map'),
            'new_item'           => __('New Map', 'store-locations-map'),
            'edit_item'          => __('Edit Map', 'store-locations-map'),
            'view_item'          => __('View Map', 'store-locations-map'),
            'all_items'          => __('All Maps', 'store-locations-map'),
            'search_items'       => __('Search Maps', 'store-locations-map'),
            'parent_item_colon'  => __('Parent Maps:', 'store-locations-map'),
            'not_found'          => __('No maps found.', 'store-locations-map'),
            'not_found_in_trash' => __('No maps found in Trash.', 'store-locations-map')
        );

        $args = array(
            'labels'             => $labels,
            'public'             => false,
            'show_ui'            => true,
            'show_in_menu'       => true,
            'query_var'          => true,
            'capability_type'    => 'post',
            'has_archive'        => false,
            'hierarchical'       => false,
            'menu_icon'          => 'dashicons-location',
            'menu_position'      => null,
            'supports'           => array('title')
        );

        register_post_type('nahiroimap-maps', $args);
    }

    /**
     * Modifica las columnas mostradas en la tabla de administración para el tipo de publicación.
     * Añade dos nuevas columnas: 'map_id' y 'map_shortcode'.
     *
     * @param array $columns
     * @return array
     */
    public function nahiroimap_modify_columns($columns) {
        // Eliminar columnas existentes
        unset($columns['author']);
        unset($columns['date']);

        // Añadir nuevas columnas
        $columns['map_description'] = __('Description', 'store-locations-map');
        $columns['map_id'] = __('ID', 'store-locations-map');
        $columns['map_shortcode'] = __('Shortcode', 'store-locations-map');
        return $columns;
    }

    /**
     * Rellena las columnas personalizadas con datos de los campos personalizados.
     *
     * @param string $column
     * @param int $post_id
     * @return void
     */
    public function nahiroimap_columns_content($column, $post_id) {
        switch ($column) {
            case 'map_description':
                echo esc_html(get_post_meta($post_id, '_map_description', true));
                break;

            case 'map_id':
                echo esc_html(get_the_ID());
                break;

            case 'map_shortcode':
                echo "<input type='text' onfocus='this.select();' class='large-text code' readonly='readonly' value='[store-locations-map id=\"" . esc_attr(get_the_ID()) . "\"]' />";
                break;
        }
    }

    /**
     * Hace que las columnas personalizadas sean ordenables.
     *
     * @param array $columns
     * @return array
     */
    public function nahiroimap_sortable_columns($columns) {
        $columns['map_id'] = 'map_id';
        return $columns;
    }

    /**
     * Maneja la lógica de ordenamiento para las columnas personalizadas.
     *
     * @param WP_Query $query
     * @return void
     */
    public function nahiroimap_custom_orderby($query) {
        if (!is_admin()) {
            return;
        }

        $orderby = $query->get('orderby');

        if ('map_id' === $orderby) {
            $query->set('meta_key', '_map_id');
            $query->set('orderby', 'meta_value');
        } elseif ('map_shortcode' === $orderby) {
            $query->set('meta_key', '_map_shortcode');
            $query->set('orderby', 'meta_value');
        }
    }

    /**
     * Añade el submenú de configuración para el tipo de publicación nahiroimap-maps.
     */
    public function nahiroimap_settings_submenu() {
        add_submenu_page(
            'edit.php?post_type=nahiroimap-maps',
            __('Settings Page', 'store-locations-map'),
            __('Map Selector', 'store-locations-map'),
            'manage_options',
            'nahiroimap-settings',
            array($this, 'nahiroimap_settings_content')
        );
    }

    /**
     * Muestra el contenido de la página de configuración.
     *
     * @return void
     */
    public function nahiroimap_settings_content() {
        if (!current_user_can('manage_options')) {
            return;
        }
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            <form action="options.php" method="post">
                <?php
                settings_fields('nahiroimap_options_group');
                do_settings_sections('nahiroimap-country');
                submit_button(__('Save Settings', 'store-locations-map'));
                ?>
            </form>
        </div>
        <?php
    }

    /**
     * Añade las opciones al grupo de opciones nahiroimap_options_group.
     * @return void
     */
    public function nahiroimap_settings_init() {
        register_setting('nahiroimap_options_group', 'nahiroimap_country_option', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => null,
        ));

        add_settings_section(
            'nahiroimap_settings_section',
            __('Map Settings', 'store-locations-map'),
            array($this, 'nahiroimap_section_callback'),
            'nahiroimap-country'
        );

        add_settings_field(
            'nahiroimap_select_field',
            __('Select a Country', 'store-locations-map'),
            array($this, 'nahiroimap_country_field_callback'),
            'nahiroimap-country',
            'nahiroimap_settings_section'
        );
    }

    /**
     * Callback para la sección de configuración.
     * @return void
     */
    public function nahiroimap_section_callback() {
        echo '<p>' . esc_html( __('Choose an option from the dropdown below:', 'store-locations-map') ). '</p>';
    }

    /**
     * Callback para el campo de selección de país.
     * @return void
     */
    public function nahiroimap_country_field_callback() {
        $options = get_option('nahiroimap_country_option');
        require_once plugin_dir_path(__FILE__) . '../../includes/country-list.php';
    }

    /**
     * Añade el submenú para mostrar los productos de nahiro.net
     */
    public function nahiroimap_products_plugin_submenu() {
        add_submenu_page(
            'edit.php?post_type=nahiroimap-maps',
            __('Other Plugins', 'store-locations-map'),
            __('Plugins', 'store-locations-map'),
            'manage_options',
            'nahiroimap-plugins',
            array($this, 'nahiroimap_product_plugins_content')
        );
    }

     /**
     * Muestra el contenido de la página de productos (plugins).
     *
     * @return void
     */
    public function nahiroimap_product_plugins_content() {
        if (!current_user_can('manage_options')) {
            return;
        }

        $lang=get_bloginfo("language");
        require_once(NAHIROIMAP_PLUGIN_PATH.'includes/list-plugins.php'); 

    }
}
