<?php
require __DIR__ . '/bootstrap.php';

$size = (int)($_GET['size'] ?? 192);
if (!in_array($size, [192, 512], true)) {
    $size = 192;
}
$maskable = !empty($_GET['maskable']);

$settings = Settings::safeAll();
$logoPath = trim($settings['logo_path'] ?? '');
$defaultIcon = __DIR__ . '/assets/icons/' . ($size === 512 ? ($maskable ? 'maskable-512.png' : 'icon-512.png') : 'icon-192.png');

if (!function_exists('imagecreatetruecolor')) {
    if (is_file($defaultIcon)) {
        header('Content-Type: image/png');
        header('Cache-Control: public, max-age=3600');
        readfile($defaultIcon);
        exit;
    }
    http_response_code(404);
    exit;
}

$sourcePath = '';
if ($logoPath !== '') {
    $candidate = __DIR__ . '/' . ltrim($logoPath, '/');
    if (is_file($candidate)) {
        $sourcePath = $candidate;
    }
}
if ($sourcePath === '' && is_file($defaultIcon)) {
    $sourcePath = $defaultIcon;
}
if ($sourcePath === '') {
    http_response_code(404);
    exit;
}

$info = @getimagesize($sourcePath);
$mime = $info['mime'] ?? '';
$src = null;
switch ($mime) {
    case 'image/png':
        $src = @imagecreatefrompng($sourcePath);
        break;
    case 'image/jpeg':
        $src = @imagecreatefromjpeg($sourcePath);
        break;
    case 'image/webp':
        if (function_exists('imagecreatefromwebp')) {
            $src = @imagecreatefromwebp($sourcePath);
        }
        break;
    case 'image/gif':
        $src = @imagecreatefromgif($sourcePath);
        break;
}
if (!$src) {
    header('Content-Type: image/png');
    header('Cache-Control: public, max-age=3600');
    readfile($defaultIcon);
    exit;
}

$canvas = imagecreatetruecolor($size, $size);
imagesavealpha($canvas, true);
$transparent = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
imagefill($canvas, 0, 0, $transparent);

// Fundo amarelo/verde combinando com o CFC, para ícone ficar bonito mesmo com logos transparentes.
$yellow = imagecolorallocate($canvas, 241, 196, 15);
$green = imagecolorallocate($canvas, 0, 141, 52);
$white = imagecolorallocate($canvas, 255, 255, 255);
imagefilledellipse($canvas, (int)($size/2), (int)($size/2), (int)($size*0.96), (int)($size*0.96), $green);
imagefilledellipse($canvas, (int)($size/2), (int)($size/2), (int)($size*0.84), (int)($size*0.84), $yellow);
if ($maskable) {
    imagefilledellipse($canvas, (int)($size/2), (int)($size/2), (int)($size*0.74), (int)($size*0.74), $white);
}

$srcW = imagesx($src);
$srcH = imagesy($src);
$max = (int)($size * ($maskable ? 0.62 : 0.72));
$ratio = min($max / max(1, $srcW), $max / max(1, $srcH));
$dstW = max(1, (int)round($srcW * $ratio));
$dstH = max(1, (int)round($srcH * $ratio));
$dstX = (int)(($size - $dstW) / 2);
$dstY = (int)(($size - $dstH) / 2);
imagecopyresampled($canvas, $src, $dstX, $dstY, 0, 0, $dstW, $dstH, $srcW, $srcH);

header('Content-Type: image/png');
header('Cache-Control: public, max-age=3600');
imagepng($canvas);
imagedestroy($canvas);
imagedestroy($src);
