<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Setting;
use Inertia\Inertia;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Cache;

class PwaSettingController extends Controller
{
    public function index()
    {
        $settings = Setting::whereIn('key', [
            'pwa_enable', 'pwa_name', 'pwa_short_name', 
            'pwa_theme_color', 'pwa_bg_color'
        ])->pluck('value', 'key')->toArray();

        $iconPath = Storage::disk('public')->exists('settings/pwa_icon.png') 
            ? asset('storage/settings/pwa_icon.png') . '?v=' . time() 
            : null;

        return Inertia::render('cp/Settings/Pwa', [
            'settings' => $settings,
            'pwaIcon' => $iconPath
        ]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'pwa_enable' => 'boolean',
            'pwa_name' => 'required|string|max:255',
            'pwa_short_name' => 'required|string|max:50',
            'pwa_theme_color' => 'required|string|max:10',
            'pwa_bg_color' => 'required|string|max:10',
            'pwa_icon' => 'nullable|image|mimes:png|max:2048|dimensions:min_width=512,min_height=512',
        ]);

        Setting::updateOrCreate(['key' => 'pwa_enable'], ['value' => $request->pwa_enable ? '1' : '0']);
        Setting::updateOrCreate(['key' => 'pwa_name'], ['value' => $request->pwa_name]);
        Setting::updateOrCreate(['key' => 'pwa_short_name'], ['value' => $request->pwa_short_name]);
        Setting::updateOrCreate(['key' => 'pwa_theme_color'], ['value' => $request->pwa_theme_color]);
        Setting::updateOrCreate(['key' => 'pwa_bg_color'], ['value' => $request->pwa_bg_color]);

        if ($request->hasFile('pwa_icon')) {
            // PWA heavily relies on exact PNG formats for icons
            $request->file('pwa_icon')->storeAs('settings', 'pwa_icon.png', 'public');
        }

        Cache::forget('app_settings');

        return back()->with('success', 'PWA Settings updated successfully.');
    }
}