<?php

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

class AIEO_Store_Map_Block {

    private static $registered = false;

    public static function register() {
        if (self::$registered) { return; }
        self::$registered = true;
        add_action('init', array(__CLASS__, 'register_block'));
        add_shortcode('aieo_store_map', array(__CLASS__, 'shortcode'));
    }

    public static function register_block() {
        register_block_type('aieo/store-map', array(
            'api_version'     => 3,
            'title'           => __('AIEO Store Map', 'ai-eshop-optimizer'),
            'description'     => __("A single store's location map (keyless Google Maps embed) + directions link. Auto-resolves on a store page, or set a location slug.", 'ai-eshop-optimizer'),
            'category'        => 'widgets',
            'icon'            => 'location',
            'keywords'        => array('map', 'location', 'directions', 'store', 'shop'),
            'supports'        => array('align' => array('wide')),
            'attributes'      => array(
                'locationSlug' => array('type' => 'string', 'default' => ''),
                'height'       => array('type' => 'number', 'default' => 320),
                'aspect'       => array('type' => 'string', 'default' => ''),
                'showDirections' => array('type' => 'boolean', 'default' => true),
            ),
            'uses_context'    => array('postId'),
            'render_callback' => array(__CLASS__, 'render'),
        ));
    }

    public static function shortcode($atts) {
        $atts = shortcode_atts(array('location' => '', 'height' => 320, 'aspect' => '', 'directions' => '1'), $atts, 'aieo_store_map');
        return self::render(array(
            'locationSlug'   => (string) $atts['location'],
            'height'         => (int) $atts['height'],
            'aspect'         => (string) $atts['aspect'],
            'showDirections' => !in_array((string) $atts['directions'], array('0', 'no', 'false', ''), true),
        ));
    }

    public static function render($attrs, $content = '', $block = null) {
        if (!class_exists('AIEO_Google_Reviews_Helpers')) { return ''; }
        $attrs = wp_parse_args(is_array($attrs) ? $attrs : array(), array(
            'locationSlug' => '', 'height' => 320, 'aspect' => '', 'showDirections' => true,
        ));
        $loc = AIEO_Google_Reviews_Helpers::resolve_single($attrs['locationSlug'], $block);
        if (!$loc) { return ''; }

        $query = self::map_query($loc);
        if ($query === '') { return ''; }

        $height = max(160, min(720, (int) $attrs['height']));
        
        
        
        $aspect = preg_replace('/[^0-9.\/]/', '', (string) $attrs['aspect']);
        $frame_style = ($aspect !== '' && strpos($aspect, '/') !== false)
            ? 'aspect-ratio:' . $aspect . ';'
            : 'height:' . (int) $height . 'px;';
        $embed  = 'https://maps.google.com/maps?q=' . rawurlencode($query) . '&z=15&hl='
            . rawurlencode((string) ($loc['language'] ?? 'el')) . '&output=embed';
        $label  = (string) ($loc['label'] ?? '');

        $wrap = function_exists('get_block_wrapper_attributes')
            ? get_block_wrapper_attributes(array('class' => 'aieo-store-map'))
            : 'class="aieo-store-map"';

        ob_start();
        ?>
<div <?php echo $wrap; ?>>
    <div class="aieo-store-map__frame" style="<?php echo esc_attr($frame_style); ?>">
        <iframe
            title="<?php echo esc_attr(sprintf(__('Map — %s', 'ai-eshop-optimizer'), $label !== '' ? $label : __('store location', 'ai-eshop-optimizer'))); ?>"
            src="<?php echo esc_url($embed); ?>"
            width="100%" height="100%" style="border:0;display:block;"
            loading="lazy" referrerpolicy="no-referrer-when-downgrade"
            allowfullscreen></iframe>
    </div>
    <?php if (!empty($attrs['showDirections'])) :
        $dir = self::directions_url($loc);
        if ($dir !== '') : ?>
        <a class="aieo-store-map__dir" href="<?php echo esc_url($dir); ?>" target="_blank" rel="noopener noreferrer">
            <?php echo esc_html__('Get directions', 'ai-eshop-optimizer'); ?>
        </a>
    <?php endif; endif; ?>
</div>
        <?php
        $html = (string) ob_get_clean();
        self::print_style_once();
        return $html;
    }

    
    private static function map_query($loc) {
        $lat = isset($loc['lat']) && $loc['lat'] !== null && $loc['lat'] !== '' ? (float) $loc['lat'] : null;
        $lng = isset($loc['lng']) && $loc['lng'] !== null && $loc['lng'] !== '' ? (float) $loc['lng'] : null;
        if ($lat !== null && $lng !== null && ($lat !== 0.0 || $lng !== 0.0)) {
            return $lat . ',' . $lng;
        }
        $addr = trim(implode(' ', array_filter(array(
            (string) ($loc['street'] ?? ''),
            (string) ($loc['postcode'] ?? ''),
            (string) ($loc['locality'] ?? ''),
            (string) ($loc['country'] ?? ''),
        ))));
        if ($addr !== '') { return $addr; }
        $a = trim((string) ($loc['address'] ?? ''));
        if ($a !== '') { return $a; }
        return trim((string) ($loc['label'] ?? ''));
    }

    
    private static function directions_url($loc) {
        $place_id = trim((string) ($loc['place_id'] ?? ''));
        if ($place_id !== '') {
            return 'https://www.google.com/maps/dir/?api=1&destination='
                . rawurlencode(self::map_query($loc)) . '&destination_place_id=' . rawurlencode($place_id);
        }
        $q = self::map_query($loc);
        return $q !== '' ? 'https://www.google.com/maps/dir/?api=1&destination=' . rawurlencode($q) : '';
    }

    private static function print_style_once() {
        static $done = false;
        if ($done) { return; }
        $done = true;
        $css = '.aieo-store-map{margin:0}'
            . '.aieo-store-map__frame{position:relative;width:100%;border-radius:14px;overflow:hidden;background:#eceae6;box-shadow:0 1px 3px rgba(0,0,0,.08)}'
            . '.aieo-store-map__dir{display:inline-flex;align-items:center;gap:6px;margin-top:12px;font-size:.92rem;font-weight:600;text-decoration:none}'
            . '.aieo-store-map__dir::before{content:"\\27A4";font-size:.8em}';
        echo '<style id="aieo-store-map-css">' . $css . '</style>'; 
    }
}
