<?php

namespace App\Http\Controllers;

use App\Models\AppSetting;
use Illuminate\Http\Request;

/**
 * Manifest web app con nombre desde ajustes. Iconos: mismos PNG PWA que index.html y manifest estático
 * (/pwa-192.png, /pwa-512.png en public/) para evitar mezclar logo de marca con tamaños incorrectos.
 */
class PwaManifestController extends Controller
{
    public function show(Request $request)
    {
        $businessName = AppSetting::getValue('business_name', 'Barbería DIAICR') ?? 'Barbería DIAICR';

        $short = function_exists('mb_substr')
            ? mb_substr($businessName, 0, 12, 'UTF-8')
            : substr($businessName, 0, 12);

        $icon192 = $this->absoluteUrl($request, '/pwa-192.png');
        $icon512 = $this->absoluteUrl($request, '/pwa-512.png');

        $manifest = [
            'name' => $businessName,
            'short_name' => $short !== '' ? $short : 'DIAICR',
            'description' => $businessName.' — Reservá tu cita',
            'start_url' => '/',
            'scope' => '/',
            'display' => 'standalone',
            'display_override' => ['standalone', 'fullscreen', 'minimal-ui'],
            'background_color' => '#000000',
            'theme_color' => '#000000',
            'lang' => 'es',
            'categories' => ['lifestyle', 'business'],
            'icons' => [
                ['src' => $icon192, 'sizes' => '192x192', 'type' => 'image/png', 'purpose' => 'any'],
                ['src' => $icon512, 'sizes' => '512x512', 'type' => 'image/png', 'purpose' => 'any'],
                ['src' => $icon512, 'sizes' => '512x512', 'type' => 'image/png', 'purpose' => 'maskable'],
            ],
        ];

        return response()
            ->json($manifest, 200, [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
            ->header('Content-Type', 'application/manifest+json; charset=UTF-8')
            ->header('Cache-Control', 'private, no-cache, no-store, must-revalidate')
            ->header('Pragma', 'no-cache');
    }

    private function absoluteUrl(Request $request, string $path): string
    {
        if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
            return $path;
        }

        return $request->getSchemeAndHttpHost().'/'.ltrim($path, '/');
    }
}
