<?php
/**
 * Map Field Handler - Dynamic Map Provider Support
 * 
 * @package HvnlyNab\Database\FieldTypes
 * @since 2.0.0
 */

namespace HvnlyNab\Database\FieldTypes;

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

class MapField extends BaseFieldType {
    
    /**
     * Debug flag - disable for production
     */
    private static $debug_enabled = false;
    
    public function __construct() {
        parent::__construct('map');
        $this->requires_assets = true;
    }
    
    public function render($field, $value, $post_id) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $map_provider = $settings_manager->get_map_provider();
        $google_api_key = $settings_manager->get_google_maps_api_key();
        $default_lat = $settings_manager->get_default_latitude();
        $default_lng = $settings_manager->get_default_longitude();
        $default_zoom = $settings_manager->get_map_zoom();
        
        $use_leaflet = in_array($map_provider, ['leaflet', 'openstreetmap']);
        $use_google = ($map_provider === 'google' && !empty($google_api_key));
        
        if ($map_provider === 'google' && empty($google_api_key)) {
            $use_leaflet = true;
            $use_google = false;
            $map_provider = 'leaflet';
        }
        
        $group_base_id = $field['group_base_id'] ?? '';
        $address_field_name = $field['address_field_name'] ?? ($group_base_id . '_address');
        $lat_field_name = $field['lat_field_name'] ?? ($group_base_id . '_latitude');
        $lng_field_name = $field['lng_field_name'] ?? ($group_base_id . '_longitude');
        
        $address_value = get_post_meta($post_id, $address_field_name, true);
        $lat_value = get_post_meta($post_id, $lat_field_name, true);
        $lng_value = get_post_meta($post_id, $lng_field_name, true);
        
        // Generate a clean map ID (replace hyphens with underscores for JavaScript)
        $raw_map_id = $group_base_id ?: $field['id'] ?? uniqid('map_');
        $map_id = 'hvnly_map_' . sanitize_html_class($raw_map_id);
        $js_callback = 'initGoogleMap_' . str_replace('-', '_', $map_id);
        
        $tile_url = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
        $attribution = '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
        
        if ($map_provider === 'openstreetmap') {
            $tile_url = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
            $attribution = '© OpenStreetMap contributors';
        }
        
        ob_start();
        ?>
<div data-field-id="<?php echo esc_attr($field['id'] ?? ''); ?>" data-field-type="map"
    data-map-group-id="<?php echo esc_attr($group_base_id); ?>"
    data-map-provider="<?php echo esc_attr($map_provider); ?>"
    data-address-field-name="<?php echo esc_attr($address_field_name); ?>"
    data-lat-field-name="<?php echo esc_attr($lat_field_name); ?>"
    data-lng-field-name="<?php echo esc_attr($lng_field_name); ?>"
    data-map-container-id="<?php echo esc_attr($map_id); ?>" data-js-callback="<?php echo esc_attr($js_callback); ?>">

    <div class="hvnly-map-field-wrapper" data-map-id="<?php echo esc_attr($map_id); ?>">
        <div class="hvnly-meta-field" style="display:block; margin:0;">
            <div class="hvnly-meta-label"
                style="display: flex; width: 100%; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 15px;">
                <div class="hvnly-map-provider-badge"
                    style="display: inline-flex; align-items: center; gap: 6px; background: #6C60FE15; padding: 4px 12px; border-radius: 20px; border-left: 3px solid #6C60FE;">
                    <i class="fas fa-map-marker-alt" style="color: #6C60FE; font-size: 12px;"></i>
                    <span style="font-size: 11px; font-weight: 500; color: #6C60FE;">
                        <?php 
                        if ($use_google) {
                            echo esc_html__('Google Maps', 'havenlytics');
                        } elseif ($map_provider === 'openstreetmap') {
                            echo esc_html__('OpenStreetMap (Direct)', 'havenlytics');
                        } else {
                            echo esc_html__('Leaflet (OpenStreetMap)', 'havenlytics');
                        }
                        ?> -
                        <?php echo !empty($lat_value) && !empty($lng_value) ? esc_html__('Coordinates Saved', 'havenlytics') : esc_html__('Set coordinates by searching or dragging marker', 'havenlytics'); ?>
                    </span>
                </div>

                <button type="button" class="button hvnly-geocode-address-btn"
                    data-map-id="<?php echo esc_attr($map_id); ?>"
                    data-address-field-name="<?php echo esc_attr($address_field_name); ?>"
                    data-lat-field-name="<?php echo esc_attr($lat_field_name); ?>"
                    data-lng-field-name="<?php echo esc_attr($lng_field_name); ?>"
                    data-map-provider="<?php echo esc_attr($map_provider); ?>"
                    style="display: inline-flex; align-items: center; gap: 6px;">
                    <i class="fas fa-map-pin"></i>
                    <?php esc_html_e('Get Coordinates from Address', 'havenlytics'); ?>
                </button>

                <div class="coordinates-info"
                    style="font-size: 11px; background: #f5f5f5; padding: 4px 10px; border-radius: 6px;">
                    <i class="fas fa-location-dot" style="color: #6C60FE; margin-right: 4px;"></i>
                    <strong><?php esc_html_e('Coordinates:', 'havenlytics'); ?></strong>
                    <span class="current-lat"
                        style="font-weight: 500;"><?php echo !empty($lat_value) ? esc_html(number_format((float)$lat_value, 6)) : '—'; ?></span>,
                    <span class="current-lng"
                        style="font-weight: 500;"><?php echo !empty($lng_value) ? esc_html(number_format((float)$lng_value, 6)) : '—'; ?></span>
                </div>
            </div>

            <!-- Live Address Display -->
            <div class="hvnly-map-live-address"
                style="margin-bottom: 15px; padding: 10px; background: #e8f0fe; border-radius: 6px; border-left: 3px solid #6C60FE;">
                <i class="fas fa-map-pin" style="color: #6C60FE; margin-right: 8px;"></i>
                <strong><?php esc_html_e('Current Address:', 'havenlytics'); ?></strong>
                <span class="hvnly-map-current-address" id="hvnly-current-address-<?php echo esc_attr($map_id); ?>">
                    <?php echo !empty($address_value) ? esc_html($address_value) : esc_html__('No address set', 'havenlytics'); ?>
                </span>
            </div>

            <div style="text-align: center; margin-bottom: 10px; font-size: 11px; color: #666;">
                <i class="fas fa-info-circle"></i>
                <?php esc_html_e('Enter address above, then click "Get Coordinates", or drag the marker on the map', 'havenlytics'); ?>
            </div>

            <div class="hvnly-meta-input hvnly-popup-meta-input">
                <?php if ($use_google) : ?>
                <div id="<?php echo esc_attr($map_id); ?>" class="hvnly-map-container hvnly-google-map-container"
                    data-map-id="<?php echo esc_attr($map_id); ?>" data-map-provider="google"
                    data-js-callback="<?php echo esc_attr($js_callback); ?>"
                    data-address-field-name="<?php echo esc_attr($address_field_name); ?>"
                    data-lat-field-name="<?php echo esc_attr($lat_field_name); ?>"
                    data-lng-field-name="<?php echo esc_attr($lng_field_name); ?>"
                    data-initial-lat="<?php echo esc_attr(!empty($lat_value) ? $lat_value : $default_lat); ?>"
                    data-initial-lng="<?php echo esc_attr(!empty($lng_value) ? $lng_value : $default_lng); ?>"
                    data-default-zoom="<?php echo esc_attr($default_zoom); ?>"
                    data-google-api-key="<?php echo esc_attr($google_api_key); ?>"
                    style="height: 400px; width: 100%; background: #f0f0f0; border: 1px solid #ddd; border-radius: 8px;">
                    <div class="hvnly-map-loading"
                        style="display: flex; align-items: center; justify-content: center; height: 100%; background: #f8f9fa; border-radius: 8px;">
                        <div style="text-align: center;">
                            <i class="fas fa-spinner fa-spin" style="font-size: 24px; color: #6C60FE;"></i>
                            <p><?php esc_html_e('Loading Google Map...', 'havenlytics'); ?></p>
                        </div>
                    </div>
                </div>
                <?php else : ?>
                <div id="<?php echo esc_attr($map_id); ?>" class="hvnly-map-container hvnly-leaflet-map-container"
                    data-map-id="<?php echo esc_attr($map_id); ?>"
                    data-map-provider="<?php echo esc_attr($map_provider); ?>"
                    data-tile-url="<?php echo esc_attr($tile_url); ?>"
                    data-tile-attribution="<?php echo esc_attr($attribution); ?>"
                    data-address-field-name="<?php echo esc_attr($address_field_name); ?>"
                    data-lat-field-name="<?php echo esc_attr($lat_field_name); ?>"
                    data-lng-field-name="<?php echo esc_attr($lng_field_name); ?>"
                    data-initial-lat="<?php echo esc_attr(!empty($lat_value) ? $lat_value : $default_lat); ?>"
                    data-initial-lng="<?php echo esc_attr(!empty($lng_value) ? $lng_value : $default_lng); ?>"
                    data-default-zoom="<?php echo esc_attr($default_zoom); ?>"
                    style="height: 400px; width: 100%; background: #f0f0f0; border: 1px solid #ddd; border-radius: 8px;">
                    <div class="hvnly-map-loading"
                        style="display: flex; align-items: center; justify-content: center; height: 100%; background: #f8f9fa; border-radius: 8px;">
                        <div style="text-align: center;">
                            <i class="fas fa-spinner fa-spin" style="font-size: 24px; color: #6C60FE;"></i>
                            <p><?php esc_html_e('Loading map...', 'havenlytics'); ?></p>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<style>
.hvnly-map-provider-badge {
    transition: all 0.2s ease;
}

.hvnly-map-latitude,
.hvnly-map-longitude {
    transition: border-color 0.2s ease;
}

.hvnly-google-map-container {
    width: 100%;
}

.hvnly-map-live-address {
    transition: all 0.2s ease;
}

.hvnly-map-live-address:hover {
    background: #e0e8f8;
}
</style>
<?php
        return ob_get_clean();
    }
    
    public function save($post_id, $field_name, $value) { return; }
    public function sanitize($value) { return sanitize_text_field($value); }
    public function validate($value, $field) { return true; }
    public function enqueue_assets() {}
}