<?php

namespace RxConnexionBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use RxConnexionBundle\Entity\GeneralUserEntity;
use RxConnexionBundle\Form\GeneralUserForm;

/**
 * @Route("")
 */
class GeneralUserController extends Controller
{
    /**
     * @Route("/general-user", name="general_user")
     */
    public function indexAction(Request $request)
    {
        if(!$this->isLoggedInGeneralUser()) return $this->redirectToLoginGeneralUser();

        return $this->render('@RxConnexion/GeneralUser/index.html.twig', array(
            'stylesheets' => array('css/main/main.css')
        ));
    }

    /**
     * @Route("/general-user-register", name="general_user_register")
     */
    public function registerAction(Request $request) {

        $em = $this->em();

        $addressData = array('country' => '', 'province' => '', 'city' => '');

        $options = array('action' => 'new');
        $generalUser = new GeneralUserEntity();
        $form = $this->createForm(new GeneralUserForm(), $generalUser, $options);

        $countries = $em->getRepository('RxConnexionBundle:CountryEntity')->findAll();

        $errors = array();

        if($request->getMethod() === 'POST') {

            $generalUser_form = $request->get($form->getName());

            $errors = $em->getRepository('RxConnexionBundle:GeneralUserEntity')->validate($generalUser_form, $request);

            if(!count($errors)) {

                $form->handleRequest($request);

                if($form->isValid()) {

                    $city = $em->getRepository('RxConnexionBundle:CityEntity')->find($request->get('city'));

                    $generalUser->setCity($city);
                    $em->persist($generalUser);
                    $em->flush();

                    return $this->render('RxConnexionBundle:GeneralUser:register_success.html.twig', array(
                        'generalUser' => $generalUser
                    ));

                } else {

                    $errors[] = 'Unexpected error encountered. Please try again.';
                }

            } else {

                $form->get('username')->setData($generalUser_form['username']);
                $form->get('first_name')->setData($generalUser_form['first_name']);
                $form->get('middle_name')->setData($generalUser_form['middle_name']);
                $form->get('last_name')->setData($generalUser_form['last_name']);
                $form->get('gender')->setData($generalUser_form['gender']);
                $form->get('birth_date')->setData($generalUser_form['birth_date']);
                $form->get('street')->setData($generalUser_form['street']);
                $form->get('zip_code')->setData($generalUser_form['zip_code']);
                $form->get('mobile_no')->setData($generalUser_form['mobile_no']);
                $form->get('mobile_no_two')->setData($generalUser_form['mobile_no_two']);
                $form->get('mobile_no_three')->setData($generalUser_form['mobile_no_three']);
                $form->get('phone_no')->setData($generalUser_form['phone_no']);
                $form->get('phone_no_two')->setData($generalUser_form['phone_no_two']);
                $form->get('phone_no_three')->setData($generalUser_form['phone_no_three']);
                $form->get('email')->setData($generalUser_form['email']);
                $form->get('email_two')->setData($generalUser_form['email_two']);
                $form->get('email_three')->setData($generalUser_form['email_three']);

                $addressData = array(
                    'country' => $request->get('country'),
                    'province' => $request->get('province'),
                    'city' => $request->get('city')
                );
            }
        }

        return $this->render('@RxConnexion/GeneralUser/register.html.twig', array(
            'stylesheets' => array('css/generalUser/register.css'),
            'form' => $form->createView(),
            'countries' => $countries,
            'errors' => $errors,
            'addressData' => $addressData
        ));

    }

    /**
     * @Route("/general-user-login", name="general_user_login")
     */
    public function loginAction(Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if($authService->isLoggedInGeneralUser()) return $this->redirect($this->generateUrl('general_user'), 302);

        $errors = array();

        if($request->getMethod() === 'POST') {

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

            $username = $request->get('username');
            $password = $request->get('password');


            $user = $em->getRepository('RxConnexionBundle:GeneralUserEntity')->findOneBy(array('username' => $username, 'isActive' => true));

            if($user && ($user->getPassword() === crypt(md5($password), $user->getPassword()) || $user->getPassword() === $password)) {
                $session = $this->get('session');

                $session->remove('generalUserData');

                $userData = array(
                    'id' => $user->getId(),
                    'username' => $user->getUsername(),
                    'firstName' => $user->getFirstName(),
                    'middleName' => $user->getMiddleName(),
                    'fullName' => $user->getFullName()
                );

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

                // 86400 = 1 day
                setcookie('generalUser_userId', $user->getId(), (time() +  (86400)));
                setcookie('generalUser_username', $user->getUsername(), (time() + (86400)));

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

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

    /**
     * @Route("/general-user-logout", name="general_user_logout")
     */
    public function logoutAction() {

        if(!$this->isLoggedInGeneralUser()) return $this->redirectToLoginGeneralUser();

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

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

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

        //return $this->redirectToLoginGeneralUser();

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