<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace LifeStyle\SamlAuthBundle\Database\Data\UserLoginHistory;

use LifeStyle\SamlAuthBundle\Database\Manager as DbManger;
use LifeStyle\SamlAuthBundle\Security\User\SamlUser;
use LifeStyle\SamlAuthBundle\Entity\UserLoginHistory;

/**
 * Class Index
 * @package LifeStyle\SamlAuthBundle\Database\Data\UserLoginHistory
 */
class Index
{
    /**
     * @var DbManger
     */
    private $dbM;

    /**
     * Factory constructor.
     * @param DbManger $dbM
     */
    public function __construct(DbManger $dbM)
    {
        $this->dbM = $dbM;
    }

    /**
     * @param string $keyId
     * @param int $lastXMonth
     * @return array
     * @throws \Exception
     */
    public function getUserLoginHistoryByUserId($keyId, $lastXMonth = 6)
    {
        $dbUser = $this->dbM->repository()->user()->findOneBy(['keyId' => $keyId]);

        if (null === $dbUser) {
            return [];
        }

        $localUserId = $dbUser->getId();

        $loginHistoryArray = [];

        $monthCounter = 0;
        while ($lastXMonth > 0) {
            $lastDayThisMonth = new \DateTime('last day of this month');
            $manDateTo = $lastDayThisMonth->sub(new \DateInterval('P'.$monthCounter.'M'));
            $dateFrom = new \DateTime($manDateTo->format("Y")."-".$manDateTo->format("m")."-01");
            $dateTo = $manDateTo;
            $loginHistoryArray[$manDateTo->format("F")." ".$manDateTo->format("Y")] = $this->getUserHistoryEntries(
                $localUserId,
                $dateFrom,
                $dateTo
            );

            $monthCounter++;
            $lastXMonth--;
        }
        return $loginHistoryArray;
    }

    /**
     * @param SamlUser $user
     * @param int $lastXMonth
     * @return array
     * @throws \Exception
     */
    public function getUserLoginHistory(SamlUser $user, $lastXMonth = 6)
    {
        $dbUser = $this->dbM->repository()->user()->findOneBy(['userGuid' => $user->getUserSamlData()->getUserGuid()]);
        if (null === $dbUser) {
            return [];
        }

        $localUserId = $dbUser->getId();

        $loginHistoryArray = [];

        $monthCounter = 0;
        while ($lastXMonth > 0) {
            $lastDayThisMonth = new \DateTime('last day of this month');
            $manDateTo = $lastDayThisMonth->sub(new \DateInterval('P'.$monthCounter.'M'));
            $dateFrom = new \DateTime($manDateTo->format("Y")."-".$manDateTo->format("m")."-01");
            $dateTo = $manDateTo;
            $loginHistoryArray[$manDateTo->format("F")." ".$manDateTo->format("Y")] = $this->getUserHistoryEntries(
                $localUserId,
                $dateFrom,
                $dateTo
            );

            $monthCounter++;
            $lastXMonth--;
        }

        return $loginHistoryArray;
    }


    /**
     * @param $localUserId
     * @param \DateTime $dateFrom
     * @param \DateTime $dateTo
     * @return array
     */
    private function getUserHistoryEntries($localUserId, \DateTime $dateFrom, \DateTime $dateTo)
    {

        $query = $this->dbM->getEntityManager()->createQueryBuilder();

        $query->select('uh')
            ->from('LifeStyleSamlAuthBundle:UserLoginHistory', 'uh')
            ->where('uh.localUserId = :localUserId')
            ->andWhere('uh.lastLoginAt BETWEEN :dateFrom AND :dateTo')
            ->orderBy('uh.lastLoginAt', 'DESC')
            ->setParameter('localUserId', $localUserId)
            ->setParameter('dateFrom', $dateFrom)
            ->setParameter('dateTo', $dateTo);

        return $query->getQuery()->getArrayResult();
    }
}
