<?php

namespace App\Services;

class LegalService
{
    public function __construct(protected SystemSettingService $systemSettingService)
    {
    }

    public function get(): array
    {
        $defaults = [
            'terms_title' => 'Terms and Conditions',
            'terms_content' => "By creating an account and using this platform, you agree to use the service lawfully and protect your account credentials.\n\nAll purchases are subject to provider availability. Wallet entries are final records for account balance updates.\n\nFraudulent use, abuse, or unauthorized access may lead to account suspension.",
            'terms_version' => 1,
            'terms_updated_at' => null,
        ];

        $values = $this->systemSettingService->many('legal', $defaults);

        return [
            'terms_title' => (string) ($values['terms_title'] ?? $defaults['terms_title']),
            'terms_content' => (string) ($values['terms_content'] ?? $defaults['terms_content']),
            'terms_version' => max(1, (int) ($values['terms_version'] ?? $defaults['terms_version'])),
            'terms_updated_at' => $values['terms_updated_at'] ? (string) $values['terms_updated_at'] : null,
        ];
    }

    public function update(string $title, string $content, bool $publishNewVersion = true): array
    {
        $current = $this->get();
        $version = (int) $current['terms_version'];

        if ($publishNewVersion) {
            $version++;
        }

        $this->systemSettingService->putMany([
            ['section' => 'legal', 'key' => 'terms_title', 'value' => trim($title), 'type' => 'string'],
            ['section' => 'legal', 'key' => 'terms_content', 'value' => trim($content), 'type' => 'string'],
            ['section' => 'legal', 'key' => 'terms_version', 'value' => $version, 'type' => 'integer'],
            ['section' => 'legal', 'key' => 'terms_updated_at', 'value' => now()->toDateTimeString(), 'type' => 'string'],
        ]);

        return $this->get();
    }
}
