<?php

namespace Actigraph\ActipageBaseBundle\Controller;

use Actigraph\ActipageBaseBundle\Services\Account\AccountService;
use Actigraph\ActipageBaseBundle\Services\CaptchaService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class AccountController extends AbstractController
{
    public function index(Request $request, SessionInterface $session, AccountService $accountService)
    {
        if ($session->get('accountId') === null) {
            return $this->forward('Actigraph\ActipageBaseBundle\Controller\AccountController::login');
        }
        if ($request->get('req') == 'logout') {
            $session->set('accountId', null);

            return $this->redirect('/');
        }

        $user = $accountService->getUser();

        return $this->render('@ActigraphActipageBaseBundle/Modules/Account/index.html.twig', [
            'user' => $user,
        ]);
    }

    public function login(SessionInterface $session, Request $request, AccountService $accountService, CaptchaService $captcha)
    {
        if ($session->get('accountId') !== null) {
            return $this->forward('Actigraph\ActipageBaseBundle\Controller\AccountController::index');
        }


        if ($accountService->getType() == 'form') {
            if ($request->getMethod() == 'POST') {
                if ($captcha->isCaptchaValid($request->request->all())) {
                    $user = $accountService->checkLogin($request->request->all());
                    if ($user != false) {
                        $accountService->login($user);

                        if ($session->get('loginReferer')) {
                            $referer = $session->get('loginReferer');
                            $session->remove('loginReferer');

                            return $this->redirect($referer);
                        }

                        return $this->forward('Actigraph\ActipageBaseBundle\Controller\AccountController::index');
                    } else {
                        $this->addFlash('danger', $accountService->getError());
                    }
                } else {
                    $this->addFlash('danger', 'Vous devez compléter le captcha.');
                }
            }

            return $this->render('@ActigraphActipageBase/Modules/Account/login.html.twig', [

            ]);
        } elseif ($accountService->getType() == 'api') {
            // SETRAM CIAM
            // TADAO SSO
        }

        throw new \Exception('unknown login account type');
    }
}
