<?php

declare(strict_types=1);

$source = $argv[1] ?? '';
$target = __DIR__ . '/../assets/img/karvi-solutions-invoice.png';

if ($source === '' || !is_file($source)) {
    fwrite(STDERR, "Usage: php extract_invoice_logo.php <screenshot.png>\n");
    exit(1);
}

if (!function_exists('imagecreatefrompng')) {
    fwrite(STDERR, "GD extension required.\n");
    exit(1);
}

$info = getimagesize($source);
if ($info === false) {
    fwrite(STDERR, "Invalid image.\n");
    exit(1);
}

[$width, $height] = $info;
$image = imagecreatefrompng($source);
if ($image === false) {
    fwrite(STDERR, "Could not load image.\n");
    exit(1);
}

$pageHeight = (int) round($height / 2);
$crop = [
    'x' => max(0, (int) round($width * 0.48)),
    'y' => max(0, (int) round($pageHeight * 0.04)),
    'width' => min($width, (int) round($width * 0.5)),
    'height' => min($pageHeight, (int) round($pageHeight * 0.14)),
];

$cropped = imagecrop($image, $crop);
if ($cropped === false) {
    fwrite(STDERR, "Crop failed.\n");
    exit(1);
}

$white = imagecolorallocate($cropped, 255, 255, 255);
for ($y = 0; $y < imagesy($cropped); $y++) {
    for ($x = 0; $x < imagesx($cropped); $x++) {
        $rgb = imagecolorat($cropped, $x, $y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;
        if ($r < 40 && $g < 40 && $b < 40) {
            imagesetpixel($cropped, $x, $y, $white);
        }
    }
}

if (!imagepng($cropped, $target)) {
    fwrite(STDERR, "Could not save logo.\n");
    exit(1);
}

echo "Saved {$target}\n";
