<?php
/**
 * Gateway Controller for Warranty Cart Admin REST API
 *
 * Reports what the store's payment gateways can do.
 *
 * @package WarrantyCart
 */

namespace WarrantyCart\REST\Controllers;

use WarrantyCart\Integrations\GatewaySupport;
use WarrantyCart\REST\Controller;
use WP_REST_Response;
use WP_REST_Server;

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

/**
 * Gateways class
 */
class Gateways extends Controller {

	/**
	 * Gateway capability lookup.
	 *
	 * @var GatewaySupport
	 */
	private GatewaySupport $gateways;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->rest_base = 'admin';
		$this->gateways  = new GatewaySupport();
	}

	/**
	 * Register routes
	 */
	public function register_routes(): void {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/gateways',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_gateways' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
				),
			)
		);
	}

	/**
	 * List every payment gateway and what it supports.
	 *
	 * @return WP_REST_Response
	 */
	public function get_gateways(): WP_REST_Response {
		return $this->success_response(
			array(
				'gateways' => $this->gateways->status(),

				/*
				 * Warranties are created on `woocommerce_order_status_completed`,
				 * so the answer here is "yes, if the store can take payment at
				 * all". Sent rather than assumed in the client, so the screen
				 * stays honest if that ever stops being true.
				 */
				'sellable' => array() !== $this->gateways->available(),
				'refunds'  => $this->gateways->any_supports( GatewaySupport::REFUNDS ),
			)
		);
	}
}
