<?php
/**
 * EduTrack PWA Icon Generator
 *
 * Generates a branded PNG icon on the fly using PHP GD.
 * Falls back to a pure-PHP solid-colour PNG if GD is unavailable.
 *
 * Query params:
 *   size   — pixel dimensions (default 192; values: 72,96,128,144,152,192,384,512)
 *   bg     — background hex colour without # (default 2563eb = admin blue)
 *   letter — centre character (default E)
 */

// Suppress any PHP notices/warnings so they never corrupt the binary output
ini_set('display_errors', '0');
ob_start(); // capture accidental output from included files / notices

// ── Parameters ────────────────────────────────────────────────────────────
$size   = in_array((int) ($_GET['size'] ?? 192), [72, 96, 128, 144, 152, 192, 384, 512], true)
        ? (int) $_GET['size']
        : 192;

$rawBg  = preg_replace('/[^0-9a-fA-F]/', '', (string) ($_GET['bg'] ?? '2563eb'));
$rawBg  = strlen($rawBg) === 6 ? $rawBg : '2563eb';

$letter = mb_strtoupper(mb_substr(preg_replace('/[^A-Za-z]/', 'E', (string) ($_GET['letter'] ?? 'E')), 0, 1));

// ── Parse hex colour ──────────────────────────────────────────────────────
$r = (int) hexdec(substr($rawBg, 0, 2));
$g = (int) hexdec(substr($rawBg, 2, 2));
$b = (int) hexdec(substr($rawBg, 4, 2));

// ── GD availability check ─────────────────────────────────────────────────
if (!function_exists('imagecreatetruecolor')) {
    // GD not available — generate a solid-colour PNG of the correct size
    // using pure PHP (no library required) so the manifest size always matches.
    ob_end_clean();
    header('Content-Type: image/png');
    header('Cache-Control: public, max-age=3600');
    echo _buildSolidPng($size, $size, $r, $g, $b);
    exit;
}

// ── Create canvas ─────────────────────────────────────────────────────────
$img = imagecreatetruecolor($size, $size);
imagealphablending($img, true);
imagesavealpha($img, true);

// Background colour
$bgColor = imagecolorallocate($img, $r, $g, $b);
imagefill($img, 0, 0, $bgColor);

// ── Rounded corners via filled arcs at corners ────────────────────────────
$radius = (int) ($size * 0.22); // ~22% radius = iOS-style rounded square

imagefilledarc($img, $radius,         $radius,         $radius * 2, $radius * 2, 180, 270, IMG_ARC_PIE, $bgColor);
imagefilledarc($img, $size - $radius, $radius,         $radius * 2, $radius * 2, 270, 360, IMG_ARC_PIE, $bgColor);
imagefilledarc($img, $radius,         $size - $radius, $radius * 2, $radius * 2,  90, 180, IMG_ARC_PIE, $bgColor);
imagefilledarc($img, $size - $radius, $size - $radius, $radius * 2, $radius * 2,   0,  90, IMG_ARC_PIE, $bgColor);

// ── Draw a bold letter using GD built-in font ─────────────────────────────
$fontSize = 5;                              // largest built-in font
$charW    = imagefontwidth($fontSize);
$charH    = imagefontheight($fontSize);

// Scale factor to make letter fill ~55% of the icon
$scale    = max(1, (int) ($size * 0.55 / max($charW, $charH)));

// Draw char at 1× into a tiny canvas, then scale it up
$tmpChar = imagecreatetruecolor($charW, $charH);
$tmpBg   = imagecolorallocate($tmpChar, $r, $g, $b);
$tmpFg   = imagecolorallocate($tmpChar, 255, 255, 255);
imagefill($tmpChar, 0, 0, $tmpBg);
imagechar($tmpChar, $fontSize, 0, 0, $letter, $tmpFg);

$scaledW    = $charW * $scale;
$scaledH    = $charH * $scale;
$scaledChar = imagecreatetruecolor($scaledW, $scaledH);
imagefill($scaledChar, 0, 0, $bgColor);
imagecopyresized($scaledChar, $tmpChar, 0, 0, 0, 0, $scaledW, $scaledH, $charW, $charH);
imagedestroy($tmpChar);

// Centre the letter on the icon
$destX = (int) (($size - $scaledW) / 2);
$destY = (int) (($size - $scaledH) / 2);
imagecopy($img, $scaledChar, $destX, $destY, 0, 0, $scaledW, $scaledH);
imagedestroy($scaledChar);

// ── Output ────────────────────────────────────────────────────────────────
ob_end_clean(); // discard any stray output before sending binary data
header('Content-Type: image/png');
header('Cache-Control: public, max-age=31536000, immutable');
header('Vary: Accept-Encoding');
imagepng($img, null, 6);
imagedestroy($img);

// ── Pure-PHP solid-colour PNG builder (no GD needed) ─────────────────────
/**
 * Build a minimal valid PNG filled with a single RGB colour.
 * Uses RFC-compliant chunk layout: signature + IHDR + IDAT + IEND.
 */
function _buildSolidPng(int $w, int $h, int $r, int $g, int $b): string
{
    // PNG signature
    $sig = "\x89PNG\r\n\x1a\n";

    // IHDR chunk: width(4) height(4) bitDepth(1) colorType(1=RGB=2) compress(1) filter(1) interlace(1)
    $ihdrData = pack('NNCCCCCC', $w, $h, 8, 2, 0, 0, 0);
    $ihdr     = pack('N', 13) . 'IHDR' . $ihdrData . pack('N', crc32('IHDR' . $ihdrData));

    // IDAT chunk: one filter-byte (0=None) + RGB pixels per scanline, gzip-compressed
    $scanline = "\x00" . str_repeat(chr($r) . chr($g) . chr($b), $w);
    $raw      = str_repeat($scanline, $h);
    $zData    = gzcompress($raw, 6);
    $idat     = pack('N', strlen($zData)) . 'IDAT' . $zData . pack('N', crc32('IDAT' . $zData));

    // IEND chunk
    $iend = "\x00\x00\x00\x00IEND" . pack('N', crc32('IEND'));

    return $sig . $ihdr . $idat . $iend;
}
