<?php

namespace RxConnexionBundle\Controller;

use Firebase\JWT\JWT;
use RxConnexionBundle\Entity\LoginTrackerEntity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;

/**
 * @Route("")
 */
class LoginController extends Controller
{
    /**
     * @Route("/login", name="login")
     */
    public function indexAction(Request $request)
    {
        $authService = $this->get('rx_connexion.authService');
        if($authService->isLoggedIn()) return $this->redirect($this->generateUrl('main'), 302);
        $thenURI = $request->query->get('then');
        if($request->getMethod() === 'POST') {

            $em = $this->getDoctrine()->getManager();
            $session = $this->get('session');
            $session->clear();

            $accountNo = $request->get('account_no');
            $username = $request->get('username');
            $password = $request->get('password');
            $remember = $request->get('remember');
            if(!empty($accountNo) && $username != 'superadmin' ) {


                $userType = 'Account';
                $user = $em->getRepository('RxConnexionBundle:AccountUserEntity')->findOneBy(array('username' => $username, 'isActive' => true, 'isDeleted' => false));
                if($user && ($user->getPassword() === crypt(md5($password), $user->getPassword()) || $user->getPassword() === $password)) {

                    $userAccesses = $em->getRepository('RxConnexionBundle:UserAccessEntity')->findBy(array('type' => $user->getAccountUserType()->getDescription()));
                    $accesses = array();

                    foreach($userAccesses as $userAccess) {
                        $accesses[] = $userAccess->getDescription();
                    }

                    foreach($user->getUserOtherAccessesByType('Add') as $userOtherAccess) {
                        if(!in_array($userOtherAccess->getDescription(), $accesses)) {
                            $accesses[] = $userOtherAccess->getDescription();
                        }
                    }

                    $userOtherAccesses = $user->getUserOtherAccessesByType('Restrict');
                    if(count($userOtherAccesses)) {
                        foreach($userOtherAccesses as $userOtherAccess) {
                            if(FALSE !== $key = array_search($userOtherAccess->getDescription(), $accesses)) {
                                unset($accesses[$key]);
                            }
                        }
                        $accesses = array_values($accesses);
                    }

                    /*$branches = array();
                    $userBranches = $em->getRepository('RxConnexionBundle:AccountUserHealthFacilityEntity')->findBy(array('accountUser' => $user));
                    foreach($userBranches as $userBranch) {
                        $branches[] = $userBranch->getHealthFacility()->getId();
                    }*/
                    $branches = $user->getActiveHealthFacilityIdsAsArray();


                    $companies = $user->getActiveCompanyIdsAsArray();
                    $companyBranches = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->getHealthFacilityByCompanyId_toArray($companies);

                    $type = ($userType === 'System' ? $user->getType() : $user->getAccountUserType()->getDescription());
                    $userData = array(
                        'userType' => $userType,
                        'id' => $user->getId(),
                        'username' => $user->getUsername(),
                        'firstName' => $user->getFirstName(),
                        'middleName' => $user->getMiddleName(),
                        'fullName' => $user->getFullName(),
                        'type' => $type,
                        'accountId' => ($userType === 'System' ? 0 : $user->getAccountUserType()->getAccount()->getId()),
                        'accesses' => $accesses,
                        'branches' => $branches,
                        'company' => array(
                            'ids' => $companies,
                            'companyBranches' => $companyBranches,
                        ),
                        'ws_token' => JWT::encode(array(
                            'session' => md5(rand(0, 999) . '-' . time()),
                            'user_id' => $user->getId()
                        ), $this->container->getParameter('ws_key')),
                    );
                    if($type === 'Clinician' && $user->getProvider()){
                        $userData['providerId'] = base64_encode($user->getProvider()->getId());
                    }
                    $session->set('userData', $userData);

                    // 86400 = 1 day
                    //setcookie('userType', $userType, (time() + (86400)));
                    //setcookie('userId', $user->getId(), (time() +  (86400)));
                    //setcookie('username', $user->getUsername(), (time() + (86400)));
                    //setcookie('fullName', $user->getFullName(), (time() + (86400)));
                    $landingPage = $this->generateUrl('main');
                    switch($type){

                        case "Admin": (!$authService->isUserHasAccesses(array('Admin Management Dashboard'))) ? $landingPage = $this->generateUrl('main') : $landingPage = $this->generateUrl('management_dashboard'); break;
                        case "Super Admin": $landingPage = $this->generateUrl('report_status'); break;
                        case "MOA Manager": $landingPage = $this->generateUrl('main'); break;
                        case "MOA": $landingPage = $this->generateUrl('main'); break;
                        case "CBT - Operations Manager": $landingPage = $this->generateUrl('main'); break;
                        case "Finance": $landingPage = $this->generateUrl('patient'); break;
                        case "Marketing Staff": $landingPage = $this->generateUrl('patient'); break;
                        case "Clinician": $landingPage = $this->generateUrl('main'); break;
                    }
                    $url = !is_null($thenURI) && !empty($thenURI) ? $thenURI : $landingPage;
                    $response = new RedirectResponse($url);
                    $response->headers->setCookie(new Cookie('userType', $userType, (time() + (86400))));
                    $response->headers->setCookie(new Cookie('userId', $user->getId(), (time() + (86400))));
                    $response->headers->setCookie(new Cookie('username', $user->getUsername(), (time() + (86400))));
                    $response->headers->setCookie(new Cookie('fullName', $user->getFullName(), (time() + (86400))));
                    if(isset($remember)) {
                        $response->headers->setCookie(new Cookie('remUser', $user->getUsername(), strtotime('+1 year')));
                        $response->headers->setCookie(new Cookie('remPwd', $user->getPassword(), strtotime('+1 year')));
                    } else {
                        $response->headers->setCookie(new Cookie('remUser', null, -1));
                        $response->headers->setCookie(new Cookie('remPwd', null, -1));
                    }

                    //Insert to login tracker

//                    $test = $em->getReference('RxConnexionBundle:AccountUserEntity', $user->getId());
//                    var_dump($test->getId());
//                    die();
                    $loginTracker = new LoginTrackerEntity();
                    $loginTracker->setUsername($user->getUsername());
                    $loginTracker->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $user->getId()));
                    $loginTracker->setStartDate(date('Y-m-d h:i:s'));
                    $loginTracker->setNote(LoginTrackerEntity::STATUS_LOGIN);
                    $em->persist($loginTracker);
                    $em->flush();

                    $response->send();

                }else{
                    $this->get('session')->getFlashBag()->set('error_messages', 'Invalid username or password.');
                }
            } else {
                $userType = 'System';
                $user = $em->getRepository('RxConnexionBundle:UserEntity')->findOneBy(array('username' => $username, 'isActive' => true));
                if($user && ($user->getPassword() === crypt(md5($password), $user->getPassword()) || $user->getPassword() === $password)) {
                    $type = ($userType === 'System' ? $user->getType() : $user->getAccountUserType()->getDescription());
                    $userData = array(
                        'userType' => $userType,
                        'id' => $user->getId(),
                        'username' => $user->getUsername(),
                        'firstName' => $user->getFirstName(),
                        'middleName' => $user->getMiddleName(),
                        'fullName' => $user->getFullName(),
                        'type' => $type,
                        'accountId' => ($userType === 'System' ? 0 : $user->getAccountUserType()->getAccount()->getId()),
                        'ws_token' => JWT::encode(array(
                            'source' => 'rxconnexion',
                            'session' => md5(rand(0, 999) . '-' . time()),
                            'user_id' => $user->getId()
                        ), $this->container->getParameter('ws_key'))

                    );

                    $session->set('userData', $userData);

                    // 86400 = 1 day
                    //setcookie('userType', $userType, (time() + (86400)));
                    //setcookie('userId', $user->getId(), (time() +  (86400)));
                    //setcookie('username', $user->getUsername(), (time() + (86400)));
                    //setcookie('fullName', $user->getFullName(), (time() + (86400)));
                    $landingPage = $this->generateUrl('main');
                    switch($type){
                        case "Admin": $landingPage = $this->generateUrl('report_status'); break;
                        case "Super Admin": $landingPage = $this->generateUrl('report_status'); break;
                        case "MOA Manager": $landingPage = $this->generateUrl('main'); break;
                        case "MOA": $landingPage = $this->generateUrl('main'); break;
                        case "CBT - Operations Manager": $landingPage = $this->generateUrl('main'); break;
                        case "Finance": $landingPage = $this->generateUrl('patient'); break;
                        case "Marketing Staff": $landingPage = $this->generateUrl('patient'); break;
                        case "Clinician": $landingPage = $this->generateUrl('calendar_appointment'); break;
                    }
                    $url = !is_null($thenURI) && !empty($thenURI) ? $thenURI : $landingPage;
                    $response = new RedirectResponse($url);
                    $response->headers->setCookie(new Cookie('userType', $userType, (time() + (86400))));
                    $response->headers->setCookie(new Cookie('userId', $user->getId(), (time() + (86400))));
                    $response->headers->setCookie(new Cookie('username', $user->getUsername(), (time() + (86400))));
                    $response->headers->setCookie(new Cookie('fullName', $user->getFullName(), (time() + (86400))));
                    if(isset($remember)) {
                        $response->headers->setCookie(new Cookie('remUser', $user->getUsername(), strtotime('+1 year')));
                        $response->headers->setCookie(new Cookie('remPwd', $user->getPassword(), strtotime('+1 year')));
                    } else {
                        $response->headers->setCookie(new Cookie('remUser', null, -1));
                        $response->headers->setCookie(new Cookie('remPwd', null, -1));
                    }
                    $response->send();

                }else{
                    $this->get('session')->getFlashBag()->set('error_messages', 'Invalid username or password.');
                }
            }
        }

        return $this->render('@RxConnexion/Login/index.html.twig', array(
            'stylesheets' => array('rxconnexion/admin/css/auth/login.css'),
            'title' => 'Login',
            'thenUri' => $thenURI
        ));
    }

    /**
     * @Route("/logout", name="logout")
     */
    public function logoutAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();

        $em = $this->getDoctrine()->getManager();

        if($_COOKIE['username'] != 'superadmin') {
            //Insert to login tracker
            $loginTracker = new LoginTrackerEntity();
            $loginTracker->setUsername($_COOKIE['username']);
            $loginTracker->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $_COOKIE['userId']));
            $loginTracker->setStartDate(date('Y-m-d h:i:s'));
            $loginTracker->setNote(LoginTrackerEntity::STATUS_LOGOUT);
            $em->persist($loginTracker);
            $em->flush();
        }


        $this->get('session')->clear();

        if(isSet($_COOKIE['userId'])) {
            unset($_COOKIE['userId']);
            setcookie('userId', null, -1, '/');
        }

        if(isSet($_COOKIE['username'])) {
            unset($_COOKIE['username']);
            setcookie('username', null, -1, '/');
        }

        return $authService->redirectToLogin();

        //return $this->redirect($this->generateUrl('main'), 302);
    }
}
