<?php

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

class AIEO_Google_Reviews_Place_Lookup {

    const FINDPLACE_URL = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';

    
    public static function resolve($query, $api_key, $language = 'el') {
        $query = trim((string) $query);
        if ($query === '' || $api_key === '') {
            return array('error' => __('Query and API key are both required.', 'ai-eshop-optimizer'));
        }

        
        
        
        if (preg_match('/^ChIJ[A-Za-z0-9_\-]{20,}$/', $query)) {
            return array('place_id' => $query);
        }

        
        
        
        
        
        $text = self::extract_text_from_url($query);
        if ($text === '') { $text = $query; }

        $url = add_query_arg(array(
            'input'    => rawurlencode($text),
            'inputtype'=> 'textquery',
            'fields'   => 'place_id,name,formatted_address',
            'language' => $language,
            'key'      => $api_key,
        ), self::FINDPLACE_URL);
        
        
        $url = self::FINDPLACE_URL
            . '?input=' . rawurlencode($text)
            . '&inputtype=textquery'
            . '&fields=' . rawurlencode('place_id,name,formatted_address')
            . '&language=' . rawurlencode($language)
            . '&key=' . rawurlencode($api_key);

        $resp = wp_remote_get($url, array(
            'timeout'   => 15,
            'headers'   => array('Accept' => 'application/json'),
        ));
        if (is_wp_error($resp)) {
            return array('error' => $resp->get_error_message());
        }
        $code = (int) wp_remote_retrieve_response_code($resp);
        $body = (string) wp_remote_retrieve_body($resp);
        $json = json_decode($body, true);

        if ($code !== 200 || !is_array($json)) {
            return array('error' => sprintf(
                
                __('Google returned HTTP %d.', 'ai-eshop-optimizer'),
                $code
            ));
        }
        if (($json['status'] ?? 'UNKNOWN') !== 'OK') {
            $msg = (string) ($json['error_message'] ?? $json['status']);
            return array('error' => $msg);
        }

        $cand = isset($json['candidates'][0]) ? $json['candidates'][0] : array();
        if (empty($cand['place_id'])) {
            return array('error' => __('No matching place found. Try refining the query.', 'ai-eshop-optimizer'));
        }

        return array(
            'place_id' => (string) $cand['place_id'],
            'name'     => (string) ($cand['name'] ?? ''),
            'address'  => (string) ($cand['formatted_address'] ?? ''),
        );
    }

    
    private static function extract_text_from_url($url) {
        if (strpos($url, 'http') !== 0) { return ''; }
        $parts = wp_parse_url($url);
        if (!is_array($parts)) { return ''; }
        $host = isset($parts['host']) ? $parts['host'] : '';
        $path = isset($parts['path']) ? $parts['path'] : '';
        $qs   = array();
        if (!empty($parts['query'])) {
            wp_parse_str($parts['query'], $qs);
        }

        
        if (preg_match('#/maps/place/([^/@]+)#', $path, $m)) {
            return urldecode($m[1]);
        }
        
        if (!empty($qs['q'])) {
            return (string) $qs['q'];
        }
        
        
        
        
        if (strpos($host, 'g.page') !== false) {
            return '';
        }
        return '';
    }
}
