<?php
namespace Misuzu;

use Misuzu\Config;
use Misuzu\Config\CfgTools;
use Misuzu\Config\IConfig;
use Misuzu\Users\User;

require_once '../../../misuzu.php';

if(!User::hasCurrent()
    || !perms_check_user(MSZ_PERMS_GENERAL, User::getCurrent()->getId(), MSZ_PERM_GENERAL_MANAGE_CONFIG)) {
    echo render_error(403);
    return;
}

$sVar = [
    'name' => '',
    'type' => '',
    'value' => null,
    'new' => true,
];

$sName = (string)filter_input(INPUT_GET, 'name');

if(!empty($sName)) {
    if(!CfgTools::validateName($sName))
        throw new \Exception("Config key name has invalid format.");

    $sVar['name'] = $sName;
}

$sType = (string)filter_input(INPUT_GET, 'type');
if(!empty($sType)) {
    if(!CfgTools::isValidType($sType))
        throw new \Exception("Specified type is invalid.");

    $sVar['type'] = $sType;
    $sVar['value'] = CfgTools::default($sType);
}

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    if(!CSRF::validateRequest())
        throw new \Exception("Request verification failed.");

    if(empty($sName)) {
        $sName = (string)filter_input(INPUT_POST, 'conf_name');

        if(empty($sName) || !CfgTools::validateName($sName))
            throw new \Exception("Config key name has invalid format.");

        $sVar['name'] = $sName;
    }

    $sLogAction = AuditLog::CONFIG_CREATE;

    if($cfg->hasValue($sName)) {
        $sType = CfgTools::type($cfg->getValue($sName));
        $sVar['new'] = false;
        $sLogAction = AuditLog::CONFIG_UPDATE;
    } elseif(empty($sType)) {
        $sType = (string)filter_input(INPUT_POST, 'conf_type');
        if(empty($sType) || !CfgTools::isValidType($sType))
            throw new \Exception("Specified type is invalid.");
    }

    $sVar['type'] = $sType;

    $sValue = CfgTools::default($sType);

    if($sType === 'array') {
        if(!empty($_POST['conf_value']) && is_array($_POST['conf_value'])) {
            foreach($_POST['conf_value'] as $fv) {
                $fv = (string)$fv;

                if(str_starts_with($fv, 's:')) {
                    $fv = substr($fv, 2);
                } elseif(str_starts_with($fv, 'i:')) {
                    $fv = (int)substr($fv, 2);
                } elseif(str_starts_with($fv, 'b:')) {
                    $fv = strtolower(substr($fv, 2));
                    $fv = $fv !== 'false' && $fv !== '0' && $fv !== '';
                }

                $sValue[] = $fv;
            }
        }
    } elseif($sType === 'boolean') {
        $sValue = !empty($_POST['conf_value']);
    } else {
        $sValue = (string)filter_input(INPUT_POST, 'conf_value');
        if($sType === 'integer')
            $sValue = (int)$sValue;
    }

    $sVar['value'] = $sValue;

    AuditLog::create($_SERVER['REMOTE_ADDR'], $sLogAction, [$sName]);
    $cfg->setValue($sName, $sValue);
    url_redirect('manage-general-settings');
    return;
}

if($cfg->hasValue($sName)) {
    $sVar['new'] = false;
    $sValue = $cfg->getValue($sName);
    $sVar['type'] = $sType = CfgTools::type($sValue);

    if($sType === IConfig::T_ARR)
        foreach($sValue as $fk => $fv)
            $sValue[$fk] = ['integer' => 'i', 'string' => 's', 'boolean' => 'b'][gettype($fv)] . ':' . $fv;
    
    $sVar['value'] = $sValue;
}

Template::render('manage.general.setting', [
    'conf_var' => $sVar,
]);
