<?php

namespace App\Campaigns\Creatives;

/**
 * The shapes Google's image ads come in, and what counts as one.
 *
 * One place because there were two, and they disagreed. GooglePublisher sorts
 * the attached creatives by ratio and accepts anything above Google's stated
 * minimum - 1.91:1 at 600x314, 1:1 at 300x300 - while the publish gate asked
 * for exactly 1200x628 and exactly 1200x1200, which are Google's
 * recommendations and not its requirements.
 *
 * So the gate refused campaigns the publisher would have published and Google
 * does accept: confirmed by publishing one to 346-085-5874 with a 1920x1005
 * and a 500x500, which the gate reported as "needs a creative at 1200x628" and
 * Google created as a RESPONSIVE_DISPLAY_AD. The publisher's own docblock
 * records that the exact-size match was the earlier mistake there and that
 * fixing it was the point; the gate kept the version that was replaced.
 */
class DisplayImageShapes
{
    /**
     * Ratio, and the smallest Google will take at that ratio.
     *
     * @var array<string, array{ratio: float, min_width: int, min_height: int, label: string}>
     */
    public const SHAPES = [
        'landscape' => ['ratio' => 1.91, 'min_width' => 600, 'min_height' => 314, 'label' => '1.91:1'],
        'square' => ['ratio' => 1.0, 'min_width' => 300, 'min_height' => 300, 'label' => '1:1'],
        'portrait' => ['ratio' => 0.8, 'min_width' => 480, 'min_height' => 600, 'label' => '4:5'],
    ];

    /**
     * How far off the ratio an image may be.
     *
     * Three per cent, because a 1920x1005 is 1.910 and a 1200x628 is 1.911 and
     * both are the same shape to anyone looking at them.
     */
    public const RATIO_TOLERANCE = 0.03;

    /** Which shape these dimensions are, by ratio alone, or null for none of them. */
    public static function shapeOf(int $width, int $height): ?string
    {
        if ($width < 1 || $height < 1) {
            return null;
        }

        $ratio = $width / $height;

        foreach (self::SHAPES as $shape => $spec) {
            if (abs($ratio - $spec['ratio']) / $spec['ratio'] <= self::RATIO_TOLERANCE) {
                return $shape;
            }
        }

        return null;
    }

    /** Whether these dimensions are a usable image of that shape. */
    public static function fits(string $shape, int $width, int $height): bool
    {
        return self::shapeOf($width, $height) === $shape
            && $width >= self::SHAPES[$shape]['min_width']
            && $height >= self::SHAPES[$shape]['min_height'];
    }

    /** What to ask a buyer for, in the terms Google states it. */
    public static function describe(string $shape): string
    {
        return sprintf(
            '%s at %dx%d or larger',
            self::SHAPES[$shape]['label'],
            self::SHAPES[$shape]['min_width'],
            self::SHAPES[$shape]['min_height'],
        );
    }
}
