<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class TMNL_Google {

    private static $transient_prefix = 'tmnl_google_reviews_';
    private static $cache_expiry = 30 * DAY_IN_SECONDS; // 30 days

    /**
     * Fetch reviews from Google Places API (New) and cache them
     */
    public static function fetch_reviews( $force = false ) {
        $api_key  = get_option( 'tmnl_google_api_key', '' );
        $place_id = get_option( 'tmnl_google_place_id', '' );

        if ( empty( $api_key ) || empty( $place_id ) ) {
            return new WP_Error( 'missing_config', 'APIキーまたはPlace IDが設定されていません。' );
        }

        $transient_key = self::$transient_prefix . md5( $place_id );

        // Return cache if available and not forcing refresh
        if ( ! $force ) {
            $cached = get_transient( $transient_key );
            if ( false !== $cached ) {
                return $cached;
            }
        }

        // Call Google Places API (New)
        $url = sprintf(
            'https://places.googleapis.com/v1/places/%s?fields=reviews,displayName,rating,userRatingCount&languageCode=ja&key=%s',
            rawurlencode( $place_id ),
            rawurlencode( $api_key )
        );

        $response = wp_remote_get( $url, array(
            'timeout' => 15,
            'headers' => array(
                'X-Goog-FieldMask' => 'reviews,displayName,rating,userRatingCount',
            ),
        ) );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code( $response );
        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );

        if ( $code !== 200 ) {
            $error_msg = $data['error']['message'] ?? "APIエラー (HTTP {$code})";
            return new WP_Error( 'api_error', $error_msg );
        }

        $reviews = self::parse_reviews( $data );

        // Cache for 30 days
        set_transient( $transient_key, $reviews, self::$cache_expiry );
        update_option( 'tmnl_cache_updated_at', current_time( 'mysql' ) );

        // Store place info
        if ( isset( $data['displayName']['text'] ) ) {
            update_option( 'tmnl_google_place_name', $data['displayName']['text'] );
        }
        if ( isset( $data['rating'] ) ) {
            update_option( 'tmnl_google_place_rating', $data['rating'] );
        }
        if ( isset( $data['userRatingCount'] ) ) {
            update_option( 'tmnl_google_place_review_count', $data['userRatingCount'] );
        }

        return $reviews;
    }

    /**
     * Parse API response into normalized review array
     */
    private static function parse_reviews( $data ) {
        $reviews = array();

        if ( empty( $data['reviews'] ) || ! is_array( $data['reviews'] ) ) {
            return $reviews;
        }

        foreach ( $data['reviews'] as $r ) {
            $reviews[] = array(
                'author_name' => $r['authorAttribution']['displayName'] ?? '',
                'author_icon' => $r['authorAttribution']['photoUri'] ?? '',
                'rating'      => $r['rating'] ?? 0,
                'text'        => $r['text']['text'] ?? '',
                'date'        => isset( $r['publishTime'] ) ? date( 'Y-m-d', strtotime( $r['publishTime'] ) ) : '',
                'relative_time' => $r['relativePublishTimeDescription'] ?? '',
            );
        }

        return $reviews;
    }

    /**
     * Get cached reviews (does not call API)
     */
    public static function get_cached_reviews() {
        $place_id = get_option( 'tmnl_google_place_id', '' );
        if ( empty( $place_id ) ) return array();

        $transient_key = self::$transient_prefix . md5( $place_id );
        $cached = get_transient( $transient_key );
        return $cached ?: array();
    }

    /**
     * Get filtered reviews by min rating
     */
    public static function get_filtered_reviews( $min_rating = 1 ) {
        $reviews = self::get_cached_reviews();
        if ( $min_rating <= 1 ) return $reviews;

        return array_filter( $reviews, function( $r ) use ( $min_rating ) {
            return $r['rating'] >= $min_rating;
        });
    }

    /**
     * Clear cache
     */
    public static function clear_cache() {
        $place_id = get_option( 'tmnl_google_place_id', '' );
        if ( empty( $place_id ) ) return;
        delete_transient( self::$transient_prefix . md5( $place_id ) );
        delete_option( 'tmnl_cache_updated_at' );
    }

    /**
     * Get cache status info
     */
    public static function get_cache_status() {
        $place_id = get_option( 'tmnl_google_place_id', '' );
        if ( empty( $place_id ) ) {
            return array( 'has_cache' => false, 'updated_at' => null, 'count' => 0 );
        }

        $reviews = self::get_cached_reviews();
        $updated = get_option( 'tmnl_cache_updated_at', null );

        return array(
            'has_cache'  => ! empty( $reviews ),
            'updated_at' => $updated,
            'count'      => count( $reviews ),
        );
    }
}
