<?php
/**
 * Author: Rymera Web Co.
 *
 * @package SAAI\REST
 */

namespace SAAI\REST;

use SAAI\Abstracts\Abstract_REST;
use SAAI\Classes\Plan_Manager;
use SAAI\Traits\Singleton_Trait;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

defined( 'ABSPATH' ) || exit;

/**
 * Account REST API controller class.
 *
 * @since 1.0.7
 */
class Account extends Abstract_REST {

    use Singleton_Trait;

    /**
     * Holds the class instance object
     *
     * @since 1.0.7
     * @var Account $instance object
     */
    protected static $instance;

    /**
     * REST constructor.
     *
     * @since 1.0.7
     */
    public function __construct() {
    }

    /**
     * Works as constructor for this class.
     *
     * @since 1.0.7
     * @return void
     */
    public function register_plugin_routes() {
        $this->rest_base = 'account';
        parent::register_plugin_routes();
    }

    /**
     * Register the routes for Plan Manager.
     *
     * @since 1.0.7
     * @return void
     */
    public function register_routes() {
        // Manual fetch endpoint.
        register_rest_route(
            $this->namespace,
            "/$this->rest_base/fetch",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'manual_fetch_plans' ),
                'permission_callback' => array( $this, 'update_item_permissions_check' ),
            )
        );

        // Get plan status endpoint.
        register_rest_route(
            $this->namespace,
            "/$this->rest_base/status",
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_plan_status' ),
                'permission_callback' => array( $this, 'get_item_permissions_check' ),
            )
        );
    }

    /**
     * Manually fetch subscription plans.
     *
     * @param WP_REST_Request $request The request object.
     * @return WP_REST_Response|WP_Error The response object or error.
     */
    public function manual_fetch_plans( $request ) {
        $plan_manager = Plan_Manager::instance();

        if ( ! $plan_manager ) {
            return new WP_Error(
                'plan_manager_not_available',
                __( 'Plan Manager is not available.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 500 )
            );
        }

        $result = $plan_manager->manual_fetch();

        if ( is_wp_error( $result ) ) {
            return new WP_REST_Response(
                array(
                    'success' => false,
                    'message' => $result->get_error_message(),
                    'code'    => $result->get_error_code(),
                ),
                400
            );
        }

        return new WP_REST_Response(
            array(
                'success' => true,
                'message' => __( 'Subscription plans fetched successfully.', 'storeagent-ai-for-woocommerce' ),
                'data'    => $plan_manager->get_status(),
            ),
            200
        );
    }

    /**
     * Get current plan status.
     *
     * @param WP_REST_Request $request The request object.
     * @return WP_REST_Response|WP_Error The response object or error.
     */
    public function get_plan_status( $request ) {
        $plan_manager = Plan_Manager::instance();

        if ( ! $plan_manager ) {
            return new WP_Error(
                'plan_manager_not_available',
                __( 'Plan Manager is not available.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 500 )
            );
        }

        // Check if force refresh is requested.
        $force_refresh = rest_sanitize_boolean( $request->get_param( 'force_refresh' ) );
        if ( $force_refresh ) {
            // Fetch fresh plan data from remote server before returning status.
            $fetch_result = $plan_manager->manual_fetch();

            // If fetch fails, log the error but still return cached data.
            if ( is_wp_error( $fetch_result ) ) {
                wc_get_logger()->warning(
                    'Failed to refresh plan data: ' . $fetch_result->get_error_message(),
                    array( 'source' => 'storeagent-ai-for-woocommerce' )
                );
                // Continue to return cached data even if refresh failed.
            }
        }

        return new WP_REST_Response(
            array(
                'success' => true,
                'data'    => $plan_manager->get_status(),
            ),
            200
        );
    }
}
