<?php
namespace OPNsense\RMMAgent\Api;
use OPNsense\Base\ApiControllerBase;
use OPNsense\RMMAgent\RMMAgent;
use OPNsense\Core\Config;

class SettingsController extends ApiControllerBase
{
    public function getAction()
    {
        $mdl = new RMMAgent();
        $result = array('rmmagent' => array('general' => array()));
        foreach ($mdl->general->iterateItems() as $key => $node) {
            $result['rmmagent']['general'][$key] = (string)$node;
        }
        return $result;
    }

    public function setAction()
    {
        $result = array('result' => 'failed');
        if ($this->request->isPost()) {
            $mdl = new RMMAgent();
            $post = null;

            // OPNsense sends data as rmmagent[general][KEY]
            $rmmagent = $this->request->getPost('rmmagent');
            if (!empty($rmmagent) && isset($rmmagent['general'])) {
                $post = $rmmagent['general'];
            }

            // Fallback: JSON body
            if (empty($post)) {
                $rawBody = $this->request->getRawBody();
                if (!empty($rawBody)) {
                    $jsonData = json_decode($rawBody, true);
                    if (isset($jsonData['rmmagent']['general'])) {
                        $post = $jsonData['rmmagent']['general'];
                    } elseif (isset($jsonData['general'])) {
                        $post = $jsonData['general'];
                    }
                }
            }

            if (!empty($post)) {
                foreach ($post as $key => $value) {
                    try {
                        $node = $mdl->general->$key;
                        if ($node !== null) {
                            $node->setValue($value);
                        }
                    } catch (\Exception $e) {
                        // skip
                    }
                }
            }

            $valMsgs = $mdl->performValidation();
            if ($valMsgs->count() > 0) {
                $result['validations'] = array();
                foreach ($valMsgs as $msg) {
                    $result['validations']['rmmagent.general.' . $msg->getField()] = $msg->getMessage();
                }
            } else {
                $mdl->serializeToConfig();
                Config::getInstance()->save();
                $result['result'] = 'saved';
            }
        }
        return $result;
    }
}
