<commit_before><?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Adteam\Core\Admin\Checkout\Repository;

use Doctrine\ORM\EntityRepository;
use Adteam\Core\Admin\Checkout\Entity\CoreConfigs;
use Adteam\Core\Admin\Checkout\Entity\OauthUsers;
use Adteam\Core\Admin\Checkout\Entity\CoreCheckoutActivationLog;

class CoreCheckoutActivationLogRepository extends EntityRepository
{
    /**
     * Fetch all config values
     *
     * @return array
     */
    public function fetchLast()
    {
        $config = $this->_em->getRepository(CoreConfigs::class)->getCheckoutRange();

        $currentTime = time();
        $rangeStart = isset($config['checkout.date.start']) ? (int)$config['checkout.date.start'] : 0;
        $rangeEnd = isset($config['checkout.date.end']) ? (int)$config['checkout.date.end'] : 0;

        $checkoutIsActive = $rangeStart <= $currentTime && $currentTime <= $rangeEnd;

        $result = $this->createQueryBuilder('B')
            ->select("B.status as enabled,DATE_FORMAT(B.createdAt,'%d-%m-%Y" .
                " %H:%i:%s') as version")
            ->innerJoin('B.requestedBy', 'R')
            ->orderBy('B.createdAt', 'DESC')
            ->getQuery()->getResult();
        if (isset($result[0])) {
            $checkout = (array)$result[0];
            $checkout['enabled'] = $checkoutIsActive;
            $checkout['dateStart'] = $rangeStart;
            $checkout['dateEnd'] = $rangeEnd;
            return $checkout;
        }

        throw new \InvalidArgumentException('Inicializar_canje');
    }

    /**
     * verifica si esta vacio log
     *
     * @return boolean
     */
    private function hasInit()
    {
        $isInit = false;
        $result = $this->createQueryBuilder('B')
            ->select("B.id, B.createdAt, R.id as userId, R.displayName, B.status")
            ->innerJoin('B.requestedBy', 'R')
            ->getQuery()->getResult();
        if (count($result) <= 0) {
            $isInit = true;
        }
        return $isInit;

    }

    /**
     * @param object $data
     * @param string $identity
     * @return boolean
     * @throws \InvalidArgumentException
     */
    public function create($data, $identity)
    {
        $user = $this->getUserByUsername($identity['user_id']);

        // Obtener los parámetros
        $dateStart = property_exists($data, 'date.start') ? $data->{"date.start"} : null;
        $dateEnd = property_exists($data, 'date.end') ? $data->{"date.end"} : null;

        // Al menos un parámetro debe existir
        if (is_null($dateStart) && is_null($dateEnd)) {
            throw new \InvalidArgumentException('Missing_Arguments');
        }

        // Validar rangos correctos
        if (!is_null($dateStart) && !is_null($dateEnd) && (int)$dateStart >= (int)$dateEnd) {
            throw new \InvalidArgumentException('Invalid_Range');
        }

        $currentTime = time();

        // Colocar rangos que vienen nulos
        $dateStart = is_null($dateStart) ? 0 : $dateStart;
        $dateEnd = is_null($dateEnd) ? PHP_INT_MAX : $dateEnd;

        // Determinar si el canje será activado (dateStart enviado y fecha actual mayor o igual a fecha de canje)
        $enabled = !is_null($dateStart) && $currentTime >= $dateStart;
        $enabled = $enabled && (is_null($dateEnd) ? true : $currentTime < $dateEnd);

        if ($this->hasInit()) {
            if ($enabled) {
                return $this->insertLog($user, $dateStart, $dateEnd);
            } else {
                throw new \InvalidArgumentException('only_true');
            }
        } else {
            return $this->insertLog($user, $dateStart, $dateEnd);
        }
    }

    /**
     * Obtiene usuario mediante username
     *<commit_msg>Modifica el entero máximo de la fecha de cierre predeterminada<commit_after><?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Adteam\Core\Admin\Checkout\Repository;

use Doctrine\ORM\EntityRepository;
use Adteam\Core\Admin\Checkout\Entity\CoreConfigs;
use Adteam\Core\Admin\Checkout\Entity\OauthUsers;
use Adteam\Core\Admin\Checkout\Entity\CoreCheckoutActivationLog;

class CoreCheckoutActivationLogRepository extends EntityRepository
{
    /**
     * Fetch all config values
     *
     * @return array
     */
    public function fetchLast()
    {
        $config = $this->_em->getRepository(CoreConfigs::class)->getCheckoutRange();

        $currentTime = time();
        $rangeStart = isset($config['checkout.date.start']) ? (int)$config['checkout.date.start'] : 0;
        $rangeEnd = isset($config['checkout.date.end']) ? (int)$config['checkout.date.end'] : 0;

        $checkoutIsActive = $rangeStart <= $currentTime && $currentTime <= $rangeEnd;

        $result = $this->createQueryBuilder('B')
            ->select("B.status as enabled,DATE_FORMAT(B.createdAt,'%d-%m-%Y" .
                " %H:%i:%s') as version")
            ->innerJoin('B.requestedBy', 'R')
            ->orderBy('B.createdAt', 'DESC')
            ->getQuery()->getResult();
        if (isset($result[0])) {
            $checkout = (array)$result[0];
            $checkout['enabled'] = $checkoutIsActive;
            $checkout['dateStart'] = $rangeStart;
            $checkout['dateEnd'] = $rangeEnd;
            return $checkout;
        }

        throw new \InvalidArgumentException('Inicializar_canje');
    }

    /**
     * verifica si esta vacio log
     *
     * @return boolean
     */
    private function hasInit()
    {
        $isInit = false;
        $result = $this->createQueryBuilder('B')
            ->select("B.id, B.createdAt, R.id as userId, R.displayName, B.status")
            ->innerJoin('B.requestedBy', 'R')
            ->getQuery()->getResult();
        if (count($result) <= 0) {
            $isInit = true;
        }
        return $isInit;

    }

    /**
     * @param object $data
     * @param string $identity
     * @return boolean
     * @throws \InvalidArgumentException
     */
    public function create($data, $identity)
    {
        $user = $this->getUserByUsername($identity['user_id']);

        // Obtener los parámetros
        $dateStart = property_exists($data, 'date.start') ? $data->{"date.start"} : null;
        $dateEnd = property_exists($data, 'date.end') ? $data->{"date.end"} : null;

        // Al menos un parámetro debe existir
        if (is_null($dateStart) && is_null($dateEnd)) {
            throw new \InvalidArgumentException('Missing_Arguments');
        }

        // Validar rangos correctos
        if (!is_null($dateStart) && !is_null($dateEnd) && (int)$dateStart >= (int)$dateEnd) {
            throw new \InvalidArgumentException('Invalid_Range');
        }

        $currentTime = time();

        // Colocar rangos que vienen nulos
        $dateStart = is_null($dateStart) ? 0 : $dateStart;
        $dateEnd = is_null($dateEnd) ? (pow(2, 32) - 1) : $dateEnd;

        // Determinar si el canje será activado (dateStart enviado y fecha actual mayor o igual a fecha de canje)
        $enabled = !is_null($dateStart) && $currentTime >= $dateStart;
        $enabled = $enabled && (is_null($dateEnd) ? true : $currentTime < $dateEnd);

        if ($this->hasInit()) {
            if ($enabled) {
                return $this->insertLog($user, $dateStart, $dateEnd);
            } else {
                throw new \InvalidArgumentException('only_true');
            }
        } else {
            return $this->insertLog($user, $dateStart, $dateEnd);
        }
    }

    /**
     * Obtiene usuario mediante username
     *
{'fraction_non_alphanumeric': 0.14516542703257246, 'fraction_numerical': 0.0020518081559374197, 'mean_word_length': 2.4176161262050835, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6341701', 'n_tokens_mistral': 2352, 'n_tokens_neox': 2299, 'n_words': 495}