<?php

declare(strict_types=1);

namespace Cin\Quickpurchase\classes;

use ReturnTypeWillChange;

/**
 * @property string condition
 * @property int quantity
 * @property string cName
 * @property string cArtNr
 * @property string cHAN
 * @property int kArtikel
 * @property string fVKBrutto
 * @property string fVKNetto
 * @property string custom_description
 * @property float fLagerbestand
 * @property float mindestbestand
 * @property int direct_purchase
 * @property int condition_history_id
 * @property int queue_id
 * @property string previewImage
 */
final class PurchaseArticle
{
  private object $j;

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

  #[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 hasMinOrderQuantity(): bool
  {
    return 0 < $this->mindestbestand;
  }

  public function isInStock(): bool
  {
    return 0 < $this->fLagerbestand;
  }

  /**
   * Foreach the stringified session storage as PurchaseArticle array.
   *
   * @param string[]                                             $purchaseArticles Json Strings presenting a PurchaseArticle
   * @param callable(PurchaseArticle $pArticle, int $index):void $callback
   */
  public static function foreach(array $purchaseArticles, callable $callback): void
  {
    foreach ($purchaseArticles as $idx => $articleJson) {
      $pArticle = new self($articleJson);
      $callback($pArticle, $idx);
    }
  }

  /**
   * Get the stringified session storage as object (PurchaseArticle) storage.
   */
  public static function storage(): array
  {
    $storage = [];
    self::foreach($_SESSION['cin_ankauf_storage'], static function ($pArticle) use (&$storage): void {
      $storage[] = $pArticle;
    });

    return $storage;
  }
}
