<?php



namespace OPNsense\Freeradius\Api;

use OPNsense\Base\ApiControllerBase;
use OPNsense\Freeradius\Eap;
use OPNsense\Core\Config;

class EapController extends ApiControllerBase
{
    public function getAction()
    {
        // define list of configurable settings
        $result = array();
        if ($this->request->isGet()) {
            $mdlEAP = new EAP();
            $result['eap'] = $mdlEAP->getNodes();
        }
        return $result;
    }

    public function setAction()
    {
        $result = array("result" => "failed");
        if ($this->request->isPost()) {
            // load model and update with provided data
            $mdlEAP = new EAP();
            $mdlEAP->setNodes($this->request->getPost("eap"));

            // perform validation
            $valMsgs = $mdlEAP->performValidation();
            foreach ($valMsgs as $field => $msg) {
                if (!array_key_exists("validations", $result)) {
                    $result["validations"] = array();
                }
                $result["validations"]["eap." . $msg->getField()] = $msg->getMessage();
            }

            // serialize model to config and save
            if ($valMsgs->count() == 0) {
                $mdlEAP->serializeToConfig();
                Config::getInstance()->save();
                $result["result"] = "saved";
            }
        }
        return $result;
    }
}
