<?php
namespace DevOwl\SearchEnginePostType;

use WP_Error;

/**
 * Implement a quota for a given post type.
 */
class Quota {
    use UtilsProvider;

    /**
     * The post type instance.
     *
     * @var SearchEnginePostType
     */
    private $searchEnginePostType;

    /**
     * C'tor.
     *
     * @param SearchEnginePostType $searchEnginePostType
     * @codeCoverageIgnore
     */
    public function __construct($searchEnginePostType) {
        $this->searchEnginePostType = $searchEnginePostType;
    }

    /**
     * Increment the quota by `1` and return `WP_Error` if quota is exceeded.
     */
    public function incrementQuota() {
        $optionName = $this->getOptionName();
        $value = get_option($optionName, 0);
        if ($value >= $this->getSearchEnginePostType()->getArg('quota')) {
            return new WP_Error('search_engine_post_type_quota_exceeded');
        }

        return update_option($optionName, $value + 1);
    }

    /**
     * Reset the quota to `0`.
     */
    public function resetQuota() {
        update_option($this->getOptionName(), 0);
    }

    /**
     * Get the option name for the quota option in `wp_options`.
     */
    public function getOptionName() {
        return sprintf('%s-%s', SEARCH_ENGINE_PT_OPT_PREFIX, $this->getSearchEnginePostType()->getArg('name'));
    }

    /**
     * Getter.
     *
     * @codeCoverageIgnore
     */
    public function getSearchEnginePostType() {
        return $this->searchEnginePostType;
    }
}
