<?php
namespace nur\v\bs3\fo;

use nur\b\params\Tparametrable;
use nur\base;
use nur\v\v;

abstract class ControlVisualInput extends ControlVisual {
  use Tparametrable;

  /** @var string type de champ input */
  const INPUT_TYPE = null;

  const PARAMETRABLE_PARAMS_SCHEMA = [
    "label" => ["?content", null, "libellé du champ"],
    "autohide_label" => ["?bool", null, "faut-il cacher le label s'il y a le placeholder?"],
    "placeholder" => ["?content", null, "valeur suggérée"],
    "required" => ["?bool", null, "ce champ est-il requis?"],
    "show_required" => ["?bool", null, "faut-il afficher la marque de champ requis?"],
  ];

  function __construct(Form $form, ?array $params=null) {
    parent::__construct($form, $params);
    base::update_n($this->ppPlaceholder, $this->ppLabel);
    base::update_n($this->ppShowRequired, $this->ppRequired);
  }

  /** @var array|string */
  protected $ppLabel;

  /** @var ?bool */
  protected $ppAutohideLabel;

  /** @var array|string */
  protected $ppPlaceholder;

  /** @var ?bool */
  protected $ppRequired;

  /** @var ?bool */
  protected $ppShowRequired;

  protected function buildControl(): array {
    $name = $this->ppName;
    $value = $this->ppValue;
    return v::tag1("input", [
      "type" => static::INPUT_TYPE,
      "id" => $this->ppId,
      "name" => $name,
      "value" => $value,
      "readonly" => $this->ppReadonly? "readonly": false,
      "disabled" => $this->ppDisabled? "disabled": false,
      "required" => $this->ppRequired? "required": false,
      "placeholder" => $this->ppPlaceholder,
      "class" => ["form-control", $this->ppClass],
      "style" => $this->ppStyle,
      $this->ppAttrs,
    ]);
  }

  function getControl(): array {
    $control = $this->buildControl();
    if ($this->ppNaked) return $control;

    $form = $this->form;
    $name = $this->ppName;
    $value = $this->ppValue;
    $label = $this->ppLabel;
    $autohideLabel = $this->ppAutohideLabel;
    if ($autohideLabel === null) $autohideLabel = $form->isAutohideLabel();
    if ($autohideLabel && $this->ppPlaceholder && !$value) $label = null;
    $showLabel = $label || !$autohideLabel;
    if ($label && $this->ppRequired && $this->ppShowRequired) {
      $label = [q($label), " <sup class=\"required\" title=\"required\">(*)</sup>"];
    } else {
      $label = q($label);
    }

    [$fgClass, $feedback] = $this->getStdFeedback($name, $value);
    return $this->getFglcLayout($label, $showLabel, $control, $fgClass, $feedback);
  }
}
