<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Admin;

defined('ABSPATH') || exit;

final class GoogleFontsCatalogController
{
    private const CACHE_TTL = 12 * HOUR_IN_SECONDS;

    public function fetch() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_send_json_error([
                'code' => 'forbidden',
                'message' => __('You are not allowed to access the font catalog.', 'asuka-product-designer'),
            ], 403);
        }

        check_ajax_referer('apd_google_fonts_catalog', 'nonce');

        $settings = (new AdminSettings())->all();
        $apiKey = trim((string) ($settings['google_fonts_api_key'] ?? ''));
        if ($apiKey === '') {
            wp_send_json_error([
                'code' => 'missing_api_key',
                'message' => __('Add a Google Fonts API key in Asuka Designer settings to load the complete live catalog.', 'asuka-product-designer'),
                'settingsUrl' => admin_url('admin.php?page=apd-settings'),
            ], 400);
        }

        $cacheKey = 'apd_google_fonts_' . substr(hash('sha256', $apiKey), 0, 16);
        $cached = get_transient($cacheKey);
        if (is_array($cached) && $cached !== []) {
            wp_send_json_success([
                'items' => $cached,
                'cached' => true,
            ]);
        }

        $url = add_query_arg([
            'key' => $apiKey,
            'sort' => 'alpha',
            'capability' => 'WOFF2',
        ], 'https://www.googleapis.com/webfonts/v1/webfonts');

        $response = wp_remote_get($url, [
            'timeout' => 20,
            'redirection' => 3,
            'headers' => [
                'Accept' => 'application/json',
            ],
        ]);

        if (is_wp_error($response)) {
            wp_send_json_error([
                'code' => 'request_failed',
                'message' => __('Google Fonts could not be reached. Please try again in a moment.', 'asuka-product-designer'),
            ], 502);
        }

        $status = (int) wp_remote_retrieve_response_code($response);
        $payload = json_decode((string) wp_remote_retrieve_body($response), true);
        if ($status < 200 || $status >= 300 || ! is_array($payload['items'] ?? null)) {
            $remoteMessage = sanitize_text_field((string) ($payload['error']['message'] ?? ''));
            wp_send_json_error([
                'code' => 'invalid_google_response',
                'message' => $remoteMessage !== ''
                    ? $remoteMessage
                    : __('Google Fonts returned an invalid response. Check the API key and its restrictions.', 'asuka-product-designer'),
            ], $status >= 400 && $status < 600 ? $status : 502);
        }

        $items = [];
        foreach ((array) $payload['items'] as $font) {
            if (! is_array($font)) {
                continue;
            }

            $family = sanitize_text_field((string) ($font['family'] ?? ''));
            if ($family === '') {
                continue;
            }

            $variants = [];
            foreach ((array) ($font['variants'] ?? []) as $variant) {
                $variant = sanitize_text_field((string) $variant);
                if ($variant !== '') {
                    $variants[] = $variant;
                }
            }

            $subsets = [];
            foreach ((array) ($font['subsets'] ?? []) as $subset) {
                $subset = sanitize_key((string) $subset);
                if ($subset !== '') {
                    $subsets[] = $subset;
                }
            }

            $items[] = [
                'family' => $family,
                'category' => sanitize_key((string) ($font['category'] ?? '')),
                'variants' => array_values(array_unique($variants)),
                'subsets' => array_values(array_unique($subsets)),
                'lastModified' => sanitize_text_field((string) ($font['lastModified'] ?? '')),
            ];
        }

        if ($items === []) {
            wp_send_json_error([
                'code' => 'empty_catalog',
                'message' => __('Google Fonts returned an empty catalog.', 'asuka-product-designer'),
            ], 502);
        }

        set_transient($cacheKey, $items, self::CACHE_TTL);

        wp_send_json_success([
            'items' => $items,
            'cached' => false,
        ]);
    }
}
