<?php

namespace WHMCS\Module\Addon\ProxyCheap\Admin;

/**
 * Sample Admin Area Controller
 */
class Controller {

public function scripts()
{
    return '<link href="https://cdn.jsdelivr.net/npm/jsoneditor@latest/dist/jsoneditor.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/jsoneditor@latest/dist/jsoneditor.min.js"></script>';
}
public function services($vars)
{
    $planId = $_GET['plan'] ? trim($_GET['plan']) : null;
    $postdata = json_encode(['planId' => $planId, 'service' => $_GET['service'], 'apikey' => $vars['apikey'], 'apisecret' => $vars['apisecret']]);

    $opts = array('http' =>
        array(
            'method'  => 'POST',
                  'header'  => "Content-Type: application/json\r\n" .
                   "Accept: application/json\r\n",
            'content' => $postdata
        )
    );

$context  = stream_context_create($opts);

$result = file_get_contents(\App::getSystemUrl().'index.php?m=proxycheap&json=1&c=V2\OrderConfiguration', false, $context);

return $this->scripts().$this->renderServices($vars).'<h2>API debug data</h2>
<div id="editorservice" style=""></div>
<script>
  const editorservice = document.getElementById("editorservice");
  new JSONEditor(editorservice, {
    mode: "view"
  }, '.$result.');
  
</script>';
}
    /**
     * Index action.
     *
     * @param array $vars Module configuration parameters
     *
     * @return string
     */

public function renderServices($vars)
{
    $modulelink = $vars['modulelink'];
     $apiMetadata = file_get_contents(\App::getSystemUrl().'index.php?m=proxycheap&json=1&c=V2\GetProxyTypes');
        
        $apiMetadataObj = json_decode($apiMetadata);
        $services = isset($apiMetadataObj->services) && is_countable($apiMetadataObj->services) ? $apiMetadataObj->services : [];
        
        $servicesMenuHtml = '';
        foreach($services as $service)
        {

            if(isset($service->plans))
            {
                $servicesMenuHtml .= "<br />";
                foreach($service->plans as $plan)
                {
                    $servicesMenuHtml .= '<a href="'.$modulelink.'&action=services&service='.$service->id.'&plan='.$plan->id.'" class="btn btn-default">'.$service->label.' (Plan:'.$plan->label.')</a>';
                }
                $servicesMenuHtml .= "<br />";
            }
            else
            {
                   $servicesMenuHtml .= '<a href="'.$modulelink.'&action=services&service='.$service->id.'" class="btn btn-default">'.$service->label.'</a>';
            }
            

        }

        return <<<EOF
        
Services: <p>
    {$servicesMenuHtml}
   
</p>

EOF;
}
    public function index($vars)
    {

        return $this->renderServices($vars);
    }

}