<?php

namespace App\Http\Controllers;

use App\Models\ShopSetting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ShopSettingController extends Controller
{
    public function index(): JsonResponse
    {
        $settings = ShopSetting::all()->groupBy('group');
        return response()->json(['success' => true, 'data' => $settings]);
    }

    public function public(): JsonResponse
    {
        // Only return safe public settings
        $keys = ['shop_name', 'shop_description', 'shop_logo', 'shop_favicon',
                 'primary_color', 'contact_email', 'contact_phone',
                 'instagram', 'telegram', 'whatsapp', 'currency', 'currency_symbol'];

        $settings = ShopSetting::whereIn('key', $keys)->pluck('value', 'key');

        return response()->json(['success' => true, 'data' => $settings]);
    }

    public function update(Request $request): JsonResponse
    {
        $request->validate([
            'settings'       => 'required|array',
            'settings.*.key' => 'required|string',
            'settings.*.value' => 'nullable|string',
            'settings.*.group' => 'sometimes|string',
        ]);

        foreach ($request->settings as $setting) {
            ShopSetting::set(
                $setting['key'],
                $setting['value'] ?? null,
                $setting['group'] ?? 'general'
            );
        }

        return response()->json(['success' => true, 'message' => 'Settings updated.']);
    }

    public function uploadLogo(Request $request): JsonResponse
    {
        $request->validate(['logo' => 'required|file|mimes:jpeg,png,webp,svg|max:512000']);

        $oldLogo = ShopSetting::get('shop_logo');
        if ($oldLogo) Storage::disk('public')->delete($oldLogo);

        $path = $request->file('logo')->store('settings', 'public');
        ShopSetting::set('shop_logo', $path, 'general');

        return response()->json(['success' => true, 'data' => ['logo_url' => Storage::url($path)]]);
    }
}
