<?php

namespace onespace\tools\widgets\input;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\InputWidget;

/**
 * Draw a Toggle Switch checkbox input element.
 * 
 * @author Gareth Palmer <gareth@one-space.co.za>
 */

final class Switcher extends InputWidget {

    /**
     * ## OPTIONAL
     * 
     * Set a left hand label next to the toggle.
     *
     * @var string  $leftLabel
     * 
     * @access  public
     */

    public string $leftLabel;

    /**
     * ## OPTIONAL
     * 
     * Set a left hand label next to the toggle.
     *
     * @var string  $rightLabel
     * 
     * @access  public
     */

    public string $rightLabel;

    /**
     * ## OPTIONAL
     * 
     * Whether the switch should be on by default. Ignored if a model is passed.
     * 
     * @var bool    $checked    Default: false
     * 
     * @access  public
     */

    public bool $checked = false;


    /**
     * {@inheritdoc}
     *
     * @return void
     * 
     * @access  public
     */

    public function init(): void {
        parent::init();
        $this->options = ArrayHelper::merge($this->options, ['data-type' => 'ui-switcher']);
        $this->options['id'] ??= 'sw' . Yii::$app->security->generateRandomString(8);
    }


    /**
     * {@inheritdoc}
     *
     * @return string
     * 
     * @access  public
     */

    public function run(): string {
        parent::run();

        $input = '';

        $input .= Html::beginTag('div', ['class' => 'ui-slider-container']);

        if (isset($this->leftLabel)) {
            $input .= Html::label($this->leftLabel, $this->options['id'], ['class' => 'ui-main-label']);
        }

        $input .= Html::beginTag('label', ['class' => 'ui-switch']);
        if (!$this->hasModel()) {
            $input .= Html::checkbox($this->name, $this->checked, $this->options);
        } else {
            $this->options['label'] = false;
            $input .= Html::activeCheckbox($this->model, $this->attribute, $this->options);
        }
        $input .= Html::tag('span', '', ['class' => 'ui-slider ui-slider-round']);
        $input .= Html::endTag('label');

        if (isset($this->rightLabel)) {
            $input .= Html::label($this->rightLabel, $this->options['id'], ['class' => 'ui-main-label']);
        }

        $input .= Html::endTag('div'); // ui-slider-container

        return $input;
    }
}
