<?php

namespace Phox\core\admin\panel\wdes_options\pages\elements;

use Phox\core\admin\panel\wdes_options\pages\elements\Abstract_Basic_Type;
use Phox\core\admin\panel\wdes_options\Panel_Controller;

class Toggle extends Abstract_Basic_Type
{

    /**
     * @param string $id Set ID
     * @param bool $value Set value
     * @param string|null $title Set name
     * @param string|null $description Set description
     */
    public function __construct(
        string $id ,
        mixed $value,
        string $title = null,
        string $description = null,
    )
    {
        $this->label($title);
        $this->description($description);
        $this->id($id);
        $this->value($value);
        $this->properties = [];
    }

    public function type(): string
    {
        return 'toggle';
    }

    public function saved_value():mixed
    {
        $option_value = Panel_Controller::getInstance()->get_db_source()->get_option($this->id);
        $value = '';
        if ( true === $option_value || 1 === $option_value || '1' === $option_value || 'true' === $option_value) {
            $value = true;
        }

        if ( false === $option_value || 0 === $option_value || '0' === $option_value || 'false' === $option_value) {
            $value = false;
        }

        return $value;

    }

    public function value($value): void
    {
        $value = ! empty( $this->saved_value() ) || is_bool($this->saved_value()) ? $this->saved_value() : $value;

        $this->values = [
            'value' => $value
        ];
    }

    public function validate_type(): string
    {
        return 'bool';
    }

}