<?php

namespace Widgets\Jquery\Jgrid;

/**
 * Description of ActiveJGrid
 *
 * @author Dmitriy
 */
class ActiveJGrid extends Jqgrid
{

    private $session;

    protected $name;

    public $rowlist = array(2, 100, 250, 500, 1000);


    function setSession($session)
    {
        $this->session = $session;
    }


    /**
     * get columns array
     * @return type
     */
    public function getColumns()
    {
        return $this->colmodel;
    }


    /**
     * кол-во записей
     *
     * @return type
     */
    protected function getCount()
    {

        $criteria = new \SimpleORM\Specification();
        $criteria->setManualSelect("COUNT(*) AS cnt");
        $row = $this->model->resultArray()->findBySpecification($criteria);
        return $row['cnt'];
    }

    /**
     * получение данных
     * @return type
     */
    protected function getRows()
    {

        $criteria = new \SimpleORM\Specification();

        if (isset($this->post['page']) && isset($this->post['rows'])) {
            $criteria->setLimit($this->post['rows']);
            $criteria->setOfset(($this->post['page'] - 1) * $this->post['rows']);
        } else {
            $criteria->setLimit($this->post['rows']);
        }

        if (isset($this->post['sidx']) && isset($this->post['sord'])) {
            $criteria->setOrder([
                $this->post['sidx'] => $this->post['sord']
            ]);
        } else {
            $criteria->setOrder([
                $this->sortname => $this->sortorder
            ]);
        }

        $this->setExtendsFilter($criteria);

        //ed($criteria);

        $rows = $this->model->resultArray()->useJoins()->findAllBySpecification($criteria);
        //ed($rows,1);
        $line = array();

        foreach ($this->colmodel as $k => $column) {
            $line[] = '$this->prepareRow2($row,\'' . $column['name'] . '\',\'' . $column['index'] . '\') '; //
        }

        $this->line = '$_rows[$i] = array( \'id\' => $this->prepareFirstRow($row),  \'cell\' => array(' . "\r\n" . implode(',' . "\r\n", $line) . '));';

        //__var_dump($this->group_rows);

        return $this->extractRows($rows);
    }

    /**
     * Применение фильтра с клиента
     * @param \SimpleORM\Specification $criteria
     */
    protected function setExtendsFilter(\SimpleORM\Specification $criteria)
    {
        $where = [];

        foreach ($this->colmodel as $column) {

            if (input_post($column['index'])) {
                $where[$column['index']] = [
                    'value' => input_post($column['index']),
                    'operator' => 'like'
                ];
            }

        }

        $criteria->setWhere($where);

    }

    protected function extractRows($rows)
    {

        $summ_text = '';


        if (count($this->summary) > 0) {
            foreach ($this->summary as $summ_field) {
                $this->summary_result[$summ_field] = 0;
                $summ_text .= '$this->summary_result[\'' . $summ_field . '\'] += $row[\'' . $summ_field . '\'];';
            }

        }

        $_rows = array();
        //__var_dump($this->line);

        $i = 0;

        if (count($rows) > 0) {
            foreach ($rows as $row) {
                if (!empty($row[$this->model->getPrimaryKey()])) {
                    eval($this->line);
                    if ($summ_text > '') eval($summ_text);
                    $i++;
                }
            }
        }
        //__var_dump($_rows);
        return $_rows;
    }

    protected function prepareFirstRow($row)
    {
        return $row[$this->model->getPrimaryKey()];
    }

    public function getKey()
    {
        return $this->key;
    }

    /**
     * Сохранение параметров состояния таблицы
     *
     * @param mixed $params
     * @return void
     */
    function saveStateParams(array $post)
    {

        // $this->session->set_userdata('grid_'. $this->name. '_params',$post);

        return true;
    }


    /**
     * Получение сохраненных данных если произошел возврат с формы
     *
     * @return
     */
    function loadStateParams()
    {

        // $save_url = $this->session->flashdata('form_back_action');

//ed( $save_url);		

        if (!empty($save_url) && str_replace('/ajax/', '/admin/', current_url()) == $save_url)//&& current_url()==$save_url
        {
            //   $this->session->userdata('grid_'. $this->name. '_params');
        }
        return FALSE;
    }

    public function init($param = array())
    {


        //отправка данные если аякс
        if (!$this->ajax_query()) {
            //продление адреса дейстия формы
            //$this->session->keep_flashdata('form_back_action');
        }

        return parent::init($param);
    }

    protected function prepareRow2(array $row, $field, $alias)
    {

        $result = !isset($row[$alias]) ? '&nbsp;' : $row[$alias];

        if (isset($this->customformat[$field])) {

            $result = call_user_func($this->customformat[$field], $row);

//            $result = call_user_func_array(array($this->customformat[$field][1], $this->customformat[$field][0]), array(array(
//                    'result' => $result,
//                    'row' => $row
//                ), false));
        }

        return $result;
    }
}
