<?php

namespace MintyPHP\Service\Branding;

use MintyPHP\Service\Image\ImageUploadTrait;
use MintyPHP\Service\Settings\SettingsAppGateway;

class BrandingFaviconService
{
    use ImageUploadTrait;

    private const MAX_SIZE = 5242880; // 5 MB
    private const SIZES = [
        16 => 'favicon-16x16.png',
        32 => 'favicon-32x32.png',
        96 => 'favicon-96x96.png',
        180 => 'apple-touch-icon.png',
        192 => 'web-app-manifest-192x192.png',
        512 => 'web-app-manifest-512x512.png',
    ];

    public function __construct(private readonly SettingsAppGateway $settingsAppGateway)
    {
    }

    public function storageBase(): string
    {
        return self::imageStorageBase();
    }

    public function storageDir(): string
    {
        return $this->storageBase() . '/branding/favicon';
    }

    public function publicDir(): string
    {
        return rtrim(dirname(__DIR__, 3) . '/web/favicon', '/');
    }

    public function hasFavicon(): bool
    {
        $path = $this->publicDir() . '/favicon-32x32.png';
        return is_file($path);
    }

    public function delete(): void
    {
        $dir = $this->storageDir();
        if (is_dir($dir)) {
            $matches = glob($dir . '/*') ?: [];
            foreach ($matches as $file) {
                if (is_file($file)) {
                    @unlink($file);
                }
            }
        }

        $public = $this->publicDir();
        foreach (self::SIZES as $file) {
            $target = $public . '/' . $file;
            if (is_file($target)) {
                @unlink($target);
            }
        }
    }

    public function saveUpload(array $file): array
    {
        if (empty($file) || !isset($file['tmp_name'])) {
            return ['ok' => false, 'error' => t('No file uploaded')];
        }
        if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            return ['ok' => false, 'error' => t('Upload failed')];
        }
        if (($file['size'] ?? 0) > self::MAX_SIZE) {
            return ['ok' => false, 'error' => t('File is too large')];
        }

        $tmpPath = $file['tmp_name'];
        $mime = $this->detectMime($tmpPath);
        if ($mime !== 'image/png') {
            return ['ok' => false, 'error' => t('Invalid image file')];
        }
        if (!self::imageCanResize()) {
            return ['ok' => false, 'error' => t('Upload failed')];
        }

        $dir = $this->storageDir();
        if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
            return ['ok' => false, 'error' => t('Upload failed')];
        }

        $this->delete();
        $originalPath = $dir . '/original.png';
        if (!move_uploaded_file($tmpPath, $originalPath)) {
            return ['ok' => false, 'error' => t('Upload failed')];
        }
        @chmod($originalPath, 0644);

        $publicDir = $this->publicDir();
        if (!is_dir($publicDir) && !mkdir($publicDir, 0755, true) && !is_dir($publicDir)) {
            return ['ok' => false, 'error' => t('Upload failed')];
        }

        foreach (self::SIZES as $size => $fileName) {
            $target = $publicDir . '/' . $fileName;
            if (!self::imageResizeSquare($originalPath, $target, $size)) {
                return ['ok' => false, 'error' => t('Upload failed')];
            }
            @chmod($target, 0644);
        }

        $this->updateManifest();
        return ['ok' => true, 'path' => $originalPath, 'mime' => $mime];
    }

    public function detectMime(string $path): string
    {
        return self::imageDetectMimeSimple($path);
    }

    private function updateManifest(): void
    {
        $manifestPath = $this->publicDir() . '/site.webmanifest';
        $data = [];
        if (is_file($manifestPath)) {
            $json = file_get_contents($manifestPath);
            $decoded = json_decode((string) $json, true);
            if (is_array($decoded)) {
                $data = $decoded;
            }
        }

        $title = $this->settingsAppGateway->getAppTitle();
        if ($title === null || $title === '') {
            $title = defined('APP_NAME') ? APP_NAME : 'CoreCore';
        }

        $data['name'] = $title;
        $data['short_name'] = $title;
        if (!isset($data['theme_color'])) {
            $data['theme_color'] = '#ffffff';
        }
        if (!isset($data['background_color'])) {
            $data['background_color'] = '#ffffff';
        }
        if (!isset($data['display'])) {
            $data['display'] = 'standalone';
        }
        if (!isset($data['icons']) || !is_array($data['icons'])) {
            $data['icons'] = [
                [
                    'src' => '/favicon/web-app-manifest-192x192.png',
                    'sizes' => '192x192',
                    'type' => 'image/png',
                    'purpose' => 'maskable',
                ],
                [
                    'src' => '/favicon/web-app-manifest-512x512.png',
                    'sizes' => '512x512',
                    'type' => 'image/png',
                    'purpose' => 'maskable',
                ],
            ];
        }

        $encoded = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        if (is_string($encoded)) {
            file_put_contents($manifestPath, $encoded . "\n");
        }
    }
}
