<?php
namespace ShopyPress\Helpers;
if ( ! defined( 'ABSPATH' ) ) exit;

use ShopyPress\Helpers\ShopifyAuth;

class ShopifyCollections {

    private static $last_response_code = 0;

    /**
     * Fetch all collections from Shopify using GraphQL
     *
     * @param string $shop The shop domain (e.g., 'mystore.myshopify.com')
     * @return array|null Array of collections or null on failure
     */
    public static function fetchCollections(string $shop): ?array {
        $access_token = ShopifyAuth::getAccessToken($shop);

        if (empty($access_token)) {
            return null;
        }

        $all_collections = [];
        $has_next_page = true;
        $cursor = null;
        $retry_count = 0;
        $max_retries = 1;

        // Pagination loop to fetch all collections
        while ($has_next_page) {
            $result = self::fetchCollectionsPage($shop, $access_token, $cursor);

            // If forbidden (403), clear token and retry once with a new token
            if ($result === null && self::$last_response_code === 403 && $retry_count < $max_retries) {
                ShopifyAuth::clearAccessToken();
                $access_token = ShopifyAuth::getAccessToken($shop);

                if (empty($access_token)) {
                    return null;
                }

                $retry_count++;
                continue;
            }

            if ($result === null) {
                return null;
            }

            $collections = $result['collections'] ?? [];
            $all_collections = array_merge($all_collections, $collections);

            $has_next_page = $result['hasNextPage'] ?? false;
            $cursor = $result['endCursor'] ?? null;
        }

        return $all_collections;
    }

    /**
     * Fetch a single page of collections
     *
     * @param string $shop The shop domain
     * @param string $access_token The access token
     * @param string|null $cursor Pagination cursor
     * @return array|null
     */
    private static function fetchCollectionsPage(string $shop, string $access_token, ?string $cursor = null): ?array {
        $url = "https://{$shop}/admin/api/2025-10/graphql.json";

        // GraphQL query for collections
        $after_param = $cursor ? ', after: "' . $cursor . '"' : '';
        $query = '{' .
            'collections(first: 250' . $after_param . ') {' .
                'edges {' .
                    'node {' .
                        'id ' .
                        'title ' .
                        'handle ' .
                        'description ' .
                        'descriptionHtml ' .
                        'productsCount {' .
                            'count' .
                        '} ' .
                        'image {' .
                            'url ' .
                            'altText' .
                        '} ' .
                        'updatedAt' .
                    '} ' .
                    'cursor' .
                '}' .
                'pageInfo {' .
                    'hasNextPage ' .
                    'endCursor' .
                '}' .
            '}' .
        '}';

        $response = wp_remote_post($url, [
            'headers' => [
                'Content-Type' => 'application/json',
                'X-Shopify-Access-Token' => $access_token,
            ],
            'body' => json_encode(['query' => $query]),
            'timeout' => 30,
        ]);

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

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);

        // Store response code for retry logic
        self::$last_response_code = $response_code;

        if ($response_code !== 200) {
            return null;
        }

        $data = json_decode($response_body, true);

        if (isset($data['errors'])) {
            return null;
        }

        $edges = $data['data']['collections']['edges'] ?? [];
        $page_info = $data['data']['collections']['pageInfo'] ?? [];

        $collections = array_map(function($edge) {
            return $edge['node'];
        }, $edges);

        return [
            'collections' => $collections,
            'hasNextPage' => $page_info['hasNextPage'] ?? false,
            'endCursor' => $page_info['endCursor'] ?? null,
        ];
    }

    /**
     * Format collections for frontend display
     *
     * @param array $collections Raw collections data
     * @return array Formatted collections
     */
    public static function formatCollections(array $collections): array {
        return array_map(function($collection) {
            return [
                'id' => $collection['id'],
                'title' => $collection['title'],
                'handle' => $collection['handle'],
                'description' => $collection['description'] ?? '',
                'products_count' => $collection['productsCount']['count'] ?? 0,
                'image_url' => $collection['image']['url'] ?? '',
                'image_alt' => $collection['image']['altText'] ?? '',
                'updated_at' => $collection['updatedAt'] ?? '',
            ];
        }, $collections);
    }
}
