<?php
/**
 * Kognetiks Chatbot - Download File from API - Ver 2.0.3
 *
 * This file contains the code for downloading a file generated by an Assistant.
 * 
 *
 * @package chatbot-chatgpt
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
    die();
}

function download_openai_file($file_id, $filename) {

    global $chatbot_chatgpt_plugin_dir_path;

    global $session_id;

    $downloads_dir = $chatbot_chatgpt_plugin_dir_path . 'downloads/';

    // Ensure the directory exists or attempt to create it
    if (!create_directory_and_index_file($downloads_dir)) {
        // Error handling, e.g., log the error or handle the failure appropriately
        // FIXME - Return an error message
        return false;
    }

    $api_key = esc_attr(get_option('chatbot_chatgpt_api_key'));
    // Decrypt the API key - Ver 2.2.6
    $api_key = chatbot_chatgpt_decrypt_api_key($api_key);
    if (empty($api_key)) {
        // FIXME - Return an error message
        return false;
    }

    // API endpoint to retrieve the file content
    $api_file_url = "https://api.openai.com/v1/files/$file_id/content";

    // Set up HTTP request arguments
    $args = array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key
        ),
        'timeout' => 30, // Prevent long wait times
    );

    // Make the request using WP HTTP API
    $response = wp_remote_get($api_file_url, $args);

    // Check for request errors
    if (is_wp_error($response)) {
        prod_trace( 'ERROR', 'Error retrieving file from OpenAI: ' . $response->get_error_message());
        return false;
    }

    // Retrieve HTTP status code
    $http_code = wp_remote_retrieve_response_code($response);

    // Check if the request was successful
    if ($http_code == 200) {

        // Retrieve response body (file contents)
        $file_content = wp_remote_retrieve_body($response);

        if (empty($file_content)) {
            prod_trace( 'ERROR', 'Error: Retrieved file content is empty.');
            return false;
        }

        // Define the full file path
        $file_path = trailingslashit($downloads_dir) . $filename;

        // Save the file locally
        if (file_put_contents($file_path, $file_content) === false) {
            prod_trace( 'ERROR', 'Error: Failed to save file locally.');
            return false;
        }

        // Return the file URL
        return content_url('plugins/' . basename($chatbot_chatgpt_plugin_dir_path) . '/downloads/' . $filename);

    } else {

        // DIAG - Diagnostics - Ver 2.4.5
        prod_trace( 'ERROR', 'Failed to retrieve the file: ' . $http_code);
        return false;
    }
}

// Delete old download files - Ver 2.0.3
function chatbot_chatgpt_cleanup_download_directory() {

    global $chatbot_chatgpt_plugin_dir_path;

    $download_dir = $chatbot_chatgpt_plugin_dir_path . 'downloads/';
    foreach (glob($download_dir . '*') as $file) {
        // Delete files older than 1 hour
        if (filemtime($file) < time() - 60 * 60 * 1) {
            unlink($file);
        }
    }
    // Create the index.php file if it does not exist
    create_directory_and_index_file($download_dir);
    
}
add_action('chatbot_chatgpt_cleanup_download_files', 'chatbot_chatgpt_cleanup_download_directory');
