<?php
/**
 * Plugin Name: Bro Hangs Map
 * Description: Displays a map of legendary bro hangouts.
 * Version: 1.0.0
 * Author: Real Bro
 */

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

// Register CPT
add_action('init', 'bro_register_hangout_cpt');
function bro_register_hangout_cpt() {
    $labels = array(
        'name' => 'Hangouts',
        'singular_name' => 'Hangout',
        'menu_name' => 'Party Map',
        'add_new' => 'Add New Hangout',
        'add_new_item' => 'Add New Hangout',
        'edit_item' => 'Edit Hangout',
        'new_item' => 'New Hangout',
        'view_item' => 'View Hangout',
        'search_items' => 'Search Hangouts',
        'not_found' => 'No hangouts found',
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'has_archive' => true,
        'menu_icon' => 'dashicons-location-alt',
        'supports' => array('title', 'editor', 'thumbnail'),
        'show_in_rest' => true,
    );
    register_post_type('bro_hangout', $args);
}

// Add Meta Boxes for Latitude and Longitude
add_action('add_meta_boxes', 'bro_add_hangout_meta_boxes');
function bro_add_hangout_meta_boxes() {
    add_meta_box('bro_hangout_location', 'Hangout Location', 'bro_hangout_location_callback', 'bro_hangout', 'normal', 'high');
}

function bro_hangout_location_callback($post) {
    $lat = get_post_meta($post->ID, '_bro_lat', true);
    $lng = get_post_meta($post->ID, '_bro_lng', true);
    wp_nonce_field('bro_hangout_save', 'bro_hangout_nonce');
    ?>
    <p>
        <label for="bro_lat">Latitude:</label>
        <input type="text" id="bro_lat" name="bro_lat" value="<?php echo esc_attr($lat); ?>" class="widefat">
    </p>
    <p>
        <label for="bro_lng">Longitude:</label>
        <input type="text" id="bro_lng" name="bro_lng" value="<?php echo esc_attr($lng); ?>" class="widefat">
    </p>
    <p class="description">Pro tip: Use Google Maps or similar to get coordinates. (e.g. 40.7128, -74.0060)</p>
    <?php
}

add_action('save_post', 'bro_save_hangout_meta');
function bro_save_hangout_meta($post_id) {
    if (!isset($_POST['bro_hangout_nonce']) || !wp_verify_nonce($_POST['bro_hangout_nonce'], 'bro_hangout_save')) return;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    if (isset($_POST['bro_lat'])) update_post_meta($post_id, '_bro_lat', sanitize_text_field($_POST['bro_lat']));
    if (isset($_POST['bro_lng'])) update_post_meta($post_id, '_bro_lng', sanitize_text_field($_POST['bro_lng']));
}

// Shortcode to display the map
add_shortcode('bro_map', 'bro_display_map');
function bro_display_map() {
    wp_enqueue_style('leaflet-css', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css');
    wp_enqueue_script('leaflet-js', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js', array(), null, true);

    ob_start();
    ?>
    <div id="bro-party-map" style="height: 500px; width: 100%; border-radius: 15px; border: 3px solid #FFBF00; margin: 20px 0;"></div>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof L === 'undefined') return;

            var map = L.map('bro-party-map').setView([40.7128, -74.0060], 13);
            L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
                subdomains: 'abcd',
                maxZoom: 20
            }).addTo(map);

            // Fetch hangouts via REST API
            fetch('/wp-json/wp/v2/bro_hangout?_embed')
                .then(response => response.json())
                .then(hangouts => {
                    var bounds = [];
                    hangouts.forEach(hangout => {
                        var lat = hangout.meta ? hangout.meta._bro_lat : null;
                        var lng = hangout.meta ? hangout.meta._bro_lng : null;

                        // Fallback to searching meta directly if not in REST (REST meta needs registration)
                        // For now, let's use a custom endpoint or ensure meta is public
                        if (!lat || !lng) {
                            // If REST doesn't show meta, we might need a custom endpoint
                        }
                    });
                });

            // Since REST meta registration is a bit verbose, let's inject markers directly for now via PHP localized script or just a simple global
            <?php
            $hangouts = get_posts(array('post_type' => 'bro_hangout', 'numberposts' => -1));
            $markers = array();
            foreach ($hangouts as $h) {
                $lat = get_post_meta($h->ID, '_bro_lat', true);
                $lng = get_post_meta($h->ID, '_bro_lng', true);
                if ($lat && $lng) {
                    $markers[] = array(
                        'lat' => (float)$lat,
                        'lng' => (float)$lng,
                        'title' => $h->post_title,
                        'content' => wp_trim_words($h->post_content, 20),
                        'link' => get_permalink($h->ID)
                    );
                }
            }
            ?>
            var markers = <?php echo json_encode($markers); ?>;
            var group = L.featureGroup();

            markers.forEach(function(m) {
                var marker = L.marker([m.lat, m.lng]).addTo(map);
                marker.bindPopup("<b>" + m.title + "</b><br>" + m.content + "<br><a href='" + m.link + "' style='color:#FFBF00;'>Check it out</a>");
                group.addLayer(marker);
            });

            if (markers.length > 0) {
                map.fitBounds(group.getBounds());
            }
        });
    </script>
    <style>
        .leaflet-popup-content-wrapper {
            background: #1a1a1a;
            color: #fff;
            border: 1px solid #FFBF00;
        }
        .leaflet-popup-tip {
            background: #FFBF00;
        }
    </style>
    <?php
    return ob_get_clean();
}
