<?php

namespace kernel\app_modules\card\services;

use DragonCode\CardNumber\CardNumber;
use DragonCode\CardNumber\Factories\BankFactory;
use DragonCode\CardNumber\Formatters\BankFormatter;
use kernel\app_modules\card\models\Card;
use kernel\app_modules\card\models\CardFile;
use kernel\FormModel;
use kernel\helpers\ImageGD;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\RoundBlockSizeMode;
use Endroid\QrCode\Writer\PngWriter;

class CardFileService
{

    public function create(Card $card): false|CardFile
    {
        $cardFile = self::createCardPNG($card);

        $model = new CardFile();
        // Пример заполнения:
        $model->file = $cardFile;
        $model->status = CardFile::ACTIVE_STATUS;
        $model->card_id = $card->id;
        // $model->slug = Slug::createSlug($form_model->getItem('title'), Card::class); // Генерация уникального slug

        if ($model->save()) {
            return $model;
        }

        return false;
    }

    public function update(FormModel $form_model, CardFile $cardTemplate): false|CardFile
    {
        // Пример обновления:
        $cardTemplate->file = $form_model->getItem('file');
        $cardTemplate->card_id = $form_model->getItem('card_id');
        $cardTemplate->status = $form_model->getItem('status');

        if ($cardTemplate->save()) {
            return $cardTemplate;
        }

        return false;
    }

    public static function createCardPNG(Card $card): false|string
    {
        if ($card->cardTemplate) {
            $formatter = BankFormatter::create();

            $customer = BankFactory::create()->paymentType($card->payment_type)->bank($card->bank_id, $card->info, $card->program)->client($card->id);

            $cardNumber = CardNumber::generate($customer, $formatter);
            //Card
            $newFileName = md5(time() . $card->id) . '.png';
            $uploadDir = "/resources/cards/";
            $uploadDirUri = $uploadDir . mb_substr($newFileName, 0, 2) . '/' . mb_substr($newFileName, 2, 2) . '/';
            $oldMask = umask(0);
            mkdir(ROOT_DIR . $uploadDirUri, 0775, true);
            umask($oldMask);
            $uploadFileDir = ROOT_DIR . $uploadDirUri;

            $img = ROOT_DIR . "/" . $card->cardTemplate->path; // Ссылка на файл
            $font = RESOURCES_DIR . "/arialmt.ttf"; // Ссылка на шрифт

            $qr = self::createQr($card->id);
            $qrImg = new ImageGD($qr->getDataUri());
            $img = new ImageGD($img);

            $pngFilePath = RESOURCES_DIR . "/tmp/" . $card->id . ".png";
            $pngFileUrl = "/resources/tmp/" . $card->id . ".png";

            $img->addText(font_size: 14, degree: 0, x: 15, y: 25, color: "#000000", font: $font, text: "KO coin");
            $img->addText(font_size: 14, degree: 0, x: 15, y: 45, color: "#000000", font: $font, text: "BGroup\ITGuild");
            $img->addText(font_size: 14, degree: 0, x: 15, y: 65, color: "#000000", font: $font, text: $card->cardTemplate->title . " card");
            $img->addText(font_size: 18, degree: 0, x: 15, y: 180, color: "#000000", font: $font, text: $cardNumber);
            $img->addText(font_size: 12, degree: 0, x: 15, y: 200, color: "#000000", font: $font, text: $card->username);
            $img->addImg($qrImg->getImg(), 200, 15, 0, 0, 124, 124, 100);
            $img->save($uploadFileDir . $newFileName);

            return $uploadDirUri . $newFileName;
        }

        return false;
    }

    public static function createQr(string|int $text): \Endroid\QrCode\Writer\Result\ResultInterface
    {
        $writer = new PngWriter();

        $qrCode = new QrCode(
            data: $text,
            encoding: new Encoding('UTF-8'),
            errorCorrectionLevel: ErrorCorrectionLevel::Low,
            size: 120,
            margin: 2,
            roundBlockSizeMode: RoundBlockSizeMode::Margin,
            foregroundColor: new Color(0, 0, 0),
            backgroundColor: new Color(255, 255, 255)
        );

        return $writer->write($qrCode);
    }

}