<?php

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

class AIEO_Store_Info_Block {

    public static function register() {
        add_action('init', array(__CLASS__, 'register_block'));
        add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_css'));
    }

    public static function register_block() {
        register_block_type('aieo/store-info', array(
            'api_version'     => 3,
            'title'           => __('AIEO Store Info (address, phone, hours)', 'ai-eshop-optimizer'),
            'description'     => __('Structured store contact info — address, clickable phone, and per-day hours. Reads from post meta + the linked Google location row.', 'ai-eshop-optimizer'),
            'category'        => 'widgets',
            'icon'            => 'store',
            'keywords'        => array('store', 'address', 'phone', 'hours', 'contact', 'καταστήμα'),
            'supports'        => array('align' => array('wide')),
            'attributes'      => array(
                'showAddress' => array('type' => 'boolean','default' => true),
                'showPhone'   => array('type' => 'boolean','default' => true),
                'showHours'   => array('type' => 'boolean','default' => true),
                'compact'     => array('type' => 'boolean','default' => false),
            ),
            'uses_context'    => array('postId'),
            'render_callback' => array(__CLASS__, 'render'),
        ));

        
        
        foreach (array('_store_address', '_store_phone', '_store_hours') as $key) {
            register_post_meta('store_location', $key, array(
                'type'         => 'string',
                'single'       => true,
                'show_in_rest' => true,
                'auth_callback'=> static function () {
                    return current_user_can('edit_posts');
                },
            ));
        }
    }

    public static function render($attrs, $content = '', $block = null) {
        $attrs = wp_parse_args(is_array($attrs) ? $attrs : array(), array(
            'showAddress' => true,
            'showPhone'   => true,
            'showHours'   => true,
            'compact'     => false,
        ));

        
        $pid = 0;
        if (is_object($block) && isset($block->context['postId'])) {
            $pid = (int) $block->context['postId'];
        }
        if ($pid <= 0 && is_singular()) { $pid = (int) get_queried_object_id(); }
        if ($pid <= 0) { return ''; }

        $address = (string) get_post_meta($pid, '_store_address', true);
        $phone   = (string) get_post_meta($pid, '_store_phone',   true);
        $hours   = (string) get_post_meta($pid, '_store_hours',   true);

        
        
        if ($address === '' && class_exists('AIEO_Google_Reviews_Helpers')) {
            $loc = AIEO_Google_Reviews_Helpers::resolve_location_for_post($pid);
            if ($loc && !empty($loc['address'])) {
                $address = (string) $loc['address'];
            }
        }

        if ($address === '' && $phone === '' && $hours === '') { return ''; }

        $tel = $phone !== '' ? preg_replace('/[^0-9+]/', '', $phone) : '';
        $compact_class = !empty($attrs['compact']) ? ' aieo-store-info--compact' : '';

        
        
        
        
        
        $out = '<dl class="aieo-store-info' . esc_attr($compact_class) . '">';

        if (!empty($attrs['showAddress']) && $address !== '') {
            $out .= '<dt>' . esc_html__('Διεύθυνση', 'ai-eshop-optimizer') . '</dt>';
            $out .= '<dd>' . esc_html($address) . '</dd>';
        }

        if (!empty($attrs['showPhone']) && $phone !== '') {
            $out .= '<dt>' . esc_html__('Τηλέφωνο', 'ai-eshop-optimizer') . '</dt>';
            $out .= '<dd>';
            if ($tel !== '') {
                $out .= '<a href="tel:' . esc_attr($tel) . '" class="aieo-store-info__tel">' . esc_html($phone) . '</a>';
            } else {
                $out .= esc_html($phone);
            }
            $out .= '</dd>';
        }

        if (!empty($attrs['showHours']) && $hours !== '') {
            
            
            
            
            $hours_norm = str_replace(array("\r\n", "\r"), "\n", trim($hours));
            $lines = array_filter(array_map('trim', explode("\n", $hours_norm)), 'strlen');
            if (!empty($lines)) {
                $out .= '<dt>' . esc_html__('Ωράριο', 'ai-eshop-optimizer') . '</dt>';
                $out .= '<dd><ul class="aieo-store-info__hours">';
                foreach ($lines as $line) {
                    $out .= '<li>' . esc_html($line) . '</li>';
                }
                $out .= '</ul></dd>';
            }
        }

        $out .= '</dl>';
        return $out;
    }

    public static function enqueue_css() {
        wp_register_style('aieo-store-info', false); 
        wp_enqueue_style('aieo-store-info');
        wp_add_inline_style('aieo-store-info', '
/* dl is the grid — every dt is column 1, every dd is column 2.
   Result: the dd column starts at the same x for every row, regardless
   of which dt label is the longest. align-items:start so multi-line
   values (Ωράριο list) don\'t centre-align with their label. */
.aieo-store-info{margin:0;padding:0;display:grid;grid-template-columns:max-content 1fr;gap:8px 14px;font-size:.95rem;line-height:1.5;align-items:start}
.aieo-store-info dt{font-weight:600;color:#111;margin:0;white-space:nowrap;grid-column:1}
.aieo-store-info dd{margin:0;color:#374151;grid-column:2}
.aieo-store-info__tel{color:inherit;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px}
.aieo-store-info__tel:hover{color:var(--wp--preset--color--accent,#F46767);text-decoration-style:solid}
.aieo-store-info__hours{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:2px}
.aieo-store-info__hours li{padding:0}
.aieo-store-info--compact{font-size:.88rem;gap:4px 10px}
@media (max-width: 480px){
  /* Stack vertically on narrow screens — labels above values, no
     wasted space on the left margin. */
  .aieo-store-info{grid-template-columns:1fr;gap:1px 0}
  .aieo-store-info dt{margin-top:6px}
}
');
    }
}
