<?php

/* Titan © TakfeDev (MKJUEL). All Rights. */

namespace App\Http\Controllers\Api\Admin;

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

class PwaSettingsController extends Controller
{
    public function index(): JsonResponse
    {
        $settings = Setting::where('group', 'pwa')
            ->pluck('value', 'key')
            ->toArray();

        return response()->json([
            'pwa_enabled' => ($settings['pwa_enabled'] ?? 'false') === 'true',
            'pwa_name' => $settings['pwa_name'] ?? config('app.name'),
            'pwa_short_name' => $settings['pwa_short_name'] ?? config('app.name'),
            'pwa_theme_color' => $settings['pwa_theme_color'] ?? '#ffffff',
            'pwa_background_color' => $settings['pwa_background_color'] ?? '#ffffff',
            'pwa_icon' => $settings['pwa_icon'] ?? null,
        ]);
    }

    public function update(Request $request): JsonResponse
    {
        $request->validate([
            'pwa_enabled' => 'required|in:true,false',
            'pwa_name' => 'required|string|max:255',
            'pwa_short_name' => 'required|string|max:50',
            'pwa_theme_color' => 'required|string|max:10',
            'pwa_background_color' => 'required|string|max:10',
            'pwa_icon' => 'nullable|image|mimes:png,jpg,jpeg|max:2048', // PWA icons should ideally be PNG
        ]);

        $inputs = $request->except(['pwa_icon']);

        // Save Text Fields
        foreach ($inputs as $key => $value) {
            Setting::updateOrCreate(
                ['group' => 'pwa', 'key' => $key],
                ['value' => $value]
            );
        }

        // Handle Icon Upload (512x512 recommended)
        if ($request->hasFile('pwa_icon')) {
            $oldSetting = Setting::where('group', 'pwa')->where('key', 'pwa_icon')->first();
            if ($oldSetting && $oldSetting->value) {
                $relativePath = str_replace('/storage/', '', $oldSetting->value);
                Storage::disk('public')->delete($relativePath);
            }

            $path = $request->file('pwa_icon')->store('uploads/pwa', 'public');
            
            Setting::updateOrCreate(
                ['group' => 'pwa', 'key' => 'pwa_icon'],
                ['value' => '/storage/' . $path]
            );
        }

        Cache::forget('pwa_settings');

        return response()->json(['message' => 'PWA Settings updated successfully.']);
    }
}