<?php
class agile_tix_data_fetcher
{

    static function fetch_agile_data($feed_type = 'main')
    {
        //agile_tix::agile_tix_log_event("fetch_agile_data called");
        
        $webURL = get_option('agile_field_webURL');
        
        // Determine which credentials to use based on feed type
        if ($feed_type === 'coming_soon') {
            // Coming soon feed uses separate credentials
            $useComingSoon = get_option('agile_field_use_coming_soon_feed');
            if (!$useComingSoon) {
                // agile_tix::agile_tix_log_event("Coming Soon Feed API: Feed is not enabled");
                return "Error: Coming soon feed is not enabled.";
            }
            
            $epgID = get_option('agile_field_coming_soon_epgID'); // Optional EPG ID
            $guid = get_option('agile_field_coming_soon_guid');
            $feedTag = false; // Coming soon feed always uses GUID, not EPG Tag
            
            // agile_tix::agile_tix_log_event("Coming Soon Feed API: GUID = " . ($guid ?: 'NOT SET') . ", EPG ID = " . ($epgID ?: 'NOT SET'));
            
            if ($guid == false || $guid == "" || is_null($guid)) {
                agile_tix::agile_tix_log_event("Coming Soon Feed API: ERROR - Invalid coming soon guid");
                return "Error: Invalid coming soon guid.";
            } 
        } else {
            // Main feed uses standard credentials
            $guid = get_option('agile_field_guid');
            $feedTag = get_option('agile_field_epgTag') ?? false;

            if ($feedTag == "" || $feedTag == false || is_null($feedTag)){
                //if we're not using a feed tag, we need a guid 
                if ($guid == false ) {
                    return "Error: Invalid guid.";
                }
            }
        }

        if ($webURL == false){
            return "Error: Invalid webURL.";
        }

        //temp workaround constant
        //$url = "https://qa.agiletix.com/websales/feed.ashx?guid=" . urlencode($guid) . "&format=json&v=latest&showsList=true&CPdata=true&fullDescription=true&withmedia=true";

        $universalTags = "&format=json&v=latest&showsList=true&CPdata=true&fullDescription=true&withmedia=true";

        $guidString = "";
        $feedTagString = "";
        if ($guid != ""){
            $guidString = "guid=" . $guid;
        } else if ($feedTag != ""){
            $feedTagString = "epgtag=" . $feedTag;
        }

        //agile_tix::agile_tix_log_event("fetch_agile_data url formation error guid: " . $guid . " feedTagString: " . $feedTagString);
        

        $url = "";
        

        if ($guidString != ""){
            $url = $webURL . "feed.ashx?" . $guidString;
            // Add epgID parameter if provided (for coming soon feed)
            if ($feed_type === 'coming_soon' && isset($epgID) && $epgID != "" && $epgID != false) {
                $url .= "&epgID=" . urlencode($epgID);
                // agile_tix::agile_tix_log_event("Coming Soon Feed API: Added epgID parameter = " . $epgID);
            }
            $url .= $universalTags;
        } else if ($feedTagString != ""){
            $url = $webURL . "feed.ashx?" . $feedTagString . $universalTags;
        } else {
            //agile_tix::agile_tix_log_event("fetch_agile_data url formation error guidString: " . $guidString . " feedTagString: " . $feedTagString);

            return "Error: Invalid guid.";
        }
        
        // if ($feed_type === 'coming_soon') {
        //     agile_tix::agile_tix_log_event("Coming Soon Feed API: Requesting URL = " . $url);
        // }
        //agile_tix::agile_tix_log_event("fetch_agile_data url: " . ($url));
        $response = wp_remote_get($url);

        //agile_tix::agile_tix_log_event("fetch_agile_data response: " . json_encode($response));

        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            agile_tix::agile_tix_log_event("fetch_agile_data Error: $error_message");
            return "Error: " . $error_message;
        }

        $http_code = wp_remote_retrieve_response_code($response);
        if ($http_code !== 200) {
            $error_body = wp_remote_retrieve_body($response);
            agile_tix::agile_tix_log_event("fetch_agile_data Error: API request failed with status code $http_code. URL: $url");
            if ($feed_type === 'coming_soon') {
                agile_tix::agile_tix_log_event("Coming Soon Feed API: Error response body = " . substr($error_body, 0, 500));
            }
            return "Error: API request failed with status code $http_code.";
        }

        $body = wp_remote_retrieve_body($response);
        if (empty($body)) {
            agile_tix::agile_tix_log_event("fetch_agile_data Error: Received an empty response from the API.");
            return "Error: Received an empty response from the API.";
        }

        $data = json_decode($body, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            //agile_tix::agile_tix_log_event("JSON Decode Error: " . $json_error);
            agile_tix::agile_tix_log_event("fetch_agile_data Error: Failed to decode API response.");
            return "Error: Failed to decode API response.";
        }
        agile_tix_Admin::agile_cache_api_transient($data);

        return $data;
    }

}

