<?php

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

class AIEO_Google_Reviews_Helpers {

    
    public static function review_url(array $location) {
        $stored = isset($location['review_url']) ? trim((string) $location['review_url']) : '';
        if ($stored !== '') { return $stored; }

        $place_id = (string) ($location['place_id'] ?? '');
        if ($place_id === '' || strpos($place_id, 'ChIJ') !== 0) {
            return '';
        }
        return 'https://search.google.com/local/writereview?placeid=' . rawurlencode($place_id);
    }

    
    public static function maps_url(array $location) {
        $place_id = (string) ($location['place_id'] ?? '');
        if ($place_id !== '' && strpos($place_id, 'ChIJ') === 0) {
            return 'https://www.google.com/maps/place/?q=place_id:' . rawurlencode($place_id);
        }
        $label = (string) ($location['label'] ?? '');
        return $label !== ''
            ? 'https://www.google.com/maps/search/?api=1&query=' . rawurlencode($label)
            : '';
    }

    
    public static function resolve_location_for_post($post_id) {
        $post_id = (int) $post_id;
        if ($post_id <= 0) { return null; }

        $loc_id = (int) get_post_meta($post_id, '_aieo_grv_location_id', true);
        if ($loc_id > 0) {
            $loc = AIEO_Google_Reviews_Locations::get($loc_id);
            if ($loc) { return $loc; }
        }
        $slug = (string) get_post_meta($post_id, '_aieo_grv_location_slug', true);
        if ($slug !== '') {
            $loc = AIEO_Google_Reviews_Locations::get_by_slug($slug);
            if ($loc) { return $loc; }
        }
        
        
        $post = get_post($post_id);
        if ($post) {
            foreach (array($post->post_name, preg_replace('/^katastima[-_]/', '', (string) $post->post_name)) as $candidate) {
                if (!$candidate) { continue; }
                $loc = AIEO_Google_Reviews_Locations::get_by_slug($candidate);
                if ($loc) { return $loc; }
            }
        }
        return null;
    }

    
    public static function fetch_reviews_for_location($location_id, $limit = 5, $min_rating = 1) {
        global $wpdb;
        $tbl = $wpdb->prefix . 'aieo_google_reviews';
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$tbl}
             WHERE location_id = %d
               AND is_visible = 1
               AND rating >= %d
             ORDER BY review_time DESC
             LIMIT %d",
            (int) $location_id, (int) $min_rating, (int) $limit
        ), ARRAY_A);
        return is_array($rows) ? $rows : array();
    }

    
    public static function fetch_reviews_mixed($limit = 12, $min_rating = 1) {
        global $wpdb;
        $rev = $wpdb->prefix . 'aieo_google_reviews';
        $loc = $wpdb->prefix . 'aieo_google_locations';
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT r.*, l.slug AS location_slug, l.label AS location_label
             FROM {$rev} r
             INNER JOIN {$loc} l ON l.id = r.location_id AND l.enabled = 1
             WHERE r.is_visible = 1 AND r.rating >= %d
             ORDER BY r.review_time DESC
             LIMIT %d",
            (int) $min_rating, (int) $limit
        ), ARRAY_A);
        return is_array($rows) ? $rows : array();
    }

    
    public static function star_html($rating) {
        $rating = (float) $rating;
        $full = (int) floor($rating);
        $half = ($rating - $full) >= 0.5 ? 1 : 0;
        $empty = 5 - $full - $half;
        $out = '<span class="aieo-grv-stars" aria-label="' . esc_attr(sprintf(
            
            __('Rated %s out of 5', 'ai-eshop-optimizer'),
            number_format_i18n($rating, 1)
        )) . '">';
        for ($i = 0; $i < $full;  $i++) { $out .= '<span class="aieo-grv-star aieo-grv-star-full" aria-hidden="true">★</span>'; }
        for ($i = 0; $i < $half;  $i++) { $out .= '<span class="aieo-grv-star aieo-grv-star-half" aria-hidden="true">★</span>'; }
        for ($i = 0; $i < $empty; $i++) { $out .= '<span class="aieo-grv-star aieo-grv-star-empty" aria-hidden="true">★</span>'; }
        $out .= '</span>';
        return $out;
    }

    
    public static function resolve_single($slug, $block = null) {
        $slug = (string) $slug;
        if ('' !== $slug && class_exists('AIEO_Google_Reviews_Locations')) {
            $loc = AIEO_Google_Reviews_Locations::get_by_slug($slug);
            if ($loc) { return $loc; }
        }
        $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(); }
        return $pid > 0 ? self::resolve_location_for_post($pid) : null;
    }

    
    
    
    

    
    public static function render_nap_html(array $loc, $stacked = false) {
        if ($stacked) {
            
            $lines  = array();
            $maps   = self::maps_url($loc);
            $street = trim((string) ($loc['street'] ?? ''));
            $town   = trim((string) ($loc['locality'] ?? ''));
            $post   = trim((string) ($loc['postcode'] ?? ''));
            $phone  = trim((string) ($loc['phone'] ?? ''));
            if ('' !== $street) {
                $s = '' !== $maps
                    ? '<a href="' . esc_url($maps) . '" target="_blank" rel="noopener">' . esc_html($street) . '</a>'
                    : esc_html($street);
                $lines[] = '<div class="aieo-loc__addr-street">' . $s . '</div>';
            }
            if ('' !== $town) { $lines[] = '<div class="aieo-loc__addr-town">' . esc_html($town) . '</div>'; }
            if ('' !== $post) { $lines[] = '<div class="aieo-loc__addr-postcode">' . esc_html($post) . '</div>'; }
            if ('' !== $phone) {
                $tel = preg_replace('/[^0-9+]/', '', $phone);
                $lines[] = '<div class="aieo-loc__phone"><a href="tel:' . esc_attr($tel) . '">' . esc_html($phone) . '</a></div>';
            }
            return ! empty($lines) ? '<div class="aieo-loc__nap aieo-loc__nap--stacked">' . implode('', $lines) . '</div>' : '';
        }
        $parts = array();
        $struct = array_filter(array(
            (string) ($loc['street'] ?? ''),
            trim((string) ($loc['postcode'] ?? '') . ' ' . (string) ($loc['locality'] ?? '')),
            (string) ($loc['region'] ?? ''),
        ), 'strlen');
        $addr = ! empty($struct) ? implode(', ', $struct) : (string) ($loc['address'] ?? '');
        if ('' !== $addr) {
            $maps = self::maps_url($loc);
            $addr_html = '' !== $maps
                ? '<a href="' . esc_url($maps) . '" target="_blank" rel="noopener">' . esc_html($addr) . '</a>'
                : esc_html($addr);
            $parts[] = '<div class="aieo-loc__addr">' . $addr_html . '</div>';
        }
        $phone = (string) ($loc['phone'] ?? '');
        if ('' !== $phone) {
            $tel = preg_replace('/[^0-9+]/', '', $phone);
            $parts[] = '<div class="aieo-loc__phone"><a href="tel:' . esc_attr($tel) . '">' . esc_html($phone) . '</a></div>';
        }
        return ! empty($parts) ? '<div class="aieo-loc__nap">' . implode('', $parts) . '</div>' : '';
    }

    
    public static function render_hours_html(array $loc) {
        $raw = (string) ($loc['hours_json'] ?? '');
        if ('' === $raw) { return ''; }
        $periods = json_decode($raw, true);
        if (! is_array($periods)) { return ''; }
        $by_day = array();
        foreach ($periods as $p) {
            if (! isset($p['open']['day'])) { continue; }
            $d = (int) $p['open']['day'];
            $o = self::fmt_hm(isset($p['open']['time']) ? (string) $p['open']['time'] : '');
            if ('' === $o) { continue; }
            $c = isset($p['close']['time']) ? self::fmt_hm((string) $p['close']['time']) : '';
            $by_day[$d][] = '' !== $c ? $o . '–' . $c : $o;
        }
        if (empty($by_day)) { return ''; }
        $wpl   = isset($GLOBALS['wp_locale']) ? $GLOBALS['wp_locale'] : null;
        $out   = '<ul class="aieo-loc__hours">';
        foreach (array(1, 2, 3, 4, 5, 6, 0) as $d) { 
            if (empty($by_day[$d])) { continue; }
            $name = ($wpl && method_exists($wpl, 'get_weekday')) ? $wpl->get_weekday($d) : (string) $d;
            $out .= '<li><span class="aieo-loc__day">' . esc_html($name) . '</span> <span class="aieo-loc__time">' . esc_html(implode(', ', $by_day[$d])) . '</span></li>';
        }
        return $out . '</ul>';
    }

    
    public static function render_action_links_html(array $loc, $show_maps = true, $show_rate = true) {
        $out = '';
        if ($show_maps) {
            $maps = self::maps_url($loc);
            if ('' !== $maps) {
                $out .= '<a class="aieo-loc__btn aieo-loc__btn--maps" href="' . esc_url($maps) . '" target="_blank" rel="noopener">' . esc_html__('Open in Google Maps', 'ai-eshop-optimizer') . '</a>';
            }
        }
        if ($show_rate) {
            $rate = self::review_url($loc);
            if ('' !== $rate) {
                $out .= '<a class="aieo-loc__btn aieo-loc__btn--rate" href="' . esc_url($rate) . '" target="_blank" rel="noopener">' . esc_html__('Rate us on Google', 'ai-eshop-optimizer') . '</a>';
            }
        }
        return '' !== $out ? '<div class="aieo-loc__actions">' . $out . '</div>' : '';
    }

    
    private static function fmt_hm($hhmm) {
        $hhmm = preg_replace('/\D/', '', (string) $hhmm);
        if (strlen((string) $hhmm) < 4) { return ''; }
        return substr($hhmm, 0, 2) . ':' . substr($hhmm, 2, 2);
    }

    
    public static function enqueue_locations_assets() {
        static $done = false;
        if ($done) { return; }
        $done = true;
        wp_register_style('aieo-locations', false); 
        wp_enqueue_style('aieo-locations');
        wp_add_inline_style('aieo-locations',
            '.aieo-store-locator__grid{display:grid;grid-template-columns:repeat(var(--aieo-loc-cols,2),1fr);gap:20px}'
            . '.aieo-store-locator--list .aieo-store-locator__grid{grid-template-columns:1fr}'
            . '.aieo-store-locator__title{margin:0 0 16px}'
            . '.aieo-store-card{border:1px solid #e2e8f0;border-radius:10px;padding:16px}'
            . '.aieo-store-card__name{margin:0 0 8px;font-size:1.1rem}'
            . '.aieo-store-card__name a{text-decoration:none;color:inherit}'
            . '.aieo-loc__nap{font-size:.95rem;line-height:1.5;color:#374151}'
            . '.aieo-loc__addr a,.aieo-loc__phone a{color:inherit}'
            . '.aieo-loc__hours{list-style:none;margin:10px 0 0;padding:0;font-size:.9rem;color:#374151}'
            . '.aieo-loc__hours li{display:flex;justify-content:space-between;gap:12px;padding:1px 0}'
            
            
            
            
            . '.aieo-loc-hours-block .aieo-loc__hours{display:grid;grid-template-columns:max-content max-content;gap:3px 24px;justify-content:start}'
            . '.aieo-loc-hours-block .aieo-loc__hours li{display:contents}'
            . '.aieo-loc__day{font-weight:600;color:#111}'
            . '.aieo-loc__actions{margin-top:12px;display:flex;flex-wrap:wrap;gap:8px}'
            . '.aieo-loc__btn{display:inline-block;padding:6px 12px;border-radius:6px;border:1px solid #d1d5db;text-decoration:none;font-size:.85rem;color:#111}'
            . '.aieo-loc__btn--rate{background:#fbbf24;border-color:#f59e0b;color:#111}'
            . '.aieo-loc__btn--maps{background:#fff}'
            . '@media(max-width:640px){.aieo-store-locator__grid{grid-template-columns:1fr}}'
        );
    }

    
    public static function cache_hash(array $attrs) {
        ksort($attrs);
        return substr(hash('sha256', wp_json_encode($attrs)), 0, 24);
    }
}
