<?php

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

add_action( 'rest_api_init', function () {
    register_rest_route( 'icd-hosting/v1', '/catalog', array(
        'methods'  => 'GET',
        'callback' => 'icd_hosting_rest_catalog',
        'permission_callback' => '__return_true', // public
    ) );
} );

/**
 * REST callback to return catalog and related small payload.
 *
 * @param \WP_REST_Request $request
 * @return \WP_REST_Response|\WP_Error
 */
function icd_hosting_rest_catalog( \WP_REST_Request $request ) {
    try {
        // Ensure plugin instance is available - check both namespaced and global function
        if ( ! function_exists( '\ICD\Hosting\ICD_Hosting' ) && ! function_exists( 'ICD\Hosting\ICD_Hosting' ) ) {
            return new WP_Error( 'plugin_not_loaded', 'Hosting plugin not available', array( 'status' => 500 ) );
        }

        // Get instance using the namespaced function
        $instance = \ICD\Hosting\ICD_Hosting();

        if ( ! $instance ) {
            return new WP_Error( 'plugin_instance_failed', 'Failed to get plugin instance', array( 'status' => 500 ) );
        }

        if ( empty( $instance->order_service ) ) {
            // Try to initialize the app if not yet initialized
            if ( method_exists( $instance, 'init' ) ) {
                $instance->init();
            }
        }

        if ( empty( $instance->order_service ) ) {
            return new WP_Error( 'service_unavailable', 'Order service unavailable', array( 'status' => 500 ) );
        }

        $viewdata = $instance->order_service->getOrderViewData();

        // Build tlds_extra_attributes similar to hosting_order shortcode
        $tlds_extra_attributes = array();
        if ( ! empty( $viewdata['tlds'] ) && is_array( $viewdata['tlds'] ) ) {
            foreach ( $viewdata['tlds'] as $tld => $tld_info ) {
                $tlds_extra_attributes[ $tld ] = isset( $tld_info['extra_attributes'] ) ? $tld_info['extra_attributes'] : array();
            }
        }

        $payload = array(
            'catalog' => isset( $viewdata['catalog'] ) ? $viewdata['catalog'] : array(),
            'resources' => isset( $viewdata['resources'] ) ? $viewdata['resources'] : array(),
            'tlds_extra_attributes' => $tlds_extra_attributes,
            'store_currency' => isset( $viewdata['store']['currency'] ) ? $viewdata['store']['currency'] : '',
        );

        $response = rest_ensure_response( $payload );
        // Cache for 60 minutes
        $response->header( 'Cache-Control', 'public, max-age=3600' );

        return $response;
    } catch ( \ICD\Hosting\Services\AppException $e ) {
        return new WP_Error( 'app_error', 'Failed to retrieve catalog', array( 'status' => 500 ) );
    } catch ( \Exception $e ) {
        return new WP_Error( 'unknown_error', 'Failed to retrieve catalog', array( 'status' => 500 ) );
    }
}

