<?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\Controller;

use LifeStyle\ActivityLogBundle\Annotation\ActivityLog;
use LifeStyle\SamlAuthBundle\Security\User\SamlUser;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use JMS\SecurityExtraBundle\Annotation\Secure;
use JMS\DiExtraBundle\Annotation as DI;
use LifeStyle\SamlAuthBundle\Form;
use LifeStyle\SamlAuthBundle\Database\Manager as SamlDbM;
use LifeStyle\SamlAuthBundle\Services\SamlService;

/**
 * Class AdminController
 * @package LifeStyle\SamlAuthBundle\Controller
 *
 * @ActivityLog(type="superadmin")
 */
class AdminController extends Controller
{
    /**
     * @DI\Inject("saml.saml_service")
     * @var SamlService
     */
    protected $saml;

    /**
     * @DI\Inject("saml.saml_database_manager")
     * @var SamlDbM
     */
    protected $samlDbM;

    /**
     * @Route("/logout", name="saml_backend_user_logout")
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function logoutAction()
    {
        if ($this->saml->getSimpleSaml()->isAuthenticated()) {
            $this->saml->getSimpleSaml()->logout();
        }
        //redirect to dashboard so to idp again
        return  $this->redirectToRoute('_admin_backend_index', array(), 301);
    }

    /**
     * @Secure(roles="ROLE_USER")
     * @Route("/current/profile", name="saml_backend_user_current_profile")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function currentProfileAction()
    {
        $currentUser = $this->getUser();
        $isSamlUser = false;
        if($currentUser instanceof SamlUser){
            $isSamlUser = true;
        }
        return  $this->render(
            '@LifeStyleSamlAuth/Admin/current_profile.html.twig',
            [
                'isSamlUser' => $isSamlUser,
                'currentUser' => $currentUser
            ]
        );
    }

    /**
     * @Secure(roles="ROLE_SUPER_ADMIN_EXTENDED")
     *
     * @Route("/saml/auth/user/log", name="admin_saml_auth_user_log")
     * @Template()
     * @return array
     */
    public function userLogAction(Request $request)
    {
        $filterBuilder = $this->samlDbM->repository()->user()->createQueryBuilder('a');
        $form = $this->get('form.factory')->create(Form\Filter\UserLog::class);

        if ($request->query->has($form->getName())) {
            $form->submit($request->query->get($form->getName()));
            $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $filterBuilder);
        }
        $query = $filterBuilder->getQuery();
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate($query, $request->query->get('page', 1), 10);

        return ['form' => $form->createView(), 'pagination' => $pagination];
    }

    /**
     * @Secure(roles="ROLE_SUPER_ADMIN_EXTENDED")
     *
     * @Route("/saml/auth/user/log/show/{keyId}", name="admin_saml_auth_user_log_show")
     * @Template()
     * @return array
     * @throws \Exception
     */
    public function userLogShowAction(Request $request, $keyId)
    {
        $userEntity = $this->samlDbM->repository()->user()->find($keyId);
        if (null !== $userEntity) {
            return [
                'userLogEntity' => $userEntity,
                'userLoginHistory' => $this->samlDbM->data()->userLoginHistory()->getUserLoginHistoryByUserId(
                    $userEntity->getId()
                ),
            ];
        }

        unset($request);
        return ['userLogEntity' => false, 'userLoginHistory' => false];
    }
}
