<?php
/*
 * Developer : John D'Alto (jdalto@yahoo.com)
 * Date : 9/1/2012
 * All code (c)2012 JLS Consulting, all rights reserved
 */

namespace Dorcas\TabithaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
//use Dorcas\TabithaBundle\Entity\Client;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
//use Dorcas\TabithaBundle\Form\Type\ClientInformationType;
use Dorcas\TabithaBundle\Form\Type\UsersType;
use Dorcas\TabithaBundle\Entity\Users;


class UsersController extends Controller
{
    function generatePassword($length=9, $strength=0) {
	$vowels = 'aeuyAEUY';
	$consonants = 'bdghjmnpqrstvzBDGHJLMNPQRSTVWXZ23456789@#$%';
//	if ($strength & 1) {
//		$consonants .= 'BDGHJLMNPQRSTVWXZ';
//	}
//	if ($strength & 2) {
//		$vowels .= "AEUY";
//	}
//	if ($strength & 4) {
//		$consonants .= '23456789';
//	}
//	if ($strength & 8) {
//		$consonants .= '@#$%';
//	}
 
	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}

    
    
    
    /**
     * Called by showAction from the form
     */
        public function newAction()
    {
        $user = new Users();
        $form   = $this->createForm(new UsersType(), $user);

        return $this->render('DorcasTabithaBundle:Users:userformaction.html.twig', array(
            'user' => $user,
            'form'   => $form->createView()
        ));
    }
    
        /**
     * Called by showAction from formtwo
     */
        public function renewAction($user)
    {
        $form   = $this->createForm(new UsersType(), $user);

        return $this->render('DorcasTabithaBundle:Users:userformaction.html.twig', array(
            'user' => $user,
            'form'   => $form->createView()
        ));
    }
    

    /**
     * Show a user entry
     */
    public function showAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
      
        $users = $em->getRepository('DorcasTabithaBundle:Users')
                   ->getUsers();

    return $this->render('DorcasTabithaBundle:Users:userform.html.twig', array(
        'users'  => $users
        ));
    }
    
    
      public function createAction()
    {
          echo "GOT HERE NOW 1";
        $user  = new Users();

        $request = $this->getRequest();
        $form    = $this->createForm(new UsersType(), $user);
        $form->bindRequest($request);
        
        $navnumber = $request->request->get("passnav");
        
         // Check to see if there is only one validation error
                // and if it is coming from the password field
                $validator = $this->get('validator');
                $errors = $validator->validate($user);
                $error = "";

                // Get the property path if there is only one error left
                if (count($errors) == 1) 
                {
                    $error = $errors[0]->getPropertyPath();
                }
            
        if ($form->isValid() || $error == 'password') {
            echo "GOT HERE NOW 2";
                $factory = $this->get('security.encoder_factory');
                $encoder = $factory->getEncoder($user);
                
                if( $error == 'password')
                {
                    // Set password to default
                    $genpassword = $this->generatePassword('8', '8');
                    $user->setPassword($genpassword);
                    $this->get('session')->setFlash('notice', 'The following password has been generated for you: ' . $genpassword );
                }
                $password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
                $user->setPassword($password);
                
                $em = $this->getDoctrine()
                       ->getEntityManager();
                $em->persist($user);
                $em->flush();
//            }

//            else  {
//                echo 'NAV = ' . $navnumber;
//              $this->get('session')->setFlash('notice', 'Please make sure you have entered a username before saving!');  
//            }
       
            switch ($navnumber) {
                        case 9:
                            return $this->redirect($this->generateUrl('DorcasTabithaBundle_homepage'));
                            break;
                        case 1:
                            return $this->redirect($this->generateUrl('DorcasTabithaBundle_clientinformation_show', array(
                        'client_id' => $client->getClientId())));
                            break;                  
                        case 2:
                            return $this->redirect($this->generateUrl('DorcasTabithaBundle_finance_show', array(
                        'client_id' => $client->getClientId())));
                            break;
                        case 3:
                            return $this->redirect($this->generateUrl('DorcasTabithaBundle_notes_show', array(
                        'client_id' => $client->getClientId())));
                            break;
                        case 4:
                            return $this->redirect($this->generateUrl('DorcasTabithaBundle_assistance_show', array(
                        'client_id' => $client->getClientId())));
                            break;
                        case "5":
                            return $this->redirect($this->generateUrl('DorcasTabithaBundle_referrals_show', array(
                        'client_id' => $client->getClientId())));
                            break;
                        case "6":
                            return $this->redirect($this->generateUrl('DorcasTabithaBundle_assistance_show', array(
                        'client_id' => $client->getClientId())));
                            break;
                        case "7":
                            return $this->redirect($this->generateUrl('DorcasTabithaBundle_users_show'));
                            break;
                        default:
                            return $this->redirect($this->generateUrl('DorcasTabithaBundle_users_show'));
                            break;
                    } 
            /*
            return $this->redirect($this->generateUrl('DorcasTabithaBundle_notes_show', array(
                'client_id' => $note->getClient()->getClientId())) . '#note-' . $note->getNoteId()
            ); */
        }
        
        $em = $this->getDoctrine()->getEntityManager();
      
        $users = $em->getRepository('DorcasTabithaBundle:Users')
                   ->getUsers();
        echo "GOT HERE NOW";
        return $this->render('DorcasTabithaBundle:Users:userformtwo.html.twig', array(
            'user' => $user,
            'users'=> $users,
            'form'    => $form->createView()
        ));
    }
    
     /**
     * Used by User EDIT
     */
        public function updateAction($id)
        {   
            $request = $this->get('request');

            if (is_null($id)) {
                $postData = $request->get('testimonial');
                $client_id = $postData['client_id'];
            }

            $em = $this->getDoctrine()->getEntityManager();
            $user = $em->getRepository('DorcasTabithaBundle:Users')->find($id);
            $oldpassword = $user->getPassword();
            $oldsalt = $user->getSalt();
            $form = $this->createForm(new UsersType(), $user);

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

//                if ($form->isValid()) {
               // Make sure that a password was entered and save to database
                    if($user->getPassword()){
                        $this->get('session')->setFlash('notice', 'Password has been changed!');
                        $factory = $this->get('security.encoder_factory');
                        $encoder = $factory->getEncoder($user);
                        $password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
                        $user->setPassword($password);
                    }
                    else {
                        // save the object with the original password to the database
                        $user->setPassword($oldpassword);
                        $user->setSalt($oldsalt);
                        $this->get('session')->setFlash('notice', 'No password was entered, so it was not changed!');
                    }
                    $em->persist($user);
                        $em->flush();
//                        $this->get('session')->setFlash('notice', 'Your edit has succeeded!');

                        // Exit now!  Window closing.
                        exit(true);



                    // Commented because I close the window right away
                   // return $this->render('DorcasTabithaBundle:Users:userformedit.html.twig', array(
                   // 'user'      => $user,
                   // 'form' => $form->createView(),
                   // ));
//                }

                 $this->get('session')->setFlash('notice', 'Your edit failed, please retry!');
                 // Exit now!  Window closing.
                exit(false);
            }
            return $this->render('DorcasTabithaBundle:Users:userformedit.html.twig', array(
            'user'      => $user,
            'form' => $form->createView(),
            ));
        }
        
        
        
      /**
        * Handles user delete requests
        */
    public function deleteAction($id)
    {
        // Get the URI of the previous REFERER
        $referer = $this->get('request')->server->get('HTTP_REFERER');

        // Set IsActive to false and save
        $em = $this->getDoctrine()->getEntityManager();
        $user = $em->getRepository('DorcasTabithaBundle:Users')->find($id);
        $user->setIsActive(false);
        $em->persist($user);
        $em->flush();

//            $this->get('session')->setFlash('notice', 'User has been Deleted!');

        // Redirect to REFERER
        return $this->redirect($referer);
    }
    
}
