<?php

namespace App\Services\Admin;

use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;

class SettingsService
{
    public function getGroup(string $group): array
    {
        return Setting::where('group', $group)
            ->get()
            ->mapWithKeys(function ($item) {
                return [$item->key => $item->value];
            })
            ->toArray();
    }

    public function updateGroup(string $group, array $data): void
    {
        foreach ($data as $key => $value) {
            $isEncrypted = str_contains($key, 'password') || str_contains($key, 'secret');

            if ($isEncrypted && empty($value)) {
                continue;
            }

            $finalValue = $value;

            if ($isEncrypted && !empty($value)) {
                try {
                    $finalValue = Crypt::encryptString($value);
                } catch (\Exception $e) {
                    Log::error("SettingsService Encryption Error: " . $e->getMessage());
                    continue; 
                }
            }

            Setting::updateOrCreate(
                ['key' => $key],
                [
                    'group' => $group,
                    'value' => $finalValue, 
                    'is_encrypted' => $isEncrypted
                ]
            );
        }

        // --- CACHE CLEARING LOGIC ---
        Cache::forget("settings.{$group}");

        if ($group === 'seo') {
            Cache::forget('seo_settings');
        }
        if ($group === 'social') {
            Cache::forget('social_settings');
        }
        if ($group === 'scripts') {
            Cache::forget('global_scripts');
        }
    }
}