<?php

namespace AleshaCMS\Http\Controllers\Admin;

use AleshaCMS\Http\Controllers\Controller;
use AleshaCMS\Models\CMS\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class SettingsController extends Controller
{
    public function index(string $group = 'general')
    {
        $settings = Setting::where('group', $group)->pluck('value', 'key');
        return view('admin.settings.index', compact('settings', 'group'));
    }

    protected array $allowedKeys = [
        'general'      => ['site_name', 'site_tagline', 'site_email', 'site_url', 'site_timezone', 'site_logo', 'site_favicon'],
        'reading'      => ['posts_per_page', 'homepage_id'],
        'writing'      => [],
        'media'        => ['media_max_size'],
        'social'       => ['social_facebook', 'social_instagram', 'social_tiktok', 'social_twitter', 'social_youtube'],
        'seo'          => ['meta_title', 'meta_description', 'enable_sitemap'],
        'integrations' => ['disqus_shortname'],
    ];

    public function update(Request $request, string $group = 'general')
    {
        $allowed = $this->allowedKeys[$group] ?? [];

        // Handle file uploads
        $fileKeys = ['site_logo', 'site_favicon'];
        foreach ($fileKeys as $fileKey) {
            if (!in_array($fileKey, $allowed, true)) continue;
            if ($request->hasFile($fileKey)) {
                $request->validate([$fileKey => 'image|max:2048|mimes:jpg,jpeg,png,gif,webp,svg,ico']);
                $path = $request->file($fileKey)->store('site', 'public');
                Setting::set($fileKey, '/storage/' . $path, $group);
            }
        }

        // Handle text fields
        foreach ($request->except(array_merge(['_token', '_method'], $fileKeys)) as $key => $value) {
            if (!in_array($key, $allowed, true)) continue;
            Setting::set($key, is_array($value) ? implode(',', $value) : (string) $value, $group);
        }

        Cache::flush();

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'message' => 'Settings saved.']);
        }

        return back()->with('success', 'Settings saved.');
    }
}
