<?php

namespace Teknisa\Libs\Util\Repositories;

use Doctrine\ORM\EntityManager;

class ZhuLog {
    /** @var EntityManager $entityManager */
    protected $entityManager;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager) {
        $this->entityManager = $entityManager;
    }

    /**
     * @param $filters
     * @param $limit
     * @param $offset
     * @param $productId
     * @param $order
     * @return array
     */
    public function getZhuLog($filters, $limit, $offset, $productId, $order) {
        $query =  <<<SQL
                    SELECT TYPE AS "TYPE", HTTP_RESPONSE_CODE AS "HTTP_RESPONSE_CODE", REQ_ID AS "REQ_ID", METHOD AS "METHOD", REQUEST_TYPE AS "REQUEST_TYPE", TIMESTAMP AS "TIMESTAMP", USER_ID AS "USER_ID", USER_NAME AS "USER_NAME", PRODUCT_ID AS "PRODUCT_ID", ROUTE AS "ROUTE", ROUTE_LABEL AS "ROUTE_LABEL", ORGANIZATION_ID AS "ORGANIZATION_ID", CONTAINER_NAME AS "CONTAINER_NAME", WIDGET_NAME AS "WIDGET_NAME", CONTENT AS "CONTENT"
                    FROM ( SELECT ZL.TYPE, ZL.HTTP_RESPONSE_CODE, ZL.REQ_ID, ZL.METHOD, ZL.REQUEST_TYPE, ZL.TIMESTAMP, 
                                  ZL.USER_ID, OP.NMOPERADOR AS USER_NAME, ZL.PRODUCT_ID, ZL.ROUTE, ZL.ROUTE AS ROUTE_LABEL,
                                  ZL.ORGANIZATION_ID, ZL.CONTAINER_NAME, ZL.WIDGET_NAME, ZL.CONTENT
                             FROM ZH_LOG ZL
                             JOIN OPERADOR OP ON OP.CDOPERADOR = ZL.USER_ID
                            WHERE ZL.PRODUCT_ID = $productId )
                   WHERE 1 = 1
                         $filters
SQL;
        $query = $this->getPaginatedQuery($query, $limit, $offset) . $order;
        return $this->entityManager->getConnection()->fetchAllAssociative($query);
    }

    private function getPaginatedQuery($query, $limit, $offset) {
        if ($limit > 0) {
            $max = $offset + $limit;
            $column = '*';
            if ($offset > 0) {
                $min = $offset + 1;
                $query = 'SELECT * FROM (SELECT a.' . $column . ', rownum AS doctrine_rownum FROM (' .
                    $query .
                    ') a WHERE rownum <= ' . $max . ') WHERE doctrine_rownum >= ' . $min;
            } else {
                $query = 'SELECT a.' . $column . ' FROM (' . $query . ') a WHERE ROWNUM <= ' . $max;
            }
        }

        return $query;
    }
} 