<?php

namespace App\Core\Settings\Services;

use App\Core\Settings\Models\SettingModel;

class SettingService
{
    public function get(string $key, ?string $default = null): ?string
    {
        $row = (new SettingModel())->where('setting_key', $key)->first();

        if (! $row) {
            return $default;
        }

        if ((int) $row['is_encrypted'] === 1 && $row['setting_value']) {
            return service('encrypter')->decrypt(base64_decode($row['setting_value']));
        }

        return $row['setting_value'];
    }

    public function set(string $key, ?string $value, string $group = 'general', bool $encrypted = false): void
    {
        $settings = new SettingModel();
        $stored = $encrypted && $value !== null
            ? base64_encode(service('encrypter')->encrypt($value))
            : $value;

        $existing = $settings->where('setting_key', $key)->first();
        $payload = [
            'setting_key' => $key,
            'setting_value' => $stored,
            'setting_group' => $group,
            'is_encrypted' => $encrypted ? 1 : 0,
        ];

        $existing ? $settings->update($existing['id'], $payload) : $settings->insert($payload);
    }

    public function grouped(): array
    {
        $rows = (new SettingModel())->orderBy('setting_group')->orderBy('setting_key')->findAll();
        $grouped = [];

        foreach ($rows as $row) {
            $grouped[$row['setting_group']][] = $row;
        }

        return $grouped;
    }
}
