<?php

namespace App\Application\Admin;

use App\Domain\Media\Image;
use App\Domain\Media\ImageRepository;
use App\Domain\Media\ImageResizer;
use App\Domain\Media\ImageVariantRepository;
use App\Domain\Media\SaveImageFile;
use App\Framework\Attributes\Route;
use App\Framework\Auth\Auth;
use App\Framework\Core\PathProvider;
use App\Framework\Database\Transaction;
use App\Framework\DateTime\SystemClock;
use App\Framework\Http\Method;
use App\Framework\Http\Request;
use App\Framework\Http\UploadedFile;
use App\Framework\Ulid\StringConverter;
use App\Framework\Ulid\Ulid;
use Media\Services\ImageService;
use function imagecopyresampled;
use function imagecreatefromjpeg;
use function imagecreatetruecolor;
use function imagedestroy;
use function imagejpeg;

class ShowImageUpload
{
    public function __construct(
        private PathProvider $pathProvider,
        private StringConverter $stringConverter,
    ) {}

    #[Auth]
    #[Route('/upload')]
    public function __invoke()
    {
        $html = <<<HTML
        <form action="/upload" method="post" enctype="multipart/form-data">
            <label for="image">Bild hochladen:</label>
            <input type="file" id="image" name="image" accept="image/*" required/>
            <input type="submit" value="Upload" />
        </form>

        HTML;

        echo $html;
        die();
    }
    #[Auth]
    #[Route('/upload', Method::POST)]
    public function upload(Request $request, Ulid $ulid, ImageRepository $imageRepository, ImageVariantRepository $imageVariantRepository,)
    {
        try {
            /** @var UploadedFile $file */
            $file = $request->files->get('image');


            $storageFolder = $this->pathProvider->resolvePath('/storage');

            // Todo: Use Clock instead of date();
            $uploadDirectory = sprintf('uploads/%s/%s/%s', date('Y'), date('m'), date('d'));

            $ulid = (string)$ulid; //$this->stringConverter->encodeBase32($ulid);

            $id = $ulid;

            // Remove Timestamp
            $id = substr($id, 10);

            $hash = hash_file('sha256', $file->tmpName);

            // Prüfen, ob ein Bild mit diesem Hash bereits existiert
            $existingImage = $imageRepository->findByHash($hash);
            if ($existingImage !== null) {
                echo "<h2>Bild bereits vorhanden</h2>";
                echo "<p>Dieses Bild wurde bereits hochgeladen.</p>";
                echo "<p>Bild-ID: " . htmlspecialchars($existingImage->ulid) . "</p>";
                return;
            }

            $idStr = str_pad((string)$id, 9, '0', STR_PAD_LEFT);
            $filePathPattern = sprintf('%s/%s/%s',
                substr($idStr, 0, 3),
                substr($idStr, 3, 3),
                substr($idStr, 6, 3),
            );

            $path = $storageFolder . '/' . $uploadDirectory . '/' . $filePathPattern . "/";

            $filename = $idStr . '_' . $hash . "_";

            #dd($path . $filename . 'variant.png');

            $smallPath = $path . $filename . 'small.png';




            [$width, $height] = getimagesize($file->tmpName);



            $image = new Image(
                ulid            : $ulid,
                filename        : $filename . 'original.jpg',
                originalFilename: $file->name,
                mimeType        : $file->getMimeType(),
                fileSize        : $file->size,
                width           : $width,
                height          : $height,
                hash            : $hash,
                path            : $path,
                altText         : 'Some alt text',
            );



            $imageRepository->save($image, $file->tmpName);



            #$image = $imageRepository->findById("0197B2CD759501F08D60312AE62ACCFC");

            #mkdir($path, 0755, true);
            $variant = new ImageResizer()($image, 50, 50);

            $imageVariantRepository->save($variant);;

            $href = "/images/".$variant->filename;
            echo "<a href='$href'>$href</a>";


            #new SaveImageFile()($image, $file->tmpName);;
            debug($variant->filename);
            dd($image);



        } catch (\Exception $e) {
            echo "<h2>Fehler beim Upload:</h2>";
            echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
            debug($e);
        }
    }
}
