<?php

namespace WHMCS\Module\Addon\ProxyCheap;

/**
 * Dispatch Handler
 */
class Dispatcher
{
    private function response($return)
    {
        echo json_encode($return);
        exit;
    }

    public  function dispatch($controller, $parameters)
    {
        ob_clean();
        header('Content-Type: application/json');
        $controller = '\\WHMCS\\Module\\Addon\\ProxyCheap\\Commands\\' . ucfirst($controller);

        if (class_exists($controller)) {
            $input = json_decode(file_get_contents("php://input"), true);

            $controller = new $controller($parameters, $input);    
        } else {
            $this->response(['error' => 'Controller does not exist']);
        }

        $method = $_SERVER['HTTP_CUSTOMMETHOD'] ? strtolower($_SERVER['HTTP_CUSTOMMETHOD']) : strtolower($_SERVER['REQUEST_METHOD']);

        if (is_callable(array($controller, $method))) {
            $return = $controller->$method();

            $this->response($return);
        } else {
            $this->response( ['error' => 'Action doesnt exist'] );
        }




        // Verify requested action is valid and callable


    }
}
