<?php
/**
 * Plugin Name: Mapbox CPT Pins
 * Description: Displays a Mapbox map with pins from a custom post type, filterable by category.
 * Version: 1.0.1
 * Author: You
 */

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

class Mapbox_CPT_Pins_Plugin {
    const OPTION_KEY = 'mapbox_cpt_pins_settings';
    const CPT = 'ponto';
    const TAX = 'map_category';
    const META_LAT = '_mb_pin_lat';
    const META_LNG = '_mb_pin_lng';

    public function __construct() {
        add_action('admin_menu', [$this, 'register_settings_page']);
        add_action('admin_init', [$this, 'register_settings']);

        add_shortcode('mapbox_pins_map', [$this, 'shortcode_map']);

        add_action('wp_enqueue_scripts', [$this, 'register_assets']);
        add_action('wp_ajax_mapbox_cpt_pins_get', [$this, 'ajax_get_pins']);
        add_action('wp_ajax_nopriv_mapbox_cpt_pins_get', [$this, 'ajax_get_pins']);
    }

    public function register_assets() {
        // Mapbox GL JS (CDN)
        wp_register_style(
            'mapbox-gl',
            'https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css',
            [],
            '2.15.0'
        );

        wp_register_script(
            'mapbox-gl',
            'https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js',
            [],
            '2.15.0',
            true
        );

        // Plugin assets
        wp_register_style(
            'mapbox-cpt-pins',
            plugin_dir_url(__FILE__) . 'assets/map.css',
            [],
            '1.0.1'
        );

        wp_register_script(
            'mapbox-cpt-pins',
            plugin_dir_url(__FILE__) . 'assets/map.js',
            ['mapbox-gl'],
            '1.0.1',
            true
        );
    }

    public function register_settings_page() {
        add_options_page(
            'Mapbox CPT Pins',
            'Mapbox CPT Pins',
            'manage_options',
            'mapbox-cpt-pins',
            [$this, 'render_settings_page']
        );
    }

    public function register_settings() {
        register_setting('mapbox_cpt_pins_group', self::OPTION_KEY);

        add_settings_section(
            'mapbox_cpt_pins_main',
            'Map Settings',
            function () {
                echo '<p>Configure Mapbox settings for the frontend map.</p>';
            },
            'mapbox-cpt-pins'
        );

        $fields = [
            'access_token' => 'Mapbox Access Token',
            'style_url' => 'Mapbox Style URL',
            'default_lat' => 'Default Center Latitude',
            'default_lng' => 'Default Center Longitude',
            'default_zoom' => 'Default Zoom',
            'marker_color' => 'Marker Color (hex)',
        ];

        foreach ($fields as $key => $label) {
            add_settings_field(
                $key,
                $label,
                function () use ($key) {
                    $opts = get_option(self::OPTION_KEY, []);
                    $val = isset($opts[$key]) ? $opts[$key] : '';

                    $placeholder = '';
                    if ($key === 'style_url') $placeholder = 'mapbox://styles/yourname/xxxx';
                    if ($key === 'default_lat') $placeholder = '41.1579';
                    if ($key === 'default_lng') $placeholder = '-8.6291';
                    if ($key === 'default_zoom') $placeholder = '10';
                    if ($key === 'marker_color') $placeholder = '#e11d48';

                    $type = ($key === 'access_token') ? 'password' : 'text';

                    echo '<input type="' . esc_attr($type) . '" name="' . esc_attr(self::OPTION_KEY) . '[' . esc_attr($key) . ']" value="' . esc_attr($val) . '" style="width:420px;max-width:100%;" placeholder="' . esc_attr($placeholder) . '" />';
                },
                'mapbox-cpt-pins',
                'mapbox_cpt_pins_main'
            );
        }
    }

    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1>Mapbox CPT Pins</h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('mapbox_cpt_pins_group');
                do_settings_sections('mapbox-cpt-pins');
                submit_button();
                ?>
            </form>

            <hr />
            <h2>Usage</h2>
            <p>Use this shortcode anywhere:</p>
            <code>[mapbox_pins_map]</code>
            <p>You can also set a custom height:</p>
            <code>[mapbox_pins_map height="600px"]</code>
        </div>
        <?php
    }

    public function shortcode_map($atts) {
        $atts = shortcode_atts([
            'height' => '520px',
        ], $atts);

        $opts = get_option(self::OPTION_KEY, []);

        $access_token = $opts['access_token'] ?? '';
        $style_url = $opts['style_url'] ?? '';
        $default_lat = $opts['default_lat'] ?? '41.1579';
        $default_lng = $opts['default_lng'] ?? '-8.6291';
        $default_zoom = $opts['default_zoom'] ?? '10';
        $marker_color = $opts['marker_color'] ?? '#e11d48';

        // Enqueue scripts only when shortcode is used
        wp_enqueue_style('mapbox-gl');
        wp_enqueue_script('mapbox-gl');
        wp_enqueue_style('mapbox-cpt-pins');
        wp_enqueue_script('mapbox-cpt-pins');

        // Categories for the filter UI
        $terms = get_terms([
            'taxonomy' => "tipo",
            'hide_empty' => true,
        ]);

        $categories = [];
        if (!is_wp_error($terms)) {
            foreach ($terms as $t) {
                $categories[] = [
                    'id' => $t->term_id,
                    'name' => $t->name,
                    'slug' => $t->slug,
                ];
            }
        }

        // IMPORTANT:
        // Instead of wp_localize_script / wp_add_inline_script,
        // we print JSON config into the HTML, so caching/minifiers can't break it.
        $config = [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('mb_cpt_pins_nonce'),
            'access_token' => $access_token,
            'style_url' => $style_url,
            'default_lat' => floatval($default_lat),
            'default_lng' => floatval($default_lng),
            'default_zoom' => floatval($default_zoom),
            'marker_color' => $marker_color,
            'categories' => $categories,
        ];

        ob_start();
        ?>
        <div class="mb-pins-wrap">

            <div class="mb-pins-filter">
                <label for="mb-pins-category"><strong>Filter</strong></label>
                <select id="mb-pins-category">
                    <option value="">All categories</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo esc_attr($cat['id']); ?>">
                            <?php echo esc_html($cat['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <script type="application/json" id="mb-cpt-pins-config">
                <?php echo wp_json_encode($config); ?>
            </script>

            <div id="mb-pins-map" style="height: <?php echo esc_attr($atts['height']); ?>"></div>

            <div class="mb-pins-list" id="mb-pins-list"></div>
            
            
        </div>
        <?php
        return ob_get_clean();
    }

    public function ajax_get_pins() {
        check_ajax_referer('mb_cpt_pins_nonce', 'nonce');

        $cat_id = isset($_GET['cat_id']) ? intval($_GET['cat_id']) : 0;

        $args = [
            'post_type' => "ponto",
            'post_status' => 'publish',
            'posts_per_page' => -1,
        ];

        if (false) {
            $args['tax_query'] = [
                [
                    'taxonomy' => self::TAX,
                    'field' => 'term_id',
                    'terms' => [$cat_id],
                ]
            ];
        }

        $q = new WP_Query($args);

        $pins = [];

        while ($q->have_posts()) {
            $q->the_post();
            $id = get_the_ID();

            $lat = get_post_meta($id, "latitude", true);
            $lng = get_post_meta($id, "longitude", true);

            if ($lat === '' || $lng === '') continue;

            $terms = get_the_terms($id, self::TAX);
            $term_names = [];
            if ($terms && !is_wp_error($terms)) {
                foreach ($terms as $t) $term_names[] = $t->name;
            }

            $pins[] = [
                'id' => $id,
                'title' => get_the_title(),
                'excerpt' => wp_strip_all_tags(get_the_excerpt()),
                'content' => wp_strip_all_tags(get_the_content()),
                'lat' => floatval($lat),
                'lng' => floatval($lng),
                'permalink' => get_permalink(),
                'categories' => $term_names,
            ];
        }

        wp_reset_postdata();

        wp_send_json_success([
            'pins' => $pins
        ]);
    }
}

new Mapbox_CPT_Pins_Plugin();
