<?php

namespace Core\App\Controllers;

class SettingsSecurityController
{
    private string $file;

    public function __construct()
    {
        $this->file = ROOT_PATH . '/storage/settings/settings_security.json';
    }

    private function load(): array
    {
        if (!file_exists($this->file)) {
            return [];
        }

        $data = json_decode(file_get_contents($this->file), true);
        return is_array($data) ? $data : [];
    }

    private function saveData(array $data): void
    {
        $dir = dirname($this->file);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        file_put_contents(
            $this->file,
            json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
        );
    }

    public function index()
    {
        $securitySettings = $this->load();

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/settings/security_settings.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    public function save()
    {
        $settings = $this->load();

        $settings['maintenance_mode'] = (int)($_POST['maintenance_mode'] ?? 0);
        $settings['maintenance_msg']  = trim($_POST['maintenance_msg'] ?? '');

        $settings['ddos_enabled'] = (int)($_POST['ddos_enabled'] ?? 0);
        $settings['ddos_limit']   = (int)($_POST['ddos_limit'] ?? 60);

        $settings['ban_list'] = array_values(array_filter(array_map(
            'trim',
            explode("\n", $_POST['ban_list'] ?? '')
        )));

        $settings['whitelist'] = array_values(array_filter(array_map(
            'trim',
            explode("\n", $_POST['whitelist'] ?? '')
        )));

        $this->saveData($settings);

        header("Location: /admin/settings/security?saved=1");
        exit;
    }

    public function clearLogs()
    {
        header("Location: /admin/system/errors");
        exit;
    }
}
