<?php
/*
 * Copyright (c) 2023. RTM Business
 */

namespace WordpressModels\ORM\Entity;

use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

/**
 * AbstractMeta class.
 *
 * Offers base properties for meta entities.
 */
#[ORM\Index(name: 'meta_key', columns: ['meta_key'])]
abstract class AbstractMeta
{

    #[ORM\Column(name: 'meta_id', type: Types::BIGINT, options: ['unsigned' => true])]
    #[ORM\Id]
    #[ORM\GeneratedValue(strategy: 'IDENTITY')]
    protected ?int $id = null;

    /**
     * @var string|null
     */
    #[ORM\Column(name: 'meta_key', type: Types::STRING, length: 255, nullable: true)]
    protected ?string $key = null;

    /**
     * @var string|null
     */
    #[ORM\Column(name: 'meta_value', type: Types::TEXT, length: 0, nullable: true)]
    protected ?string $value = null;


    public function getId(): ?int
    {
        return $this->id;
    }

    public function setId(?int $id): self
    {
        $this->id = $id;
        return $this;
    }

    public function getKey(): ?string
    {
        return $this->key;
    }

    public function setKey(?string $key): self
    {
        $this->key = $key;
        return $this;
    }

    /**
     * @return string|null
     */
    public function getValue(): ?string
    {
        return $this->value;
    }

    /**
     * Check the serialization (json or php) of the current value, and return the deserialized value.
     *
     * @return mixed
     */
    public function getValueDeserialized(): mixed
    {
        if (is_json($this->value)) {
            return json_decode($this->value);
        } elseif (is_serialized($this->value)) {
            return unserialize($this->value);
        }

        return $this->value;
    }

    /**
     * Check the serialization (json or php) of the current value, and replicate with the new value.
     *
     * If the current value is not serialized, the new value will be set as is.
     * If the current value is serialized and the given value is also serialized, the new value will be set as is.
     *
     * If the given value is an array or an object, it will always be serialized as php.
     *
     * @param mixed $value
     * @return $this
     */
    public function setValue(mixed $value): self
    {
        if (is_json($this->value) && !is_json($value)) {
            $this->value = json_encode($value);
        } elseif ((is_serialized($this->value) && !is_serialized($value))
            || is_array($value) || is_object($value)) {
            $this->value = serialize(is_object($value) ? (array)$value : $value);
        } else {
            $this->value = $value;
        }

        return $this;
    }
}