<?php

class Zend_View_Helper_MountField extends Zend_Controller_Action_Helper_Abstract
{
    public static function mountField(
        $element,
        $tipo,
        $value,
        $options,
        $validar = null,
        $when = null,
        array $parametrosAdicionais = []
    )
    {
        $atributo191 = $element === "value_atributo[191]";

        switch ($tipo) {
            // mode "go horse" on, don't blame me. I was forced to do this shit bellow :(
            case 'multilookup':
                $atributo = substr(
                    $element,
                    strpos($element, '[') + 1,
                    strpos($element, ']') - strpos($element, '[') - 1
                );
                $opcoes = self::opcoesMultilookup($atributo);

                if ($value) {
                    $arValores = explode(',', $value);
                    $val = array_shift($arValores);
                }

                $field = '<table cellpading="0" cellspacing="0">';
                $field .= '  <tr>';
                $field .= '    <td>';
                $field .= '      <input class="integer" type="text" name="' . $element . '" id="' . $element . '" value="' . $val . '">&nbsp;';
                $field .= '    </td>';
                $field .= '    <td>&nbsp;';
                $field .= '      <select name="value_atributo[' . $atributo . '_complemento]" id="value_atributo[' . $atributo . '_complemento]" class="multiple" multiple="multiple">';

                foreach ($opcoes as $id => $nome) {
                    $field .= '<option value="' . $id . '" ' . (in_array($id, $arValores) ? 'selected' : '') . '>';
                    $field .= '&nbsp;' . $nome;
                    $field .= '</option>';
                }

                $field .= '      </select>';
                $field .= '    </td>';
                $field .= '  </tr>';
                $field .= '</table>';

                return $field;
            // mode "go horse" off

            case 'select':
                $field = "<select name='$element' id='$element'>";

                if ($options) {
                    $valores = explode('|', $options);

                    if (is_array($valores)) {
                        foreach ($valores as $valor) {
                            $valor = explode(':', $valor);

                            if (array_key_exists('0', $valor) && array_key_exists('1', $valor)) {
                                if ($valor[0] == $value) {
                                    $field .= "<option value='{$valor[0]}' selected>{$valor[1]}</option>";
                                } else {
                                    $field .= "<option value='{$valor[0]}'>{$valor[1]}</option>";
                                }
                            }
                        }
                    }
                }

                $field .= "</select>";
                return $field;

            case 'radio':
                $field = "<table width='100%'>";

                if ($options) {
                    $valores = explode('|', $options);
                    $ret = array();

                    if (is_array($valores)) {
                        foreach ($valores as $valor) {
                            $valor = explode(':', $valor);

                            if (array_key_exists('0', $valor) && array_key_exists('1', $valor)) {
                                $field .= "<tr>";
                                $field .= "<td>";
                                $field .= "<input type='radio' name='$element' id='$element-{$valor[0]}' value='{$valor[0]}' />";
                                $field .= "</td>";
                                $field .= "<td>{$valor[1]}</td>";
                                $field .= "</tr>";
                            }
                        }
                    }

                    $field->setMultiOptions($ret);
                }

                $field .= "<table>";
                break;

            case 'check':
                $field = "<input type='checkbox' name='$element' id='$element' value='$value' />";
                break;

            case 'currency':
            case 'decimal':
            case 'integer':
                $field = "<input type='text' name='$element' id='$element' value='$value' class='$tipo' size='7' />";
                break;

            case 'textarea':
                $field = "<textarea name='$element' id='$element' value='$value'></textarea>";
                break;

            case 'data':
                $field = "<input type='text' name='$element' id='$element' value='$value' class='$tipo' size=10/>";
                break;

            case 'select_text':
                //combo normal que exibe um campo text ao lado de acordo com o value
                $js = $text = '';
                $atributo = substr(
                    $element,
                    strpos($element, '[') + 1,
                    strpos($element, ']') - strpos($element, '[') - 1
                );

                $arValores = explode(',', $value);

                //Exibe o campo text de acordo com o valor do select
                if (($validar != '') && ($when != '')) {
                    $valueInput = empty($arValores[1]) ? '' : $arValores[1];
                    $class = !empty($parametrosAdicionais['class']) ? $parametrosAdicionais['class'] : '';
                    $placeholder = !empty($parametrosAdicionais['placeholder'])
                        ? $parametrosAdicionais['placeholder']
                        : '';
                    $valueInput = !empty($parametrosAdicionais['valuePadrao']) && empty($valueInput)
                        ? $parametrosAdicionais['valuePadrao']
                        : $valueInput;

                    $text = "&nbsp;<input type='text'";
                    $text .= "            {$placeholder}";
                    $text .= "            name='value_atributo[{$atributo}_complemento]'";
                    $text .= "            id='value_atributo[{$atributo}_complemento]'";
                    $text .= "            class='{$class}'";
                    $text .= "            style='display:none' />";

                    if ($arValores[0] == $when || $atributo191) {
                        
                        $text = "&nbsp;<input type='text' ";
                        $text .= "            value='{$valueInput}'";
                        $text .= "            {$placeholder}";
                        $text .= "            name='value_atributo[{$atributo}_complemento]'";
                        $text .= "            id='value_atributo[{$atributo}_complemento]'";
                        $text .= "            class='{$class}'";
                        $text .= "            style='display:inline' />";
                    }

                    $js = "
                        onchange=\"document.getElementById('value_atributo[{$atributo}_complemento]').style.display = (
                            document.getElementById('value_atributo[$atributo]').value == $when ? 'inline' : 'none'
                        );\"";

                    if ($atributo191) {
                        $js = "
                        let select_permissao = document.getElementById('value_atributo[191]')
                        let input_numero_dias = document.getElementById('value_atributo[191_complemento]')
                        if(select_permissao.value > 0){
                            if (input_numero_dias.value && !input_numero_dias.value.startsWith('-')) {
                                input_numero_dias.value = '-'+input_numero_dias.value
                            }
                        }else{
                            let newStr = input_numero_dias.value.replace('-', '');
                            input_numero_dias.value = newStr
                        }\"";
                    }
                }

                $field = "<select name='$element' id='$element' $js>";

                if ($options) {
                    $valores = explode('|', $options);

                    if (is_array($valores)) {
                        foreach ($valores as $valor) {
                            $valor = explode(':', $valor);

                            if (array_key_exists('0', $valor) && array_key_exists('1', $valor)) {
                                if ($valor[0] == $arValores[0]) {
                                    $field .= "<option value='{$valor[0]}' selected>{$valor[1]}</option>";
                                } else {
                                    $field .= "<option value='{$valor[0]}'>{$valor[1]}</option>";
                                }
                            }
                        }
                    }
                }

                $field .= "</select>";

                if ($js && $text) {
                    $field .= $text;
                }

                return $field;

            case 'text':
            default:
                $field = "<input type='text' name='$element' id='$element' value='$value' />";
                break;
        }

        $html = "<label>$field</label>";

        if ($atributo191) {
            $html .= "<script>document.getElementById('value_atributo[191_complemento]').addEventListener('change', function() {
            var value = this.value;
            let select_permissao = document.getElementById('value_atributo[191]')
            if(select_permissao.value > 0){
                if (value && !value.startsWith('-')) {
                    this.value = '-' + value;
                }
            }
            });
            </script>";
        }

        return $html;
    }

    private static function opcoesMultilookup($idAtributo)
    {
        $rowAtributo = (new Produto_Model_Atributos())->find($idAtributo)->current();

        switch ($rowAtributo['ds_chave_rn']) {
            case Produto_Model_Atributos::DS_CHAVE_PROD_SUBVENCAO_FEDERAL_VALOR_MAX_GRUPO:
                $opcoes = (new Produto_Model_Tipos())->fetchPairs('id', 'ds_tipo_produto', false, false, 1, false, false, 'ASC');
                break;

            default:
                $opcoes = (new Produto_Model_Culturas())->fetchPairs('id', 'ds_nome_cultura', false, false, 1, false, false, 'ASC');
                break;
        }

        return $opcoes;
    }
}
