<?php

namespace SEOAIC\last_used_prompts;

abstract class AbstractLastUsedPrompts
{
    protected $prompts = [];
    protected $field = '';
    protected $settingsField = '';
    protected $count = 3;

    public function __construct()
    {
        global $SEOAIC_OPTIONS;

        if (
            !empty($this->settingsField)
            && isset($SEOAIC_OPTIONS[$this->settingsField])
        ) {
            $this->count = intval($SEOAIC_OPTIONS[$this->settingsField]);
        }

        $this->prompts = $this->getAll();
    }

    public function getCount()
    {
        return $this->count;
    }

    public function getSettingsCountField(): string
    {
        return $this->settingsField;
    }

    public function getAll(): array
    {
        global $SEOAIC_OPTIONS;

        $prompts = !empty($this->prompts) ? $this->prompts : ($SEOAIC_OPTIONS['last_used_prompts'][$this->field] ?? []);
        $prompts = array_map(function ($prompt) {
            return stripslashes($prompt);
        }, $prompts);

        return $prompts;
    }

    public function store($prompt = ''): void
    {
        $prompt = stripslashes($prompt);

        if (
            !empty($prompt)
            && !in_array($prompt, array_values($this->prompts))
        ) {
            $id = 'lp-' . rand(1000, 5000);
            $this->prompts = array_reverse($this->prompts);
            $this->prompts[$id] = strip_tags($prompt, '<a>');
            $this->prompts = array_reverse($this->prompts);

            if (count($this->prompts) > $this->count) {
                $this->prompts = array_slice($this->prompts, 0, $this->count);
            }

            $this->save();
        }
    }

    public function delete($id)
    {
        if (isset($this->prompts[$id])) {
            unset($this->prompts[$id]);
            $this->prompts = array_values($this->prompts);

            $this->save();
        }
    }

    private function save()
    {
        global $SEOAIC_OPTIONS;

        if (!isset($SEOAIC_OPTIONS['last_used_prompts'][$this->field])) {
            $SEOAIC_OPTIONS['last_used_prompts'][$this->field] = [];
        }

        $SEOAIC_OPTIONS['last_used_prompts'][$this->field] = $this->prompts;

        update_option('seoaic_options', $SEOAIC_OPTIONS);
    }
}
