<?php

declare(strict_types=1);

namespace Cin\Quickpurchase\classes;

use JTL\Catalog\Product\Artikel;
use ReturnTypeWillChange;
use stdClass;

/**
 * @property int id
 * @property int kKunde
 * @property string cMail
 * @property int kArtikel
 * @property string cArtNr
 * @property int quantity Is the quantity from customers offer
 * @property int condition_history_id
 * @property string custom_description
 * @property HistoryCondition historyCondition
 * @property Artikel shop_article
 * @property int quantity_offer Is the quantity from sellers offer
 */
final class QueueItem
{
  private object $j;

  public function __construct(stdClass $instance)
  {
    // $this->j = json_decode($json);
    $this->j = $instance;
  }

  #[ReturnTypeWillChange]
  public function __get($member)//: mixed
  {
    return $this->j->{$member} ?? null;
  }

  public function __set($name, $value): void
  {
    $this->j->{$name} = $value;
  }

  public function __toSimpleObject(): object
  {
    return $this->j;
  }

  public function __toString()
  {
    return json_encode($this->j, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_UNICODE);
  }

  public function __serialize()
  {
    return serialize($this->j);
  }

  public function __unserialize($data): void
  {
    $this->j = unserialize($data);
  }

  public function ToPurchaseArticle(bool $useSellerQuantity = true, bool $directPurchase = false): PurchaseArticle
  {
    $article = json_decode(json_encode((new Artikel())->fuelleArtikel($this->kArtikel)));

    $article->kArtikel  = $article->kArtikel;
    $article->cArtNr    = $article->cArtNr;
    $article->cHAN      = $article->cHAN;
    $article->cName     = $article->cName;
    $article->fVKNetto  = $article->Preise->fVKNetto;
    $article->fVKBrutto = $article->Preise->fVKBrutto;

    $article->custom_description = $this->custom_description;
    $article->quantity           = ($useSellerQuantity ? $this->quantity_offer : $this->quantity);
    $article->direct_purchase    = (int) $directPurchase;

    return new PurchaseArticle(json_encode($article));
  }
}
