<?php

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

class Churnsolution_Connection_Controller
{

    // Here initialize our namespace and resource name.
    /**
     * @var string
     */
    private $namespace;
    /**
     * @var string
     */
    private $resource_name;

    public function __construct()
    {
        // No leading slash: WordPress rejects it and logs _doing_it_wrong on every request.
        $this->namespace = 'churnsolution/v1';
        $this->resource_name = 'connection';
    }

    // Register our routes.
    public function register_routes()
    {
        register_rest_route($this->namespace, '/' . $this->resource_name, array(
            array(
                'methods' => 'GET',
                'callback' => array($this, 'churnsolution_get_connection'),
                'permission_callback' => 'is_user_logged_in',
            )
        ));

    }

    function churnsolution_get_connection(WP_REST_Request $args)
    {

        if (class_exists('Churnsolution_Connection')) {
            $connection = Churnsolution_Connection::get_connection();

            if (empty($connection)) {
                return new stdClass;
            }

            // No api_key: the browser has no use for it now that churnsolution_get_hmac_hash signs
            // server-side, and a customer holding it could mint a launch signature for any
            // subscription on the connection.
            return array(
                'id' => (int)$connection->getId(),
                'app_id' => $connection->getAppId(),
                'gateway' => $connection->getGateway()
            );

        }

        return new stdClass;
    }

}

// Function to register our new routes from the controller.
function churnsolution_register_connection_routes()
{
    $controller = new Churnsolution_Connection_Controller();
    $controller->register_routes();
}

add_action('rest_api_init', 'churnsolution_register_connection_routes');



