<?php

class Agro_View_Helper_TreeViewAcao extends Zend_Controller_Action_Helper_Abstract
{
    public static function treeViewAcao($checked = array(), $where = array())
    {
        function buscaFilhos($id_acao, $checked)
        {
            $model = new Sistema_Model_Acoes();
            $acoes = $model->fetchAll("id_parent = {$id_acao} AND fl_del = false", "ds_label")->toArray();

            $html = "<ul>";

            foreach ($acoes as $acao) {
                $label = $acao["ds_label"];

                if ($acao['fl_tipo'] === Sistema_Model_Acoes::TIPO_RELATORIO) {
                    $label = "{$acao["id"]} - {$acao["ds_label"]}";
                }

                if ($model->acaoPermitida($acao["id"])) {
                    $html .= "<li>";
                    $html .= '<input type="checkbox" name="id_acao[]" id="acao_' . $acao["id"] . '" data-acao="filho" data-parent="' . $id_acao . '" value="' . $acao["id"] . '" onclick="checkParent(this, ' . $id_acao . ');" ' . (in_array($acao["id"], $checked) ? 'checked="checked"' : "") . '>';
                    $html .= '<label title="' . $acao["ds_descricao"] . '">&nbsp' . $label . '</label>';

                    if ($model->temFilhos($acao["id"])) {
                        $html .= buscaFilhos($acao["id"], $checked);
                    }
                    $html .= "</li>";
                }
            }

            $html .= "</ul>";
            return $html;
        }

        $model = new Sistema_Model_Acoes();

        $where[] = "fl_ativo=true";
        $where[] = "fl_del=false";
        $where[] = "id_parent is null";

        $acoes = $model->fetchAll(implode(" and ", $where), "ds_label")->toArray();

        ?>
      <script type="text/javascript" src="/resources/jquery/checkboxtree/jquery.checkboxtree.js"></script>
      <link rel="stylesheet" type="text/css" href="/resources/jquery/checkboxtree/jquery.checkboxtree.css"/>

      <ul style="list-style: none; margin-top: 10px;">
        <li>
          <button id="checkAll">Marcar todos</button>
          <button id="unCheckAll">Desmarcar todos</button>
          <span>|</span>
          <button id="expandAll">Expandir tudo</button>
          <button id="collapseAll">Recolher tudo</button>
        </li>
      </ul>

      <ul id="tree1" style="border: none; margin: 15px 10px 20px 10px">
          <?php
          foreach ($acoes as $acao) {
              if ($model->acaoPermitida($acao["id"])) {
                  ?>
                <li>
                  <input type="checkbox" name="id_acao[]" id="acao_<?= $acao["id"] ?>" data-acao="pai"
                         value="<? echo $acao["id"] ?>" <? echo(in_array($acao["id"], $checked) ? 'checked="checked"' : "") ?>>
                  <label title="<? echo $acao["ds_descricao"] ?>"><? echo $acao["ds_label"] ?></label>

                    <?php
                    if ($model->temFilhos($acao["id"])):
                        echo buscaFilhos($acao["id"], $checked);
                    endif;
                    ?>
                </li>
                  <?php
              }
          }
          ?>
      </ul>

      <script type="text/javascript">
        $('#tree1').checkboxTree({
          initializeChecked: 'expanded',
          initializeUnchecked: 'collapsed',
          onCheck: {
            ancestors: '',
            descendants: 'check'
          },
          onUncheck: {
            ancestors: 'null'
          }
        });

        $("#checkAll").click(function (e) {
          e.preventDefault();
          $('#tree1').checkboxTree('checkAll');
        });

        $("#unCheckAll").click(function (e) {
          e.preventDefault();
          $('#tree1').checkboxTree('uncheckAll');
        });

        $("#expandAll").click(function (e) {
          e.preventDefault();
          $('#tree1').checkboxTree('expandAll');
        });

        $("#collapseAll").click(function (e) {
          e.preventDefault();
          $('#tree1').checkboxTree('collapseAll');
        });

        function checkParent(elemento, acaoParent) {
          const parent = $(`#acao_${acaoParent}`);

          if ($(elemento).is(':checked') === true) {
            parent.attr('checked', 'checked');
          }

          if (parent.attr('data-acao') === 'filho') {
            checkParent(parent[0], parent.attr('data-parent'));
          }
        }
      </script>
        <?
    }
}
