<?php

namespace Velis\Acl;

use Velis\Model\DataObject;
use Velis\Acl;

/**
 * ACL changelog model
 * @author Olek Procki <olo@velis.pl>
 */
class Changelog extends DataObject
{

    const ITEMS_PER_PAGE = 50;


    /**
     * Filter list params by default
     * @var bool
     */
    protected static $_filterListParams = true;


    /**
     * Returns related table name
     * @return string
     */
    protected function _getTableName()
    {
        return 'acl.changelog_tab';
    }


    /**
     * Returns list datasource view name
     * @return string
     */
    protected function _getListDatasource()
    {
        return 'acl.changelog';
    }


    /**
     * Returns matrix type name
     * @return string
     */
    public function getMatrixType()
    {
        return Acl::getMatrixTypes()[$this->matrix_acro];
    }


    /**
     * Returns changelog entry list
     *
     * @param int $page
     * @param array|ArrayObject $params
     * @param string $order
     * @param int $limit
     * @param string|array $fields
     *
     * @return \Acl\Changelog[]
     */
    public static function getList($page = 1, $params = null, $order = null, $limit = self::ITEMS_PER_PAGE, $fields = null)
    {

        if ($params['search']) {
            self::$_listConditions[] = '(
                priv_acro ILIKE :search OR
                invoker_first_name ILIKE :search OR
                invoker_last_name ILIKE :search OR
                user_first_name ILIKE :search OR
                user_last_name ILIKE :search
            )';
            self::$_listParams['search'] = '%' . $params['search'] . '%';
        }

        if ($params['date_start_from']) {
            self::$_listConditions[] = 'date_modified >= :date_modified_from';
            self::$_listParams['date_modified_from'] = $params['date_start_from'];
            if ($params['time_from']) {
                self::$_listParams['date_modified_from'] .= str_replace('T', ' ', $params['time_from']);
            } else {
                self::$_listParams['date_modified_from'] .= ' 00:00:00';
            }
        }

        if ($params['date_start_to']) {
            self::$_listConditions[] = 'date_modified <= :date_modified_to';
            self::$_listParams['date_modified_to'] = $params['date_start_to'];
            if ($params['time_to']) {
                self::$_listParams['date_modified_to'] .= str_replace('T', ' ', $params['time_to']);
            } else {
                self::$_listParams['date_modified_to'] .= ' 23:59:59';
            }
        }

        return parent::getList($page, $params, $order, $limit, $fields);
    }
}
