<?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\pages\elements\actions\Abstract_Action;

class Button extends Abstract_Basic_Type
{
    /**
     * Action
     *
     * @var string $action Set callback function to can use from frontend
     */
    private string $action;

    /**
     * Status
     *
     * @var bool $status If button is enable or disable
     */
    private bool $status;

    /**
     * Action Class
     *
     * @var Abstract_Action $action_class Set class that will fire
     */
    private Abstract_Action $action_class;

    const WDES_BUTTON_ACTIONS_DIR = __DIR__ . '/actions/';

    /**
     * @param string $id Set ID
     * @param string $action Set value
     * @param Abstract_Action $action_class
     * @param string|null $title Set title
     * @param string|null $description Set description
     */
    public function __construct(
        string $id ,
        string $action,
        Abstract_Action $action_class,
        string $title = null,
        string $description = null,
    )
    {
        $this->label($title);
        $this->description($description);
        $this->id($id);
        $this->action($action);
        $this->action_class = $action_class;
        $this->values = [];
        $this->properties = [];

        $this->register_actions($this->action);
    }

    public function default(): void
    {
        $default_values = [
            'id' => 'button-id',
            'title' => 'button',
            'description' => 'Description',
            'type' => $this->type(),
            'action' => '',
        ];

        if(isset($this->properties['status'])) $default_values['status'] = $this->status;

        $this->properties = array_merge($default_values, [
            'id' => $this->id,
            'title' => $this->title,
            'description' => $this->description,
            'action' => $this->action
        ]);
    }

    private function action(string $action): void
    {
        $this->action = $action;
    }

    public function value($value): void
    {
        $this->values = [];
    }

    public function get_prepared_save_values()
    {
        return [];
    }

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

    public function set_status(bool $status): void
    {
        $this->properties['status'] = false;

        $this->status = $status;
    }

    public function validate_values():Element_Validator
    {
        return Element_Validator::getInstance();

    }

    public function register_actions($callback){

        if( ! is_string($callback) ) return false;

        if ( defined( 'DOING_AJAX' ) && DOING_AJAX && defined('WDES_PANEL_BUTTON_ACTION') && $callback === WDES_PANEL_BUTTON_ACTION ) {

            $this->action_class->call();

        }
       return true;
    }

}