<?php
Yii::import('zii.widgets.jui.CJuiWidget');

class Handsontable extends CJuiWidget
{
    public $target = ".handsontable";
    /*public $tipo;
    public $key = false;
    public $id;*/
    public $colHeaders = array();
    public $rowHeaders = array();
    public $columns = array();

    public $afterChange = false;

    public $valores = false;

    public $readOnlyLine = false;
    public $readOnlyColumns = false;

    public function init()
    {
        parent::init();

        $this->id = "handsontable_" . Util::uid();

        return $this->registerScripts();
    }

    protected function registerScripts()
    {
        parent::registerCoreScripts();
        $basePath = Yii::getPathOfAlias('application.extensions.Handsontable.assets');
        $baseUrl = Yii::app()->getAssetManager()->publish($basePath);

        $cs=Yii::app()->getClientScript();
        $cs->registerCssFile($baseUrl . '/' . 'css/handsontable.full.css');
        $cs->registerCssFile($baseUrl . '/' . 'css/style.css');

        $this->scriptUrl = $baseUrl;
        $this->registerScriptFile('js/handsontable.full.js');
        $this->registerScriptFile('js/ruleJS.all.full.js');
        $this->registerScriptFile('js/handsontable.formula.js');
        $this->registerScriptFile('locales/pt-br.js');

        if (!$this->valores) {
            $colunas = $this->columns;
        } else {
            $colunas = $this->valores;
        }
        $valores = array();
        $linha = 1;
        foreach ($this->rowHeaders as $header) {
            foreach ($colunas as $key => $column) {
                $firstColumn = chr(65); // primeira coluna
                $currentColumn = chr($key+65);
                $lastColumn = chr(($key-1)+65); // coluna anterior a atual
                if (!isset($column['soma'])) {
                    if (!in_array($header, ["<b>Global</b>", "<b>Soma</b>", "<b>Meta do Grupo</b>"])) {
                        $valores[$linha-1][$column['data']] = (isset($column['values'][$linha])) ? $column['values'][$linha] : 0;
                    } else {
                        $penultimaLinha = count($this->rowHeaders)-1;
                        $valores[$linha-1][$column['data']] = "=SUM({$currentColumn}1:{$currentColumn}{$penultimaLinha})";
                    }
                } else {
                    $valores[$linha-1][$column['data']] = "=SUM({$firstColumn}{$linha}:{$lastColumn}{$linha})";
                    // unset($this->columns[$linha]['soma']);
                }
            }
            $linha++;
        }
        $this->valores = CJSON::encode($valores);

        $colHeaders = CJSON::encode($this->colHeaders);
        $rowHeaders = CJSON::encode($this->rowHeaders);

        $columns = CJSON::encode($this->columns);

        $script = "";
        $script .= "var {$this->id} = new Handsontable($('{$this->target}')[0], {\n";
            $script .= "data: {$this->valores},\n";
            $script .= "colHeaders: {$colHeaders},\n";
            $script .= "rowHeaders: {$rowHeaders},\n";
            $script .= "renderAllRows: true,\n";
            $script .= "minRows: " . count($this->rowHeaders) . ",\n";
            $script .= "maxRows: " . count($this->rowHeaders) . ",\n";
            $script .= "formulas: true,\n";
            $script .= "columns: {$columns},\n";
            $script .= "colWidths: 85,\n";
            if ($this->readOnlyLine || $this->readOnlyColumns) {
                $script .= "cells: function(row, col, prop) {\n";
                    $script .= "var cellProperties = {};\n";
                    if ($this->readOnlyLine) {
                        $script .= "var cellProperties = {};\n";
                        $script .= "if (row=={$this->readOnlyLine}) {\n";
                            $script .= "cellProperties.readOnly = true;\n";
                        $script .= "}\n";
                    }

                    if ($this->readOnlyColumns) {
                        $script .= "var readonly = {\n";
                            foreach ($this->readOnlyColumns as $linha => $colunas) {
                                $script .= "$linha: [";
                                    foreach ($colunas as $key => $value) {
                                        $script .= "$key,";
                                    }
                                $script .= "],\n";
                            }
                        $script .= "};\n";

                        $script .= "$.each(readonly, function(linha, colunas) {\n";
                             $script .= "$.each(colunas, function(index, coluna) {\n";
                                $script .= "if (row==linha && col==coluna) {\n";
                                    $script .= "cellProperties.readOnly = true;\n";
                                $script .= "}\n";
                             $script .= "});\n";
                        $script .= "});\n";
                    }
                    $script .= "return cellProperties;\n";
                $script .= "},\n";
            }
            if ($this->afterChange) {
                $script .= "afterChange: function (change, source) {\n";
                    $script .= "if (source != 'loadData') {\n";
                        $script .= "var data = {$this->id}.getData();\n";
                        $script .= "{$this->afterChange}(data);\n";
                    $script .= "}\n";
                $script .= "}\n";
            }
        $script .= "});\n";

        $cs->registerScript($this->id, $script, CClientScript::POS_READY);
    }
}
?>