<?php

namespace EstatebudConnect\Core;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Traits\Singleton;

class OptionsAPI
{
    private $prefix = 'estatebud_';

    use Singleton;

    public function add(string $handle, $data)
    {
        $result_flag = add_option($this->prefix . $handle, $data);
        return $result_flag;
    }

    public function get(string $handle, $default = false)
    {
        $result = get_option($this->prefix . $handle, $default);
        return $result;
    }

    public function update(string $handle, $data, $autoload = true)
    {
        $result_flag = update_option($this->prefix . $handle, $data, $autoload);
        return $result_flag;
    }

    public function delete(string $handle)
    {
        $result_flag = delete_option($this->prefix . $handle);
        return $result_flag;
    }

    public function destroy()
    {
        global $wpdb;
        $deleted = 0;

        $items = $wpdb->get_col(
            $wpdb->prepare(
                "SELECT option_name FROM {$wpdb->options}
                WHERE option_name LIKE %s",
                $this->prefix . '%',
            ),
        );

        foreach ($items as $item) {
            $options_key = str_replace('estatebud_', '', $item);
            if ($this->delete($options_key)) {
                $deleted++;
            }
        }

        return $deleted;
    }
}
