<?php
/**
 * Launchmind API Client
 * 
 * Handles all server-side API communication with Launchmind.
 * IMPORTANT: All API calls are server-side only. Never expose API keys to frontend.
 */

if (!defined('ABSPATH')) {
    exit;
}

class Launchmind_API {
    
    /**
     * Get API base URL
     */
    private static function get_api_base() {
        return rtrim(Launchmind_Blog_Connector::get_option('api_base', LAUNCHMIND_API_DEFAULT_BASE), '/');
    }
    
    /**
     * Get API key
     */
    private static function get_api_key() {
        return Launchmind_Blog_Connector::get_option('api_key', '');
    }
    
    /**
     * Get site ID
     */
    private static function get_site_id() {
        return Launchmind_Blog_Connector::get_option('site_id', '');
    }
    
    /**
     * Make API request
     * 
     * @param string $endpoint API endpoint
     * @param array $params Query parameters
     * @return array|WP_Error Response data or error
     */
    private static function request($endpoint, $params = array()) {
        $api_key = self::get_api_key();
        $api_base = self::get_api_base();
        
        if (empty($api_key)) {
            return new WP_Error('no_api_key', __('API key not configured', 'launchmind-blog'));
        }
        
        // Always include api_key as query parameter (some hosts block Authorization header)
        $params['api_key'] = $api_key;
        
        // Build URL with query parameters
        $url = $api_base . $endpoint;
        if (!empty($params)) {
            $url = add_query_arg($params, $url);
        }
        
        // Make request with authorization header (as backup)
        $response = wp_remote_get($url, array(
            'timeout' => 30,
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
                'X-Launchmind-Platform' => 'wordpress',
                'X-Launchmind-Version' => LAUNCHMIND_BLOG_VERSION,
            ),
        ));
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if ($status_code !== 200) {
            $error_message = isset($data['error']) ? $data['error'] : __('API request failed', 'launchmind-blog');
            return new WP_Error('api_error', $error_message, array('status' => $status_code));
        }
        
        return $data;
    }
    
    /**
     * Get blog posts list
     * 
     * @param array $args Arguments (limit, offset, lang)
     * @return array|WP_Error Posts array or error
     */
    public static function get_posts($args = array()) {
        $defaults = array(
            'limit' => 10,
            'offset' => 0,
            'lang' => get_locale() ? substr(get_locale(), 0, 2) : 'en',
        );
        
        $args = wp_parse_args($args, $defaults);
        
        // Add site ID
        $site_id = self::get_site_id();
        if (!empty($site_id)) {
            $args['site'] = $site_id;
        }
        
        // Check cache first
        $cache_key = Launchmind_Cache::generate_key('posts', $args);
        $cached = Launchmind_Cache::get($cache_key);
        
        if (false !== $cached) {
            return $cached;
        }
        
        // Make API request
        $response = self::request('/blog/customer', $args);
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        // Normalize response - handle both array of posts and object with posts key
        $posts = isset($response['posts']) ? $response['posts'] : (is_array($response) ? $response : array());
        
        // Map to standard format
        $normalized = self::normalize_posts($posts);
        
        // Cache the result
        Launchmind_Cache::set($cache_key, $normalized);
        
        return $normalized;
    }
    
    /**
     * Get single blog post by slug
     * 
     * @param string $slug Post slug
     * @param string $lang Language code
     * @return array|WP_Error Post data or error
     */
    public static function get_post($slug, $lang = null) {
        if (empty($slug)) {
            return new WP_Error('no_slug', __('Post slug is required', 'launchmind-blog'));
        }
        
        $lang = $lang ?: (get_locale() ? substr(get_locale(), 0, 2) : 'en');
        
        $params = array(
            'lang' => $lang,
        );
        
        // Add site ID
        $site_id = self::get_site_id();
        if (!empty($site_id)) {
            $params['site'] = $site_id;
        }
        
        // Check cache first
        $cache_key = Launchmind_Cache::generate_key('post_' . $slug, $params);
        $cached = Launchmind_Cache::get($cache_key);
        
        if (false !== $cached) {
            return $cached;
        }
        
        // Make API request - use slug as query param for customer endpoint
        $params['slug'] = $slug;
        $response = self::request('/blog/customer', $params);
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        // Customer API returns post wrapped in 'post' key
        $post_data = isset($response['post']) ? $response['post'] : $response;
        
        // Normalize single post
        $normalized = self::normalize_post($post_data);
        
        // Cache the result
        Launchmind_Cache::set($cache_key, $normalized);
        
        return $normalized;
    }
    
    /**
     * Test API connection
     * 
     * @return array|WP_Error Success message or error
     */
    public static function test_connection() {
        $response = self::request('/blog/customer', array('limit' => 1));
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        return array(
            'success' => true,
            'message' => __('Connection successful', 'launchmind-blog'),
        );
    }
    
    /**
     * Normalize posts array to standard format
     * 
     * @param array $posts Raw posts from API
     * @return array Normalized posts
     */
    private static function normalize_posts($posts) {
        if (!is_array($posts)) {
            return array();
        }
        
        return array_map(array(__CLASS__, 'normalize_post'), $posts);
    }
    
    /**
     * Get available languages for a post
     * Uses availableLanguages from the post data if available, otherwise falls back to checking cache
     * 
     * @param string $slug Post slug
     * @param array $post_data Optional post data that may already contain availableLanguages
     * @return array Available language codes
     */
    public static function get_post_languages($slug, $post_data = null) {
        if (empty($slug)) {
            return array();
        }
        
        // If post data is provided and contains availableLanguages, use that (much faster!)
        if (!empty($post_data) && isset($post_data['availableLanguages']) && is_array($post_data['availableLanguages'])) {
            return $post_data['availableLanguages'];
        }
        
        // Fallback: Try to get from cached post data
        $lang = get_locale() ? substr(get_locale(), 0, 2) : 'en';
        $params = array('slug' => $slug, 'lang' => $lang);
        $site_id = self::get_site_id();
        if (!empty($site_id)) {
            $params['site'] = $site_id;
        }
        
        $cache_key = Launchmind_Cache::generate_key('post_' . $slug, $params);
        $cached_post = Launchmind_Cache::get($cache_key);
        
        if (false !== $cached_post && isset($cached_post['availableLanguages']) && is_array($cached_post['availableLanguages'])) {
            return $cached_post['availableLanguages'];
        }
        
        // Last resort: return current language only (prevents multiple API calls)
        return array($lang);
    }
    
    /**
     * Normalize single post to standard format
     * 
     * @param array $post Raw post from API
     * @return array Normalized post
     */
    private static function normalize_post($post) {
        if (!is_array($post)) {
            return array();
        }
        
        return array(
            'title' => isset($post['title']) ? sanitize_text_field($post['title']) : '',
            'slug' => isset($post['slug']) ? sanitize_title($post['slug']) : '',
            'excerpt' => isset($post['excerpt']) ? wp_kses_post($post['excerpt']) : '',
            'html' => isset($post['content']) ? wp_kses_post($post['content']) : (isset($post['html']) ? wp_kses_post($post['html']) : ''),
            'coverImage' => isset($post['image']) ? esc_url($post['image']) : (isset($post['coverImage']) ? esc_url($post['coverImage']) : ''),
            'tags' => isset($post['keywords']) ? array_map('sanitize_text_field', (array) $post['keywords']) : (isset($post['tags']) ? array_map('sanitize_text_field', (array) $post['tags']) : array()),
            'author' => isset($post['author']) ? sanitize_text_field($post['author']) : 'Launchmind',
            'publishedAt' => isset($post['date']) ? sanitize_text_field($post['date']) : (isset($post['publishedAt']) ? sanitize_text_field($post['publishedAt']) : ''),
            'availableLanguages' => isset($post['availableLanguages']) ? array_map('sanitize_text_field', (array) $post['availableLanguages']) : array(),
            'seo' => array(
                'title' => isset($post['seo']['title']) ? sanitize_text_field($post['seo']['title']) : (isset($post['title']) ? sanitize_text_field($post['title']) : ''),
                'description' => isset($post['seo']['description']) ? sanitize_text_field($post['seo']['description']) : (isset($post['metaDescription']) ? sanitize_text_field($post['metaDescription']) : ''),
            ),
        );
    }
}

