<?php
namespace Wpupgrader\WordPress\Plugins\GdprConsentLite;

class Consents
{
    /** @var array $consents Cached Consents */
    public $consents;
    /** @var int $offset Cached offset */
    protected $offset = 0;

    public function getAll()
    {
        if ($this->consents === null) {
            $args = [
                'post_status'      => 'publish',
                'post_type'        => 'gdprc_consent',
                'numberposts'      => -1,
                'posts_per_page'   => -1,
                'suppress_filters' => 0,
            ];
            $consents = \get_posts($args);
            $this->consents = [];
            $this->offset = 0;
            foreach ($consents as $consent) {
                $this->addConsentToArray($this->consents, $consent);
            }
        }
        \ksort($this->consents, SORT_NUMERIC);
        return $this->consents;
    }

    public function getByIds(array $ids)
    {
        $args = [
            'post__in'         => $ids,
            'post_status'      => 'publish',
            'post_type'        => 'gdprc_consent',
            'numberposts'      => -1,
            'posts_per_page'   => -1,
            'suppress_filters' => 0,
        ];
        $consents = \get_posts($args);
        $result = [];
        $this->offset = 0;
        foreach ($consents as $consent) {
            $this->addConsentToArray($result, $consent);
        }
        \ksort($result, SORT_NUMERIC);
        return $result;
    }

    /**
     * Internal function to get the Consent
     *
     * @param array $array
     * @param $consent
     */
    protected function addConsentToArray(array &$array, $consent)
    {
        $order = (int)\get_post_meta($consent->ID, 'gdprc_consent_sortorder', true);
        while (isset($array[$order + $this->offset])) {
            $this->offset++;
        }
        $consent->order = $order + $this->offset;
        $array[$consent->order] = new Consent($consent);
    }
}