<?php
/**
 * Plugin Name: Set Location
 * Description: Adiciona um seletor de localização via mapa (Leaflet + OpenStreetMap) em post types configuráveis.
 * Version: 1.0
 * Author: Seu Nome
 * Text Domain: set-location
 * License: GPL v2 or later
 */

if ( ! defined( 'ABSPATH' ) ) { exit; }

define( 'SETLOCATION_PATH', plugin_dir_path( __FILE__ ) );
define( 'SETLOCATION_URL', plugin_dir_url( __FILE__ ) );

class Set_Location {

	private const META_KEYS = [
		'lat'       => '_sl_lat',
		'lng'       => '_sl_lng',
		'zoom'      => '_sl_zoom',
		'title'     => '_sl_title',
		'content'   => '_sl_content',
	];

	private $enabled_post_types = [];

	public function __construct() {
		add_action( 'admin_init', [ $this, 'register_settings' ] );
		add_action( 'admin_menu', [ $this, 'add_admin_page' ] );
		add_action( 'add_meta_boxes', [ $this, 'add_location_meta_box' ] );
		add_action( 'save_post', [ $this, 'save_location_data' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_front_assets' ] );
		add_shortcode( 'set_location_map', [ $this, 'render_map_shortcode' ] );
	}

	// ==========================================
	// 1. CONFIGURAÇÕES: QUAIS POST TYPES RECEBEM O MAPA
	// ==========================================
	public function register_settings() {
		register_setting( 'set_location_options', 'set_location_post_types', [
			'sanitize_callback' => [ $this, 'sanitize_post_types' ],
		] );
	
        register_setting( 'set_location_options', 'set_location_zoom', [
            'sanitize_callback' => function( $input ) {
                $zoom = absint( $input );
                return max( 1, min( 18, $zoom ) ); // Garante 1-18
            },
        ] );

        register_setting( 'set_location_options', 'set_location_default_lat', [
            'sanitize_callback' => function( $input ) {
                $val = floatval( $input );
                return max( -90.0, min( 90.0, $val ) );
            },
        ] );

        register_setting( 'set_location_options', 'set_location_default_lng', [
            'sanitize_callback' => function( $input ) {
                $val = floatval( $input );
                return max( -180.0, min( 180.0, $val ) );
            },
        ] );
	}

	public function sanitize_post_types( $input ) {
		$valid = get_post_types( [ 'public' => true ], 'names' );
		return array_intersect( (array) $input, $valid );
	}

	public function add_admin_page() {
		add_options_page(
			__( 'Set Location', 'set-location' ),
			__( 'Set Location', 'set-location' ),
			'manage_options',
			'set-location',
			[ $this, 'render_admin_page' ]
		);
	}

	public function render_admin_page() {
		$saved = get_option( 'set_location_post_types', [] );
		$all   = get_post_types( [ 'public' => true ], 'objects' );
		?>
		<div class="wrap">
			<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
			<form method="post" action="options.php">
				<?php settings_fields( 'set_location_options' ); ?>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Post types com localização', 'set-location' ); ?></th>
						<td>
							<?php foreach ( $all as $pt_slug => $pt_obj ) : ?>
								<label style="display:block; margin:4px 0;">
									<input type="checkbox" name="set_location_post_types[]" value="<?php echo esc_attr( $pt_slug ); ?>"
										<?php checked( in_array( $pt_slug, $saved, true ) ); ?>>
									<?php echo esc_html( $pt_obj->label ); ?>
								</label>
							<?php endforeach; ?>
							<p class="description"><?php esc_html_e( 'Marque os tipos de post que terão o seletor de localização.', 'set-location' ); ?></p>
						</td>
					</tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Localização padrão', 'set-location' ); ?></th>
                        <td>
                            <label>
                                <?php esc_html_e( 'Latitude:', 'set-location' ); ?>
                                <input type="number" step="any" style="width: 7em;" name="set_location_default_lat" 
                                    value="<?php echo esc_attr( get_option( 'set_location_default_lat', -22.291380 ) ); ?>" 
                                    class="small-text" min="-90" max="90">
                            </label>
                            <label style="margin-left: 15px;">
                                <?php esc_html_e( 'Longitude:', 'set-location' ); ?>
                                <input type="number" step="any" style="width: 7em;" name="set_location_default_lng" 
                                    value="<?php echo esc_attr( get_option( 'set_location_default_lng', -42.384675 ) ); ?>" 
                                    class="small-text" min="-180" max="180">
                            </label>
                            <p class="description">
                                <?php esc_html_e( 'Centro inicial do mapa no admin quando não há coordenadas salvas. Use ponto decimal (ex: -22.9068, -43.1729).', 'set-location' ); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="set_location_zoom"><?php esc_html_e( 'Zoom padrão', 'set-location' ); ?></label></th>
                        <td>
                            <input type="number" id="set_location_zoom" name="set_location_zoom" 
                                value="<?php echo esc_attr( get_option( 'set_location_zoom', 8 ) ); ?>" 
                                min="1" max="18" step="1" class="small-text">
                            <p class="description">
                                <?php esc_html_e( 'Nível de zoom ao carregar o mapa no admin e no frontend (1 = mundial, 18 = nível de rua).', 'set-location' ); ?>
                            </p>
                        </td>
                    </tr>
				</table>
				<?php submit_button(); ?>
			</form>
		</div>
		<?php
	}

	// ==========================================
	// 2. META BOX: SELETOR DE LOCALIZAÇÃO
	// ==========================================
    public function add_location_meta_box() {
        $this->enabled_post_types = get_option( 'set_location_post_types', [] );
        foreach ( $this->enabled_post_types as $pt ) {
            // 1. Mapa (coluna principal - advanced)
            add_meta_box(
                'set_location_map_box',
                __( 'Mapa: clique para definir', 'set-location' ),
                [ $this, 'render_map_box' ],
                $pt,
                'advanced',
                'default'
            );
            
            // 2. Dados do pin (sidebar - side)
            add_meta_box(
                'set_location_data_box',
                __( 'Dados do Marcador', 'set-location' ),
                [ $this, 'render_data_box' ],
                $pt,
                'advanced',
                'default'
            );
        }
    }

    public function render_map_box( $post ) {
        wp_nonce_field( 'set_location_nonce', 'set_location_nonce' );
        
        $lat  = get_post_meta( $post->ID, self::META_KEYS['lat'], true );
        $lng  = get_post_meta( $post->ID, self::META_KEYS['lng'], true );
        $zoom = get_post_meta( $post->ID, self::META_KEYS['zoom'], true );
        ?>
        <div id="set-location-map" style="height:350px; width:100%; border:1px solid #ccd0d4;"></div>
        <p class="description">
            <?php esc_html_e( 'Clique no mapa para posicionar ou mover o marcador. Use a roda do mouse para ajustar o zoom.', 'set-location' ); ?>
        </p>
        <!-- Campos ocultos para salvar -->
        <input type="hidden" id="sl_lat" name="sl_lat" value="<?php echo esc_attr( $lat ); ?>">
        <input type="hidden" id="sl_lng" name="sl_lng" value="<?php echo esc_attr( $lng ); ?>">
        <input type="hidden" id="sl_zoom" name="sl_zoom" value="<?php echo esc_attr( $zoom ?: get_option( 'set_location_zoom', 8 ) ); ?>">
        <?php
    }

    public function render_data_box( $post ) {
        $lat     = get_post_meta( $post->ID, self::META_KEYS['lat'], true );
        $lng     = get_post_meta( $post->ID, self::META_KEYS['lng'], true );
        $zoom    = get_post_meta( $post->ID, self::META_KEYS['zoom'], true );
        $title   = get_post_meta( $post->ID, self::META_KEYS['title'], true );
        $content = get_post_meta( $post->ID, self::META_KEYS['content'], true );
        $default_zoom = get_option( 'set_location_zoom', 8 );
        ?>
        <div class="columns" style="display: flex; gap: 1rem;">
            <div class="col" style="flex: 1;">
                <p>
                    <label><?php esc_html_e( 'Coordenadas', 'set-location' ); ?></label>
                    <input type="text" id="sl_lat_display" value="<?php echo esc_attr( $lat ); ?>" class="widefat" readonly style="background:#f6f7f7; margin-bottom:4px; font-family:monospace;">
                    <input type="text" id="sl_lng_display" value="<?php echo esc_attr( $lng ); ?>" class="widefat" readonly style="background:#f6f7f7; font-family:monospace;">
                </p>
                <p>
                    <label for="sl_zoom"><?php esc_html_e( 'Zoom', 'set-location' ); ?></label>
                    <input type="number" id="sl_zoom_input" name="sl_zoom" value="<?php echo esc_attr( $zoom ?: $default_zoom ); ?>" min="1" max="18" class="widefat">
                    <span class="description" style="display:block; margin-top:4px;">
                        <?php printf( esc_html__( 'Padrão global: %d', 'set-location' ), $default_zoom ); ?>
                    </span>
                </p>
            </div>
            <div class="col" style="flex: 1;">
                <p>
                    <label for="sl_title"><?php esc_html_e( 'Título', 'set-location' ); ?></label>
                    <input type="text" id="sl_title" name="sl_title" value="<?php echo esc_attr( $title ); ?>" class="widefat">
                </p>
                <p>
                    <label for="sl_content"><?php esc_html_e( 'Conteúdo da popup', 'set-location' ); ?></label>
                    <textarea id="sl_content" name="sl_content" rows="4" class="widefat"><?php echo esc_textarea( $content ); ?></textarea>
                </p>
                <p class="description">
                    <?php esc_html_e( 'O link "Como chegar" é gerado automaticamente.', 'set-location' ); ?>
                </p>
            </div>
        </div>
        <?php
    }

    public function save_location_data( $post_id ) {
        if ( ! isset( $_POST['set_location_nonce'] ) || ! wp_verify_nonce( $_POST['set_location_nonce'], 'set_location_nonce' ) ) return;
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
        if ( ! current_user_can( 'edit_post', $post_id ) ) return;

        $enabled = get_option( 'set_location_post_types', [] );
        if ( ! in_array( get_post_type( $post_id ), $enabled, true ) ) return;

        $fields = [
            'sl_lat'     => self::META_KEYS['lat'],
            'sl_lng'     => self::META_KEYS['lng'],
            'sl_zoom'    => self::META_KEYS['zoom'],  // ✅ Novo campo
            'sl_title'   => self::META_KEYS['title'],
            'sl_content' => self::META_KEYS['content'],
        ];

        foreach ( $fields as $input_name => $meta_key ) {
            if ( isset( $_POST[ $input_name ] ) ) {
                if ( 'sl_zoom' === $input_name ) {
                    $value = max( 1, min( 18, absint( $_POST[ $input_name ] ) ) );
                } elseif ( 'sl_content' === $input_name ) {
                    $value = wp_kses_post( $_POST[ $input_name ] );
                } else {
                    $value = sanitize_text_field( $_POST[ $input_name ] );
                }
                update_post_meta( $post_id, $meta_key, $value );
            }
        }
    }

	// ==========================================
	// 3. ASSETS: LEAFLET + CSS
	// ==========================================
	public function enqueue_admin_assets( $hook ) {
		if ( ! in_array( $hook, [ 'post.php', 'post-new.php' ], true ) ) return;
		$screen = get_current_screen();
		if ( ! in_array( $screen->post_type, $this->enabled_post_types, true ) ) return;

		wp_enqueue_style( 'set-location-leaflet', SETLOCATION_URL . 'assets/css/leaflet.css' );
		wp_enqueue_script( 'set-location-leaflet', SETLOCATION_URL . 'assets/js/leaflet.js', [], null, true );
		wp_enqueue_script( 'set-location-admin', SETLOCATION_URL . 'assets/js/admin.js', [ 'jquery', 'set-location-leaflet' ], null, true );
		
        wp_localize_script( 'set-location-admin', 'setLocationData', [
            'pluginUrl'    => SETLOCATION_URL,
            'default_lat'  => get_option( 'set_location_default_lat', -14.235004 ),
            'default_lng'  => get_option( 'set_location_default_lng', -51.92528 ),
            'default_zoom' => get_option( 'set_location_zoom', 8 ),
            'attribution'  => '&copy; <a href="https://openstreetmap.org">OpenStreetMap</a>',
        ] );
	}

    public function enqueue_front_assets() {
        if ( ! is_singular( $this->enabled_post_types ) ) return;
        $post_id = get_the_ID();
        $lat = get_post_meta( $post_id, self::META_KEYS['lat'], true );
        if ( ! $lat ) return;

        wp_enqueue_style( 'set-location-leaflet', SETLOCATION_URL . 'assets/css/leaflet.css' );
        wp_enqueue_script( 'set-location-leaflet', SETLOCATION_URL . 'assets/js/leaflet.js', [], null, true );
        
        // ✅ Enfileira o front.js separado
        wp_enqueue_script( 'set-location-front', SETLOCATION_URL . 'assets/js/front.js', [ 'set-location-leaflet' ], null, true );
        
        // Passa dados via wp_localize_script (mais limpo que dataset no HTML)
        wp_localize_script( 'set-location-front', 'setLocationFront', [
            'post_id' => $post_id,
            'lat'     => $lat,
            'lng'     => get_post_meta( $post_id, self::META_KEYS['lng'], true ),
            'title'   => get_post_meta( $post_id, self::META_KEYS['title'], true ) ?: get_the_title(),
            'content' => wp_kses_post( get_post_meta( $post_id, self::META_KEYS['content'], true ) ),
            'osmLink' => 'https://www.openstreetmap.org/directions?to=' . rawurlencode( $lat . ',' . get_post_meta( $post_id, self::META_KEYS['lng'], true ) ),
            'attribution' => '&copy; <a href="https://openstreetmap.org">OpenStreetMap</a>',
        ] );
    }

	// ==========================================
	// 4. FRONTEND: RENDERIZAÇÃO DO MAPA
	// ==========================================

    static public function get_location_data( $post_id = null ) {
        if ( ! $post_id ) $post_id = get_the_ID();
        
        $lat = get_post_meta( $post_id, self::META_KEYS['lat'], true );
        if ( ! $lat ) return false;

        $lng = get_post_meta( $post_id, self::META_KEYS['lng'], true );
        $zoom = get_post_meta( $post_id, self::META_KEYS['zoom'], true ) ?: get_option( 'set_location_zoom', 8 );

        return compact('lat', 'lng', 'zoom');
    }

    /**
     * Função principal: gera o HTML do mapa com data-* attributes.
     * Pode ser chamada via PHP no tema ou via shortcode.
     */
    public function render_location_map( $post_id = null ) {
        if ( ! $post_id ) $post_id = get_the_ID();
        
        $lat = get_post_meta( $post_id, self::META_KEYS['lat'], true );
        if ( ! $lat ) return ''; // Sem localização → retorna vazio

        $lng       = get_post_meta( $post_id, self::META_KEYS['lng'], true );
        $zoom      = get_post_meta( $post_id, self::META_KEYS['zoom'], true ) ?: get_option( 'set_location_zoom', 8 );
        $title     = get_post_meta( $post_id, self::META_KEYS['title'], true ) ?: get_the_title( $post_id );
        $content   = get_post_meta( $post_id, self::META_KEYS['content'], true );
        $osm_link  = 'https://www.openstreetmap.org/directions?to=' . rawurlencode( $lat . ',' . $lng );

        // Garante que assets estão na fila
        $this->enqueue_front_assets();

        // ✅ Gera container com TODOS os data-* que o front.js espera
        return sprintf(
            '<div class="set-location-map" data-lat="%s" data-lng="%s" data-zoom="%d" data-title="%s" data-content="%s" data-osm-link="%s" style="min-height:360px;"></div>',
            esc_attr( $lat ),
            esc_attr( $lng ),
            absint( $zoom ),
            esc_attr( $title ),
            esc_attr( $content ),
            esc_url( $osm_link )
        );
    }

    /**
     * Shortcode apenas chama a função principal (mantém compatibilidade)
     */
    public function render_map_shortcode( $atts ) {
        return $this->render_location_map();
    }
}

new Set_Location();