<?php
/**
 * Plugin Name: Store Locations Map
 * Description: A map widget that allows to choose a country and add markers with images and description in any point of the map
 * Version:     1.0.24
 * Author:      Nahiro.net - Wordpress Hilfe & Support
 * Author URI:  https://nahiro.net/
 * Text Domain: store-locations-map
 * Domain Path: /languages
 * License:     GPL v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
if ( ! defined( 'NAHIROIMAP_PLUGIN_URL' ) ) {
    define( 'NAHIROIMAP_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}
if ( ! defined( 'NAHIROIMAP_PLUGIN_PATH' ) ) {
    define( 'NAHIROIMAP_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
}

// Include the Composer autoloader
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
    require_once __DIR__ . '/vendor/autoload.php';
}

// Set an option to indicate the plugin was just activated
register_activation_hook(__FILE__, 'nahiroimap_shortcode_activate');
function nahiroimap_shortcode_activate() {
    add_option('nahiroimap_shortcode_show_welcome', true);
}

add_action( 'init', 'nahiroimap_load_textdomain' );
 
/**
 * Load plugin textdomain.
 */
function nahiroimap_load_textdomain() {
  load_plugin_textdomain( 'store-locations-map', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}

function nahiroimap_plugin_init() {
	load_plugin_textdomain( 'store-locations-map', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
    new Nahiro\InteractiveMap\Main();
}
add_action('plugins_loaded', 'nahiroimap_plugin_init');

function nahiroimap_add_dependencies()
{
    // Registrar y encolar el script principal
    wp_enqueue_script(
        'nahiroimap_core_widget_js', 
        plugins_url('assets/js/core_map.js', __FILE__), 
        array('jquery'), 
        '1.9.5', 
        true
    );
    wp_register_script('nahiroimap_widget_js', plugins_url('assets/js/map_widget.js', __FILE__), array('jquery'), '3.1.0', true);
    // Encolar el script adicional
    wp_enqueue_script('nahiroimap_widget_js');
    // Registrar el estilo
    wp_register_style('nahiroimap_widget_css', plugins_url('assets/css/map_widget.css', __FILE__), array(), '1.3.0');
    // Encolar el estilo
    wp_enqueue_style('nahiroimap_widget_css');
    // Encolar el estilo dinámico adicional
    wp_enqueue_style('nahiroimap_dynamic_css', plugin_dir_url(__FILE__) . 'assets/css/map_dynamic.css', array(), '1.0.1');
}
add_action('wp_enqueue_scripts', 'nahiroimap_add_dependencies');

function nahiroimap_add_admin_dependencies($hook)
{
    global $pagenow;

    wp_enqueue_style('nahiroimap_dynamic_css', plugin_dir_url(__FILE__) . 'assets/css/map_dynamic.css', array(), '1.0.1');

    if (get_post_type() === 'nahiroimap-maps') {
        wp_enqueue_style('nahiroimap_metabox_css', plugin_dir_url(__FILE__) . 'assets/css/map_metabox.css', array(), '1.0.1');
        wp_enqueue_media();
        wp_enqueue_script('nahiroimap_tab_switcher_js', plugin_dir_url(__FILE__) . 'assets/js/tab_switcher.js', array('jquery'), '1.0.1', true);
		
        wp_enqueue_script('nahiroimap_main_metabox_js', plugin_dir_url(__FILE__) . 'assets/js/main_metabox.js', array('jquery'), '1.0.1', true);
		$img_url = array(
		 	'pluginUrl' => NAHIROIMAP_PLUGIN_URL,
		 );
		wp_localize_script('nahiroimap_main_metabox_js', 'ServerData', $img_url);

		
        wp_enqueue_script('nahiroimap_map_preview_metabox_js', plugin_dir_url(__FILE__) . 'assets/js/map_preview_metabox.js', array('jquery'), '1.0.1', true);
        $script_data = array(
            'pluginUrl' => plugin_dir_url(__FILE__),
        );
        wp_localize_script('nahiroimap_map_preview_metabox_js', 'ServerData', $script_data);

        wp_enqueue_style('nahiroimap_map_preview_metabox_css', NAHIROIMAP_PLUGIN_URL . 'assets/css/map_preview_metabox.css', array(),'1.0.1');

    }

    if(strpos($hook,"nahiroimap-plugins") != false){
        wp_enqueue_style('nahiroimap_map_font_css', NAHIROIMAP_PLUGIN_URL . 'assets/css/nhfont.css');
        /**
         * neccesary to show the modal properly
         */
        // Load ThickBox (for the modal functionality)
        wp_enqueue_script('thickbox');
        wp_enqueue_style('thickbox');
        // Load the WP scripts that handle plugin info modals
        wp_enqueue_script('plugin-install');
        wp_enqueue_script('updates');
    }
}
add_action('admin_enqueue_scripts', 'nahiroimap_add_admin_dependencies');

/****************************
 * Funciones de activacion
 **************************/
function nahiroimap_shortcode_map_add_welcome_page() {
    add_menu_page(
        __('Welcome to Nahiro.net Store Locations Map', 'store-locations-map'), // Page title
        __('Nahiro Store Locations Map Welcome', 'store-locations-map'), // Menu title
        'manage_options', // Capability
        'nahiroimap-shortcode-map-welcome', // Menu slug
        'nahiroimap_shortcode_setup_page_content' // Function to display the content
    );
}
add_action('admin_menu', 'nahiroimap_shortcode_map_add_welcome_page');

// Renders the welcome page and update an option on submit
function nahiroimap_shortcode_setup_page_content() {
    if (!current_user_can('manage_options')) {
        return;
    }
    // Procesar el formulario al enviar
    if (isset($_POST['submit'])) {
        check_admin_referer('nahiroimap_shortcode_setup'); // Verificación de nonce de seguridad
        // Obtener y sanitizar la opción seleccionada
        $country = isset($_POST['nahiroimap_country_option']) ? sanitize_text_field( wp_unslash( $_POST['nahiroimap_country_option'] ) ) : 'germany';
        update_option('nahiroimap_country_option', $country);
        // Marcar la configuración como completa
        update_option('nahiroimap_shortcode_setup_complete', true);
        // Redirigir después de guardar
        if (!headers_sent()) {
            wp_safe_redirect(admin_url('post-new.php?post_type=nahiroimap-maps'));
            exit;
        } else {
            // Agregar un campo oculto para indicar la redirección
            echo '<input type="hidden" id="nahiroimap-redirect-flag" value="1">';
            echo '<div class="wrap"> <a href="' . esc_url(admin_url('post-new.php?post_type=nahiroimap-maps')) . '" class="nahiro-link nahiro-fallback-redirect">' . esc_html( __('Click here to go to the plugin page', 'store-locations-map') ) . '</a></div>';
            return;
        }
    }

    require_once 'includes/welcome.php';
}

// Remove the welcome page from the admin menu
function nahiroimap_remove_shortcode_welcome_page(){
    remove_menu_page('nahiroimap-shortcode-map-welcome');
}
add_action('admin_menu', 'nahiroimap_remove_shortcode_welcome_page');

// Redirect to the welcome screen
function nahiroimap_shortcode_redirect_welcome() {
    // Check if the welcome page should be shown
    if (get_option('nahiroimap_shortcode_show_welcome')) {
        // Delete the option so it doesn’t show again
        delete_option('nahiroimap_shortcode_show_welcome');
        // Redirect to the welcome page
        wp_safe_redirect(admin_url('admin.php?page=nahiroimap-shortcode-map-welcome'));
        exit;
    }
}
add_action('admin_init', 'nahiroimap_shortcode_redirect_welcome');

// Add the styles of the welcome page
function nahiroimap_shortcode_welcome_styles($hook)
{
    if ($hook === 'toplevel_page_nahiroimap-shortcode-map-welcome') {
        wp_enqueue_style('nahiroimap_welcome_css', plugin_dir_url(__FILE__) . 'assets/css/welcome.css', array(), '1.0.0');
        wp_enqueue_script(
            'nahiroimap_welcome_js', plugins_url('assets/js/welcome.js', __FILE__), 
            array(),
            '1.3.1',
			true
        );
        // Localize script to pass data from PHP to JavaScript
        wp_localize_script('nahiroimap_welcome_js', 'nahiroRedirectData', array(
            'redirectUrl' => esc_url(admin_url('post-new.php?post_type=nahiroimap-maps'))
        ));
    }
}
add_action('admin_enqueue_scripts', 'nahiroimap_shortcode_welcome_styles', 9);
