<?php

namespace App\Http\Controllers;

use App\Services\System\Setting\SystemService;
use Illuminate\Http\JsonResponse;

class PwaManifestController extends Controller
{
    public function show(SystemService $systemService): JsonResponse
    {
        $systemData = $systemService->systemData();
        $appName = $systemData['app_name'] ?? config('app.name', 'DST Collection');
        $iconUrl = $systemData['favicon_url'] ?? $systemData['logo_url'] ?? asset('assets/logo.png');

        $mimeType = 'image/png';
        $lowerIconUrl = strtolower($iconUrl);
        if (str_contains($lowerIconUrl, '.svg')) {
            $mimeType = 'image/svg+xml';
        } elseif (str_contains($lowerIconUrl, '.jpg') || str_contains($lowerIconUrl, '.jpeg')) {
            $mimeType = 'image/jpeg';
        } elseif (str_contains($lowerIconUrl, '.webp')) {
            $mimeType = 'image/webp';
        }

        $manifest = [
            'name' => $appName,
            'short_name' => $appName,
            'description' => "{$appName} - Progressive Web App",
            'theme_color' => '#171717',
            'background_color' => '#ffffff',
            'display' => 'standalone',
            'orientation' => 'portrait',
            'scope' => '/',
            'start_url' => '/',
            'id' => '/',
            'icons' => [
                [
                    'src' => $iconUrl,
                    'sizes' => '64x64',
                    'type' => $mimeType,
                ],
                [
                    'src' => $iconUrl,
                    'sizes' => '192x192',
                    'type' => $mimeType,
                ],
                [
                    'src' => $iconUrl,
                    'sizes' => '512x512',
                    'type' => $mimeType,
                    'purpose' => 'any',
                ],
                [
                    'src' => $iconUrl,
                    'sizes' => '512x512',
                    'type' => $mimeType,
                    'purpose' => 'maskable',
                ],
            ],
        ];

        return response()->json($manifest)
            ->header('Content-Type', 'application/manifest+json')
            ->header('Cache-Control', 'no-cache, no-store, must-revalidate');
    }
}
