<?php

/**
 * ESSB Add-ons API Handler
 * 
 * Handles retrieval and caching of add-ons from the ESSB API
 * 
 * @package EasySocialShareButtons
 * @since 11.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * ESSB_MyAddons_API Class
 * 
 * Static class for managing add-ons data from the REST API
 */
class ESSB_MyAddons_API
{

    /**
     * API endpoint URL
     */
    const API_URL = 'https://my.socialsharingplugin.com/wp-json/my-essb/v1/addons';

    /**
     * Cache transient key
     */
    const CACHE_KEY = 'essb_api_addons_cache';

    /**
     * Cache expiration time (1 week in seconds)
     */
    const CACHE_EXPIRATION = WEEK_IN_SECONDS;

    /**
     * Get all add-ons from cache or API
     * 
     * @return array Add-ons data
     */
    public static function get_addons()
    {
        $cached = get_transient(self::CACHE_KEY);

        if (false !== $cached) {
            return $cached;
        }

        return self::fetch_from_api();
    }

    /**
     * Force refresh the cache by deleting transient and fetching fresh data
     * 
     * @return array Fresh add-ons data
     */
    public static function refresh_cache()
    {
        delete_transient(self::CACHE_KEY);
        return self::fetch_from_api();
    }

    /**
     * Get all free add-ons with limited data (slug, name, download)
     * 
     * @return array Free add-ons with slug, name, and download URL
     */
    public static function get_free_addons_basic()
    {
        $addons = self::get_addons();
        $free_addons = array();

        if (!is_array($addons)) {
            return $free_addons;
        }

        foreach ($addons as $slug => $addon) {

            if (!is_array($addon)) {
                continue;
            }

            if (!$addon['download']) {
                continue;
            }

            if (isset($addon['type']) && $addon['type'] === 'free') {
                $free_addons[] = array(
                    'slug' => isset($addon['slug']) ? $addon['slug'] : $slug,
                    'name' => isset($addon['name']) ? $addon['name'] : '',
                    'source' => isset($addon['download']) ? $addon['download'] : ''
                );
            }
        }

        return $free_addons;
    }

    /**
     * Get all free add-ons with complete data
     * 
     * @return array All free add-ons with full data
     */
    public static function get_free_addons_full()
    {
        $addons = self::get_addons();
        $free_addons = array();

        foreach ($addons as $slug => $addon) {
            if (isset($addon['type']) && $addon['type'] === 'free') {
                $free_addons[$slug] = $addon;
            }
        }

        return $free_addons;
    }

    /**
     * Get add-ons split into featured and regular lists
     * 
     * @return array Array with 'featured' and 'addons' keys
     */
    public static function get_split_addons()
    {
        $addons = self::get_addons();
        $result = array(
            'featured' => array(),
            'addons' => array()
        );

        foreach ($addons as $slug => $addon) {
            if (isset($addon['featured']) && $addon['featured'] === true) {
                $result['featured'][$slug] = $addon;
                $result['addons'][$slug] = $addon;
            } else {
                $result['addons'][$slug] = $addon;
            }
        }

        return $result;
    }

    /**
     * Fetch add-ons from the REST API
     * 
     * @return array Add-ons data or empty array on failure
     */
    private static function fetch_from_api()
    {
        $response = wp_remote_get(
            self::API_URL,
            array(
                'timeout' => 15,
                'headers' => array(
                    'Accept' => 'application/json',
                ),
            )
        );

        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
            return array();
        }

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

        if (!is_array($data)) {
            return array();
        }

        // Store in cache
        set_transient(self::CACHE_KEY, $data, self::CACHE_EXPIRATION);

        return $data;
    }

    /**
     * Get a single add-on by slug
     * 
     * @param string $slug Add-on slug
     * @return array|null Add-on data or null if not found
     */
    public static function get_addon_by_slug($slug)
    {
        $addons = self::get_addons();

        if (isset($addons[$slug])) {
            return $addons[$slug];
        }

        return null;
    }

    /**
     * Check if cache exists
     * 
     * @return bool True if cache exists
     */
    public static function has_cache()
    {
        return false !== get_transient(self::CACHE_KEY);
    }

    /**
     * Delete the cache
     * 
     * @return bool True on success, false on failure
     */
    public static function delete_cache()
    {
        return delete_transient(self::CACHE_KEY);
    }

    /**
     * Get add-ons by category
     * 
     * @param string $category Category name
     * @return array Add-ons in the specified category
     */
    public static function get_addons_by_category($category)
    {
        $addons = self::get_addons();
        $filtered = array();

        foreach ($addons as $slug => $addon) {
            if (isset($addon['category']) && $addon['category'] === $category) {
                $filtered[$slug] = $addon;
            }
        }

        return $filtered;
    }

    /**
     * Get all unique categories from add-ons
     * 
     * @return array List of categories
     */
    public static function get_categories()
    {
        $addons = self::get_addons();
        $categories = array();

        foreach ($addons as $addon) {
            if (isset($addon['category']) && !empty($addon['category'])) {
                $categories[$addon['category']] = $addon['category'];
            }
        }

        return array_values($categories);
    }

    /**
     * Get total count of add-ons
     * 
     * @return int Number of add-ons
     */
    public static function get_total_count()
    {
        return count(self::get_addons());
    }

    /**
     * Get count of free add-ons
     * 
     * @return int Number of free add-ons
     */
    public static function get_free_count()
    {
        $count = 0;
        $addons = self::get_addons();

        foreach ($addons as $addon) {
            if (isset($addon['type']) && $addon['type'] === 'free') {
                $count++;
            }
        }

        return $count;
    }
}
