<?php

/**
 *
 * Cube Framework $Id$ 2Juc/7HKeZ9SHZoOqukALl4ZcB8gPPgu9JgWXn9brTg=
 *
 * @link        http://codecu.be/framework
 * @copyright   Copyright (c) 2017 CodeCube SRL
 * @license     http://codecu.be/framework/license Commercial License
 *
 * @version     1.10 [rev.1.10.02]
 */
/**
 * creates a checkbox element
 */

namespace Cube\Form\Element;

use Cube\Form\Element;

class Checkbox extends Element
{

    /**
     *
     * type of element - override the variable from the parent class
     *
     * @var string
     */
    protected $_element = 'checkbox';

    /**
     *
     * class constructor
     *
     * @param string $name
     */
    public function __construct($name)
    {
        parent::__construct($this->_element, $name);
    }

    /**
     *
     * render the form element
     *
     * @return string
     */
    public function render()
    {
        $output = null;
        $value = $this->getValue();

        $translate = $this->getTranslate();

        $multiple = '';
        if (count((array)$this->_multiOptions) > 1 || $this->getMultiple() === true) {
            $multiple = $this->_brackets;
        }

        $output .= '<input type="hidden" name="' . $this->_name . $multiple . '" value=""'
            . $this->_endTag;

        foreach ((array)$this->_multiOptions as $key => $option) {
            $checked = (in_array($key, (array)$value)) ? 'checked="checked"' : '';

            if (is_array($option)) {
                $title = isset($option[0]) ? $option[0] : null;
                $description = isset($option[1]) ? $option[1] : null;

                if (isset($option[2])) {
                    $this->addMultiOptionAttributes($key, $option[2]);
                }
            }
            else {
                $title = $option;
                $description = null;
            }

            $attributes = array(
                'type="' . $this->_element . '"',
                'name="' . $this->_name . $multiple . '"',
                'value="' . $key . '"',
                $this->renderAttributes(),
                $this->renderOptionAttributes($key),
                $checked,
            );

            $output .= '<label class="checkbox">'
                . '<input ' . implode(' ', array_filter($attributes)) . '>'
                . ' ' . $translate->_($title)
                . ((!empty($description)) ? '<span class="help-block">' . $translate->_($description) . '</span>' : '')
                . '</label>'
                . "\n";
        }

        return $output;
    }

}

