<?php

namespace App\Http\Controllers\Portal;

use App\Domain\Shared\Services\BrandingService;
use App\Domain\Shared\Services\SettingsService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

/**
 * The per-tenant web app manifest.
 *
 * Three things here are not decoration:
 *
 *  - `Cache-Control: private, no-store`. This is a per-tenant response on a
 *    per-tenant hostname; a shared proxy that cached it would hand one
 *    academy's branding to another's members.
 *  - Icon paths are relative. config/filesystems.php builds public URLs from
 *    env('APP_URL') verbatim with no https coercion, and a single http URL
 *    makes the manifest invalid — at which point the install prompt simply
 *    never appears, with no error anywhere.
 *  - `start_url` and `scope` are both `/app/`, so installing the portal does
 *    not capture the ERP or the public website.
 */
class ManifestController extends Controller
{
    public function __invoke(BrandingService $branding, SettingsService $settings): JsonResponse
    {
        $brand = $branding->forCurrentAcademy();

        $icons = [];
        $stored = json_decode((string) $settings->get('branding.icon_set', '{}'), true) ?: [];

        foreach ($stored as $size => $path) {
            $icons[] = [
                'src' => '/storage/' . ltrim((string) $path, '/'),
                'sizes' => "{$size}x{$size}",
                'type' => 'image/png',
                'purpose' => (int) $size >= 192 ? 'any maskable' : 'any',
            ];
        }

        if ($icons === [] && $brand->logoUrl) {
            $icons[] = [
                'src' => $this->relative($brand->logoUrl),
                'sizes' => '512x512',
                'type' => 'image/png',
                'purpose' => 'any',
            ];
        }

        $manifest = [
            'id' => '/app/',
            'name' => $brand->academyName,
            'short_name' => $brand->appShortName,
            'description' => __('بوابة') . ' ' . term('members') . ' ' . $brand->academyName,
            'start_url' => '/app/',
            'scope' => '/app/',
            'display' => 'standalone',
            'orientation' => 'portrait',
            'dir' => 'rtl',
            'lang' => app()->getLocale(),
            'background_color' => $brand->themeMode === 'dark' ? '#111827' : '#ffffff',
            'theme_color' => $brand->themeColor,
            'icons' => $icons,
            'shortcuts' => [
                [
                    'name' => __('المدفوعات'),
                    'url' => '/app/payments',
                ],
                [
                    'name' => __('التدريب'),
                    'url' => '/app/training',
                ],
            ],
        ];

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

    private function relative(string $url): string
    {
        $path = parse_url($url, PHP_URL_PATH);

        return $path ?: $url;
    }
}
