<?php

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

/**
 * Check if user is authenticated by validating stored token
 * 
 * @return array|false User data if authenticated, false otherwise
 */
function content_craft_ai_check_auth()
{
    // Get stored token
    $token = get_option('content_craft_ai_token');
    if (empty($token)) {
        return false;
    }

    // No cached data, try to get it from API
    try {
        // Add cache buster to prevent caching of the auth check
        $cache_buster = '?_=' . time();

        $response = wp_remote_get(CONTENT_CRAFT_AI_EXTERNAL_API . '/user/me' . $cache_buster, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $token,
                'Content-Type' => 'application/json',
                'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST),
                // Add cache control headers
                'Cache-Control' => 'no-cache, no-store, must-revalidate',
                'Pragma' => 'no-cache'
            ),
            'timeout' => 120
        ));

        // Handle network errors
        if (is_wp_error($response)) {
            return false;
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $status_code = wp_remote_retrieve_response_code($response);

        // Success - update user data and return
        if ($status_code === 200 && !empty($body) && $body['success']) {
            // Store subscription ID if available
            if (!empty($body['user']['subscriptionId'])) {
                update_option('content_craft_ai_active_subscription', $body['user']['subscriptionId']);
                // error_log('Content Craft AI: Stored subscription ID from user profile: ' . $body['user']['subscriptionId']);
            }

            return $body['user'];
        }

        // Clear user data on 401 (expired token)
        if ($status_code === 401) {
            content_craft_ai_clear_auth();
            return false;
        }

        return false;
    } catch (Exception $e) {
        return false;
    }
}

/**
 * Handle get current user request for REST API
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function content_craft_ai_handle_me($request)
{
    // Add no-cache headers to prevent browser caching
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Cache-Control: post-check=0, pre-check=0', false);
    header('Pragma: no-cache');
    header('Expires: 0');

    // Get token from database
    $token = get_option('content_craft_ai_token');

    if (empty($token)) {
        return new WP_Error(
            'no_token',
            'No authentication token found',
            array('status' => 401)
        );
    }

    try {
        // Forward the request to the external API with timestamp to prevent caching
        $response = wp_remote_get(CONTENT_CRAFT_AI_EXTERNAL_API . '/user/me?_=' . time(), array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $token,
                'Content-Type' => 'application/json',
                'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST),
                'Cache-Control' => 'no-cache, no-store, must-revalidate',
                'Pragma' => 'no-cache'
            )
        ));

        if (is_wp_error($response)) {
            throw new Exception($response->get_error_message());
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $status_code = wp_remote_retrieve_response_code($response);

        if ($status_code !== 200 || !$body || !$body['success']) {
            // Token is invalid or expired, clear stored data
            content_craft_ai_clear_auth();

            return new WP_Error(
                'invalid_token',
                $body['message'] ?? 'Token is invalid or expired',
                array('status' => $status_code ?? 401)
            );
        }

        // Create response with no-cache headers
        $response = rest_ensure_response($body);
        $response->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
        $response->header('Pragma', 'no-cache');
        $response->header('Expires', '0');

        return $response;
    } catch (Exception $e) {
        // Clear auth data on error
        content_craft_ai_clear_auth();

        return new WP_Error(
            'api_error',
            'An error occurred while fetching user data',
            array('status' => 500)
        );
    }
}

/**
 * Clear authentication data completely
 */
function content_craft_ai_clear_auth()
{
    // Clear all authentication data
    //NB: Never delete the api key (content_craft_ai_api_key), it's used for the external API and for scheduled articles
    delete_option('content_craft_ai_token');
    delete_option('content_craft_ai_active_subscription');

    // error_log('Content Craft AI: Cleared all authentication data including subscription ID');
}
