<?php

namespace App\Http\Controllers;

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

class PwaController extends Controller
{
    public function manifest()
    {
        $settings = Cache::rememberForever('app_settings', function () {
            return Setting::pluck('value', 'key')->toArray();
        });

        if (($settings['pwa_enable'] ?? '0') !== '1') {
            return response()->json(['error' => 'PWA is disabled'], 404);
        }

        $iconUrl = Storage::disk('public')->exists('settings/pwa_icon.png') 
            ? asset('storage/settings/pwa_icon.png') 
            : asset('placeholder.png');

        $manifest = [
            'name' => $settings['pwa_name'] ?? config('app.name'),
            'short_name' => $settings['pwa_short_name'] ?? config('app.name'),
            'start_url' => '/',
            'display' => 'standalone',
            'background_color' => $settings['pwa_bg_color'] ?? '#ffffff',
            'theme_color' => $settings['pwa_theme_color'] ?? '#000000',
            'orientation' => 'portrait',
            'icons' => [
                [
                    'src' => $iconUrl,
                    'sizes' => '192x192',
                    'type' => 'image/png',
                    'purpose' => 'any maskable'
                ],
                [
                    'src' => $iconUrl,
                    'sizes' => '512x512',
                    'type' => 'image/png',
                    'purpose' => 'any maskable'
                ]
            ]
        ];

        return response()->json($manifest);
    }

    public function serviceWorker()
    {
        $settings = Cache::rememberForever('app_settings', function () {
            return Setting::pluck('value', 'key')->toArray();
        });

        if (($settings['pwa_enable'] ?? '0') !== '1') {
            return response('// PWA Disabled', 200)->header('Content-Type', 'application/javascript');
        }

        // --- Safely return a 503 response if cache matching fails instead of throwing a TypeError ---
        $sw = <<<JS
const CACHE_NAME = 'ownstore-pwa-v1';

self.addEventListener('install', (event) => {
    self.skipWaiting();
});

self.addEventListener('activate', (event) => {
    event.waitUntil(clients.claim());
});

self.addEventListener('fetch', (event) => {
    if (event.request.method !== 'GET') return;
    
    event.respondWith(
        fetch(event.request).catch(async () => {
            const cachedResponse = await caches.match(event.request);
            if (cachedResponse) {
                return cachedResponse;
            }
            // Return a safe fallback Response if neither network nor cache works
            return new Response('You are offline.', {
                status: 503,
                statusText: 'Service Unavailable'
            });
        })
    );
});
JS;

        return response($sw, 200)
            ->header('Content-Type', 'application/javascript')
            ->header('Cache-Control', 'no-cache, no-store, must-revalidate');
    }
}