<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

/**
 * Generates PNG icons required for PWA installation on Android/Chrome.
 * SVG icons work on modern desktop browsers but many mobile browsers
 * (especially Android Chrome) require raster PNG icons for install prompts.
 *
 * Usage:  php artisan pwa:icons
 *
 * Outputs:
 *   public/icons/icon-192.png      — standard home-screen icon
 *   public/icons/icon-512.png      — splash-screen icon
 *   public/icons/icon-maskable.png — maskable (safe-zone) icon for adaptive launchers
 */
class GeneratePwaIcons extends Command
{
    protected $signature   = 'pwa:icons';
    protected $description = 'Generate 192×192 and 512×512 PNG icons for PWA installation';

    public function handle(): int
    {
        if (! extension_loaded('gd')) {
            $this->error('The GD extension is not loaded. Enable php_gd in php.ini and try again.');
            return self::FAILURE;
        }

        $dir = public_path('icons');
        if (! is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        $this->generateIcon($dir . '/icon-192.png', 192);
        $this->generateIcon($dir . '/icon-512.png', 512);
        $this->generateMaskable($dir . '/icon-maskable.png', 512);

        $this->info('PWA icons generated:');
        $this->line('  public/icons/icon-192.png');
        $this->line('  public/icons/icon-512.png');
        $this->line('  public/icons/icon-maskable.png');

        return self::SUCCESS;
    }

    /**
     * Draw a simple bar-chart icon with an indigo palette on a dark navy background.
     */
    private function generateIcon(string $path, int $size): void
    {
        $img = imagecreatetruecolor($size, $size);
        imagesavealpha($img, true);

        // Background: #0f172a (dark navy)
        $bg = imagecolorallocate($img, 15, 23, 42);
        imagefill($img, 0, 0, $bg);

        // Rounded-rectangle background simulation (four arcs at corners)
        $radius = (int)($size * 0.18);
        $this->drawRoundedRect($img, 0, 0, $size - 1, $size - 1, $radius, $bg);

        // Bar chart — 4 bars in indigo shades
        $barColors = [
            imagecolorallocate($img, 99,  102, 241),  // indigo-500
            imagecolorallocate($img, 129, 140, 248),  // indigo-400
            imagecolorallocate($img, 79,  70,  229),  // indigo-600
            imagecolorallocate($img, 139, 92,  246),  // violet-500
        ];

        $unit       = $size / 10;
        $barWidth   = (int)($unit * 1.2);
        $baseY      = (int)($size * 0.78);
        $startX     = (int)($size * 0.18);
        $gap        = (int)(($size * 0.64 - $barWidth * 4) / 3);
        $heights    = [0.38, 0.55, 0.42, 0.62]; // fraction of usable height
        $maxBarH    = (int)($size * 0.55);

        foreach ($heights as $i => $fraction) {
            $barH = (int)($maxBarH * $fraction);
            $x1   = $startX + $i * ($barWidth + $gap);
            $x2   = $x1 + $barWidth;
            $y1   = $baseY - $barH;
            imagefilledrectangle($img, $x1, $y1, $x2, $baseY, $barColors[$i]);
        }

        // Trend line (white) connecting bar tops
        $white = imagecolorallocate($img, 255, 255, 255);
        $points = [];
        foreach ($heights as $i => $fraction) {
            $barH      = (int)($maxBarH * $fraction);
            $cx        = $startX + $i * ($barWidth + $gap) + (int)($barWidth / 2);
            $cy        = $baseY - $barH;
            $points[]  = [$cx, $cy];
        }
        for ($i = 0; $i < count($points) - 1; $i++) {
            $this->drawThickLine($img, $points[$i][0], $points[$i][1],
                                       $points[$i + 1][0], $points[$i + 1][1],
                                       $white, max(1, (int)($size * 0.018)));
        }

        // Dots on trend line
        foreach ($points as [$cx, $cy]) {
            $dotR = max(2, (int)($size * 0.032));
            imagefilledellipse($img, $cx, $cy, $dotR * 2, $dotR * 2, $white);
        }

        imagepng($img, $path);
        imagedestroy($img);
    }

    /**
     * Maskable icon — same art but with guaranteed safe zone (80% of icon).
     * The safe zone is the central 80%, so we scale the art down a bit.
     */
    private function generateMaskable(string $path, int $size): void
    {
        // Generate the art into a temp image at safe-zone size
        $inner = (int)($size * 0.8);
        $tmp   = tempnam(sys_get_temp_dir(), 'pwa_icon_') . '.png';
        $this->generateIcon($tmp, $inner);

        // Compose onto a full-bleed background
        $img = imagecreatetruecolor($size, $size);
        $bg  = imagecolorallocate($img, 15, 23, 42);
        imagefill($img, 0, 0, $bg);

        $src    = imagecreatefrompng($tmp);
        $offset = (int)(($size - $inner) / 2);
        imagecopy($img, $src, $offset, $offset, 0, 0, $inner, $inner);

        imagepng($img, $path);
        imagedestroy($img);
        imagedestroy($src);
        unlink($tmp);
    }

    private function drawRoundedRect($img, int $x1, int $y1, int $x2, int $y2, int $r, $color): void
    {
        imagefilledrectangle($img, $x1 + $r, $y1,      $x2 - $r, $y2,      $color);
        imagefilledrectangle($img, $x1,      $y1 + $r, $x2,      $y2 - $r, $color);
        imagefilledellipse($img, $x1 + $r, $y1 + $r, $r * 2, $r * 2, $color);
        imagefilledellipse($img, $x2 - $r, $y1 + $r, $r * 2, $r * 2, $color);
        imagefilledellipse($img, $x1 + $r, $y2 - $r, $r * 2, $r * 2, $color);
        imagefilledellipse($img, $x2 - $r, $y2 - $r, $r * 2, $r * 2, $color);
    }

    private function drawThickLine($img, int $x1, int $y1, int $x2, int $y2, $color, int $thickness): void
    {
        imagesetthickness($img, $thickness);
        imageline($img, $x1, $y1, $x2, $y2, $color);
        imagesetthickness($img, 1);
    }
}
