<?php

namespace WHOOP\Entities;

class Attribute
{
  public const QUOTE_SINGLE = "'";
  public const QUOTE_DOUBLE = '"';

  protected string $key;
  protected mixed $value;
  protected ?string $quote;

  public function __construct(string $key, mixed $value, ?string $quote = null) {
    $this->key = $key;
    $this->value = $value;
    $this->quote = $quote;
  }

  public function setValue(mixed $value): self
  {
    $this->value = $value;

    return $this;
  }

  public function getValue(): mixed
  {
    return $this->value;
  }

  public function __toString(): string
  {
    $value = $this->value;
    $quote = $this->quote;

    if (is_array($value)) {
      $value = json_encode($value);
      $quote = $quote ?? self::QUOTE_SINGLE;
    }

    if (is_null($value)) {
      return $this->key;
    }

    if (is_null($quote)) {
      $quote = self::QUOTE_DOUBLE;
    }

    return $this->key . '=' . $quote . esc_attr($value) . $quote;
  }
}
