<?php

namespace CouponsPlus\App\Data\Store;

use WP_Post;
use CouponsPlus\Original\Environment\Env;
use CouponsPlus\App\Data\Store\Abilities\Deletable;

#[\AllowDynamicProperties]
Class SimpleKeyStorer extends PostStorer implements Deletable
{

    protected string $key;
    protected bool $deleteWhenEmpty;

    public static function create(string $key, WP_Post $post, bool $deleteWhenEmpty = false) : SimpleKeyStorer
    {
        $instance = new static($post);

        $instance->setKey($key);
        $instance->deleteWhenEmpty = $deleteWhenEmpty;

        return $instance;
    }

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

    /**
     * Prefixed eg: 'couponsplus_grove'
     */
    protected function getKey(): string
    {
        return Env::getWithPrefix($this->key);
    }

    protected function getPostFieldName() : string
    {
        return $this->getKey();
    }

    protected function storeData()
    {
        $this->updateMeta(
            $this->getKey(),
            $this->getData()
        );
    }

    public function canBeDeleted(): bool
    {
        // the main validation failed so let's see if we can delete this
        return $this->getData() === '' && $this->deleteWhenEmpty;
    }

    public function delete(): void
    {
        $this->deleteMeta($this->getKey());
    }
}