<?php

Yii::import('bootstrap.widgets.TbButtonColumn');

class PlCButtonColumn extends TbButtonColumn
{

    public $template = '{ajaxUpdate} {update} {delete}';
    public $usePageSelector = true;
    public $ajaxUpdateUrl;

    public function init()
    {
        $this->initAjaxUpdateButton();
        parent::init();
        $this->htmlOptions['class'] = 'buttonColumnIcons';
        if ($this->usePageSelector) {
            $this->setupPageSizeSelector();
        }
    }

    protected function initAjaxUpdateButton()
    {
        if (!$this->ajaxUpdateUrl) {
            $this->ajaxUpdateUrl = 'app()->controller->createUrl("update", array("id" => $data->primaryKey))';
        }

        $this->buttons['ajaxUpdate'] = array(
            'label' => Yii::t('zii', 'Update'),
            'url' => $this->ajaxUpdateUrl,
            'imageUrl' => 'imgUrl',
            'options' => array(
                'class' => 'update'
            ),
            'icon' => 'pencil',
            'visible' => isset($this->buttons['ajaxUpdate']['visible']) ? $this->buttons['ajaxUpdate']['visible'] : 'true',
        );

        $modalId = $this->grid->id . '_Modal';
        $modalDeleteBtnId = $modalId . '_deleteBtn';
        $modalHeader = '';
        if (isset($this->grid->modalUpdateHeader)) {
            $modalHeader = __($this->grid->modalUpdateHeader);
        }

        $this->buttons['ajaxUpdate']['click'] = <<<EOD
        function(){
            $.get(this.href, function(data){
                $(".modal-body").html(data);
                        $('#$modalId .modal-header h4').html("$modalHeader");
                        $('#$modalDeleteBtnId').show();
                        $('#$modalId').modal('show');
                        return false;
            });
            return false;
        }
EOD;
    }

    private function setupPageSizeSelector()
    {
        if ($this->header != null) {
            return;
        }
        $selector = CHtml::dropDownList(
                        'pageSize', getGridPageSize($this->grid->id), array(
                    10 => 10,
                    20 => 20,
                    50 => 50,
                    100 => 100,
                    200 => 200,
                    500 => 500
                        ), array(
                    'onchange' => "$.fn.yiiGridView.update('" . $this->grid->id . "',{ data:{pageSize: {'" . $this->grid->id . "':$(this).val()} }})",
                        )
        );
        $this->header = $selector;
    }
}
