<?php
/**
 * AgentForms API Client
 *
 * Handles fetching form config from agentforms.io with WP option caching.
 * Cache TTL: 24 hours (AGENTFORMS_CACHE_TTL).
 *
 * API endpoints:
 *   GET /api/v2/forms/{token}/config  — public, no auth
 *   POST /api/submit?token={token}     — public, form data
 */

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

/**
 * Get cached form config or fetch from API.
 *
 * @param string $token The form token.
 * @return array|false Form config on success, false on failure.
 */
function agentforms_get_config( $token ) {
    // Check cache first
    $cached = get_option( 'agentforms_config_' . md5( $token ) );
    if ( $cached && is_array( $cached ) && isset( $cached['expires'] ) && $cached['expires'] > time() ) {
        return $cached['config'];
    }

    // Fetch from API
    $config = agentforms_fetch_config( $token );
    if ( $config === false ) {
        // Return stale cache if available
        if ( $cached && is_array( $cached ) && isset( $cached['config'] ) ) {
            return $cached['config'];
        }
        return false;
    }

    // Cache with TTL
    $cache_data = array(
        'config'  => $config,
        'expires' => time() + AGENTFORMS_CACHE_TTL,
    );
    update_option( 'agentforms_config_' . md5( $token ), $cache_data );

    return $config;
}

/**
 * Fetch form config from agentforms.io API.
 *
 * @param string $token The form token.
 * @return array|false Form config array on success, false on failure.
 */
function agentforms_fetch_config( $token ) {
    $settings = get_option( 'agentforms_settings', array() );
    $base_url = isset( $settings['api_base_url'] ) ? $settings['api_base_url'] : AGENTFORMS_BASE_URL;
    $url      = rtrim( $base_url, '/' ) . '/api/v2/forms/' . rawurlencode( $token ) . '/config';

    $response = wp_remote_get( $url, array(
        'timeout'            => 15,
        'httpversion'        => '1.1',
        'redirection'        => 5,
        'headers'            => array(
            'Accept'        => 'application/json',
            'User-Agent'    => 'AgentForms-WP/' . AGENTFORMS_VERSION . '; ' . get_bloginfo( 'url' ),
        ),
    ) );

    if ( is_wp_error( $response ) ) {
        error_log( 'AgentForms API error: ' . $response->get_error_message() );
        return false;
    }

    $status = wp_remote_retrieve_response_code( $response );
    if ( $status !== 200 ) {
        error_log( 'AgentForms API status: ' . $status . ' for token ' . $token );
        return false;
    }

    $body = wp_remote_retrieve_body( $response );
    $data = json_decode( $body, true );

    if ( ! is_array( $data ) || ! isset( $data['fields'] ) ) {
        error_log( 'AgentForms API invalid response for token ' . $token );
        return false;
    }

    return $data;
}

/**
 * Clear the config cache for a specific token.
 *
 * @param string $token The form token.
 */
function agentforms_clear_cache( $token ) {
    delete_option( 'agentforms_config_' . md5( $token ) );
}

/**
 * Clear all AgentForms caches.
 */
function agentforms_clear_all_caches() {
    global $wpdb;
    $prefix = $wpdb->prefix . 'agentforms_config_';
    $rows   = $wpdb->get_col( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '{$prefix}%'" );
    if ( ! empty( $rows ) ) {
        foreach ( $rows as $row ) {
            delete_option( $row );
        }
    }
}