<?php

namespace MintyPHP\Service\Tenant;

use MintyPHP\Service\Image\ImageUploadTrait;

class TenantFaviconService
{
    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 isValidUuid(string $uuid): bool
    {
        return self::imageIsValidUuid($uuid);
    }

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

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

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

    public function hasFavicon(string $uuid): bool
    {
        if (!$this->isValidUuid($uuid)) {
            return false;
        }
        $path = $this->publicDir($uuid) . '/favicon-32x32.png';
        return @is_file($path);
    }

    public function delete(string $uuid): void
    {
        if (!$this->isValidUuid($uuid)) {
            return;
        }
        foreach ($this->storageDirs($uuid) as $dir) {
            if (!is_dir($dir)) {
                continue;
            }
            $matches = glob($dir . '/*') ?: [];
            foreach ($matches as $file) {
                if (is_file($file)) {
                    @unlink($file);
                }
            }
        }
        $public = $this->publicDir($uuid);
        foreach (self::SIZES as $file) {
            $target = $public . '/' . $file;
            if (is_file($target)) {
                @unlink($target);
            }
        }
    }

    public function saveUpload(string $uuid, array $file): array
    {
        if (!$this->isValidUuid($uuid)) {
            return ['ok' => false, 'error' => t('Tenant not found')];
        }
        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($uuid);
        if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
            return ['ok' => false, 'error' => t('Upload failed')];
        }

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

        $publicDir = $this->publicDir($uuid);
        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);
        }

        return ['ok' => true, 'path' => $originalPath, 'mime' => $mime];
    }

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

    private function storageDirs(string $uuid): array
    {
        $dirs = [$this->storageDir($uuid)];
        $legacy = $this->legacyStorageDir($uuid);
        if ($legacy !== $dirs[0]) {
            $dirs[] = $legacy;
        }
        return $dirs;
    }

    private function legacyStorageDir(string $uuid): string
    {
        return $this->storageBase() . '/branding/tenants/' . $uuid . '/favicon';
    }
}
