<?php

class MixcloudAPI {
    /**
     * Mixcloud API base URL
     */
    private $api_base_url = 'https://api.mixcloud.com/';

    
    /**
     * Get user cloudcasts
     */
    public function getUserCloudcasts($username, $params = []) {
    
        //example https://api.mixcloud.com/lowlight/cloudcasts/

        $endpoint = "{$username}/cloudcasts/";
        
        try {
            return $this->apiGet($endpoint, $params);
        } catch (Exception $e) {
            
            throw new Exception('Failed to get user cloudcasts: ' . $e->getMessage());
        }
        
    }

    /**
     * Get cloudcast details
     */
    public function getCloudcast($username, $cloudcast_slug) {
        // ...
    }

    /**
     * Search cloudcasts
     */
    public function searchCloudcasts($query, $params = []) {
       
        //https://api.mixcloud.com/search/?q=happy&type=cloudcast
        $endpoint = "search/";
        $params['q'] = $query;
        $params['type'] = 'cloudcast';

        try {
            return $this->apiGet($endpoint, $params);
        } catch (Exception $e) {
            throw new Exception('Failed to search cloudcasts: ' . $e->getMessage());
        }
    }

    /**
     * Get categories
     */
    public function getCategories() {
        // ...
    }

    /**
     * Get category cloudcasts
     */
    public function getCategoryCloudcasts($category, $params = []) {
        // ...
    }

    /**
     * Make a GET request to Mixcloud API
     */
    private function apiGet($endpoint, $params = []) {
    
        $url = $this->api_base_url . $endpoint . '?' . http_build_query($params);
        $response = wp_remote_get($url);

        if (is_wp_error($response)) {
        
         //throw error
         throw new Exception('Mixcloud API request failed: ' . $response->get_error_message());
        
        }

        echo '<br> - Mixcloud API URL: ' . $url ;

        $body = wp_remote_retrieve_body($response);

        //if empty response
        if (empty($body)) {
            throw new Exception('Mixcloud API returned an empty response');
        }

        $data = json_decode($body, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Failed to decode Mixcloud API response: ' . json_last_error_msg());
        }

        //if error in response
        if (isset($data['error'])) {
            throw new Exception('Mixcloud API error: ' . $data['error']['message']);
        }

        return $data;
        

    }
}
