<?php

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

class AIEO_Store_Locator_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_locator', array(__CLASS__, 'shortcode'));
    }

    public static function register_block() {
        register_block_type('aieo/store-locator', array(
            'api_version'     => 3,
            'title'           => __('AIEO Store Locator', 'ai-eshop-optimizer'),
            'description'     => __('Grid or list of all your store locations — address, phone, opening hours and Google Maps / review links.', 'ai-eshop-optimizer'),
            'category'        => 'widgets',
            'icon'            => 'location-alt',
            'keywords'        => array('store', 'locator', 'locations', 'shops'),
            'supports'        => array('align' => array('wide', 'full'), 'spacing' => array('margin' => true, 'padding' => true)),
            'attributes'      => array(
                'layout'           => array('type' => 'string',  'default' => 'grid'),
                'columns'          => array('type' => 'number',  'default' => 2),
                'showPhoto'        => array('type' => 'boolean', 'default' => true),
                'showHours'        => array('type' => 'boolean', 'default' => true),
                'showMaps'         => array('type' => 'boolean', 'default' => true),
                'showRateUs'       => array('type' => 'boolean', 'default' => true),
                'showReviews'      => array('type' => 'boolean', 'default' => true),
                'reviewsCount'     => array('type' => 'number',  'default' => 3),
                'reviewsMinRating' => array('type' => 'number',  'default' => 0),
                'onlyHq'           => array('type' => 'boolean', 'default' => false),
                'heading'          => array('type' => 'string',  'default' => ''),
            ),
            'render_callback' => array(__CLASS__, 'render'),
        ));
    }

    public static function shortcode($atts) {
        $atts = shortcode_atts(array(
            'layout' => 'grid', 'columns' => 2, 'show_hours' => 1,
            'show_maps' => 1, 'show_rate_us' => 1, 'only_hq' => 0, 'heading' => '',
        ), $atts, 'aieo_store_locator');
        return self::render(array(
            'layout'     => (string) $atts['layout'],
            'columns'    => (int) $atts['columns'],
            'showHours'  => (bool) (int) $atts['show_hours'],
            'showMaps'   => (bool) (int) $atts['show_maps'],
            'showRateUs' => (bool) (int) $atts['show_rate_us'],
            'onlyHq'     => (bool) (int) $atts['only_hq'],
            'heading'    => (string) $atts['heading'],
        ));
    }

    public static function render($attrs, $content = '', $block = null) {
        if (!class_exists('AIEO_Google_Reviews_Locations') || !class_exists('AIEO_Google_Reviews_Helpers')) {
            return '';
        }
        $attrs = wp_parse_args(is_array($attrs) ? $attrs : array(), array(
            'layout' => 'grid', 'columns' => 2, 'showPhoto' => true, 'showHours' => true, 'showMaps' => true,
            'showRateUs' => true, 'showReviews' => true, 'reviewsCount' => 3, 'reviewsMinRating' => 0,
            'onlyHq' => false, 'heading' => '',
        ));

        $locs = AIEO_Google_Reviews_Locations::list_all(true); 
        if (!empty($attrs['onlyHq'])) {
            $locs = array_values(array_filter($locs, static function ($l) { return !empty($l['is_hq']); }));
        }
        if (empty($locs)) { return ''; }

        AIEO_Google_Reviews_Helpers::enqueue_locations_assets();

        $cols   = max(1, min(4, (int) $attrs['columns']));
        $layout = in_array($attrs['layout'], array('list', 'grid'), true) ? $attrs['layout'] : 'grid';
        $wrap   = function_exists('get_block_wrapper_attributes')
            ? get_block_wrapper_attributes(array('class' => 'aieo-store-locator aieo-store-locator--' . $layout, 'style' => '--aieo-loc-cols:' . $cols . ';'))
            : 'class="aieo-store-locator aieo-store-locator--' . esc_attr($layout) . '" style="--aieo-loc-cols:' . (int) $cols . ';"';

        
        
        static $css_done = false;
        $css = '';
        if (!$css_done) {
            $css_done = true;
            $css = '<style id="aieo-store-locator-rich-css">'
                . '.aieo-store-card__photo{display:block;margin-bottom:14px;line-height:0}'
                . '.aieo-store-card__photo-img{display:block;width:100%;height:auto;border-radius:8px;aspect-ratio:16/10;object-fit:cover}'
                . '.aieo-store-card__reviews{margin-top:16px}'
                . '</style>';
        }

        $out = $css . '<div ' . $wrap . '>';
        if ('' !== (string) $attrs['heading']) {
            $out .= '<h2 class="aieo-store-locator__title">' . esc_html($attrs['heading']) . '</h2>';
        }
        $out .= '<div class="aieo-store-locator__grid">';
        foreach ($locs as $loc) {
            $name = (string) ($loc['label'] ?? '');
            if ('' === $name) { $name = (string) ($loc['google_name'] ?? ''); }
            if ('' === $name) { continue; }
            
            $page = class_exists('AIEO_SEO_Location_Page') ? (string) AIEO_SEO_Location_Page::url_for($loc) : '';
            $name_html = '' !== $page
                ? '<a href="' . esc_url($page) . '">' . esc_html($name) . '</a>'
                : esc_html($name);
            $out .= '<div class="aieo-store-card">';
            if (!empty($attrs['showPhoto'])) {
                $out .= self::photo_for_location($loc, $page);
            }
            $out .= '<h3 class="aieo-store-card__name">' . $name_html . '</h3>';
            $out .= AIEO_Google_Reviews_Helpers::render_nap_html($loc);
            if (!empty($attrs['showHours'])) {
                $out .= AIEO_Google_Reviews_Helpers::render_hours_html($loc);
            }
            $out .= AIEO_Google_Reviews_Helpers::render_action_links_html($loc, !empty($attrs['showMaps']), !empty($attrs['showRateUs']));
            
            
            if (!empty($attrs['showReviews']) && class_exists('AIEO_Google_Reviews_Block')) {
                $reviews = AIEO_Google_Reviews_Block::render(array(
                    'mode'         => 'single',
                    'locationSlug' => (string) ($loc['slug'] ?? ''),
                    'showOverall'  => false,
                    'showRateUs'   => false,
                    'maxCount'     => max(0, (int) $attrs['reviewsCount']),
                    'minRating'    => max(0, (int) $attrs['reviewsMinRating']),
                    'layout'       => 'list',
                ));
                if ('' !== trim((string) $reviews)) {
                    $out .= '<div class="aieo-store-card__reviews">' . $reviews . '</div>';
                }
            }
            $out .= '</div>';
        }
        $out .= '</div></div>';
        return $out;
    }

    
    private static function photo_for_location($loc, $link = '') {
        $metas = array();
        if (!empty($loc['id']))   { $metas[] = array('key' => '_aieo_grv_location_id',   'value' => (string) (int) $loc['id']); }
        if (!empty($loc['slug'])) { $metas[] = array('key' => '_aieo_grv_location_slug', 'value' => (string) $loc['slug']); }
        if (!$metas) { return ''; }
        $ids = get_posts(array(
            'post_type'      => 'store_location',
            'post_status'    => 'publish',
            'posts_per_page' => 1,
            'fields'         => 'ids',
            'no_found_rows'  => true,
            'meta_query'     => array_merge(array('relation' => 'OR'), $metas),
        ));
        $pid = $ids ? (int) $ids[0] : 0;
        if (!$pid || !has_post_thumbnail($pid)) { return ''; }
        $img  = get_the_post_thumbnail($pid, 'large', array('loading' => 'lazy', 'class' => 'aieo-store-card__photo-img'));
        $href = '' !== (string) $link ? (string) $link : get_permalink($pid);
        return '<a class="aieo-store-card__photo" href="' . esc_url($href) . '">' . $img . '</a>';
    }
}
