<?php
declare(strict_types=1);

/**
 * Optimize image: resize to max width and re-encode to JPEG quality 85.
 * Keeps PNG only if source is PNG with transparency; otherwise JPEG.
 */
function optimize_image(string $sourcePath, string $destPath, int $maxWidth = 1600): array {
  $info = @getimagesize($sourcePath);
  if (!$info) throw new RuntimeException("Not an image.");

  $mime = $info['mime'] ?? '';
  if (!in_array($mime, ['image/jpeg','image/png'], true)) {
    throw new RuntimeException("Unsupported image mime.");
  }

  if ($mime === 'image/jpeg') {
    $img = imagecreatefromjpeg($sourcePath);
    $hasAlpha = false;
  } else {
    $img = imagecreatefrompng($sourcePath);
    $hasAlpha = true;
  }

  $w = imagesx($img);
  $h = imagesy($img);

  $newW = $w;
  $newH = $h;

  if ($w > $maxWidth) {
    $ratio = $maxWidth / $w;
    $newW = $maxWidth;
    $newH = (int)round($h * $ratio);
  }

  if ($newW !== $w) {
    $newImg = imagecreatetruecolor($newW, $newH);
    if ($hasAlpha) {
      imagealphablending($newImg, false);
      imagesavealpha($newImg, true);
      $transparent = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
      imagefilledrectangle($newImg, 0, 0, $newW, $newH, $transparent);
    }
    imagecopyresampled($newImg, $img, 0,0,0,0, $newW,$newH, $w,$h);
    imagedestroy($img);
    $img = $newImg;
  }

  // If alpha exists, save PNG; else JPEG
  if ($hasAlpha) {
    imagepng($img, $destPath, 6);
    $outMime = 'image/png';
  } else {
    imagejpeg($img, $destPath, 85);
    $outMime = 'image/jpeg';
  }

  imagedestroy($img);

  return ['mime' => $outMime];
}
