<?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\SearchType;
//use Dorcas\TabithaBundle\Form\Type\AssistanceType;
//use Dorcas\TabithaBundle\Entity\Assistance;
//use Dorcas\TabithaBundle\Form\Type\AssistanceEditType;
//use Dorcas\TabithaBundle\Entity\History;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Doctrine\ORM\PersistentCollection;

/**
 * @Route("/ajax")
 */
class SearchController extends Controller
{
    

        public function showAction()
        {
            return $this->render('DorcasTabithaBundle:Search:searchform.html.twig');
        }

    
        public function newAction()
        {
            $client = new Client();
            $form   = $this->createForm(new SearchType(), $client);

            return $this->render('DorcasTabithaBundle:Search:searchformaction.html.twig', array(
                'client' => $client,
                'form'   => $form->createView()
            ));
        }
    
        public function renewAction()
        {
            $client = new Client();
//            $request = $this->getRequest();
            $request = Request::createFromGlobals();
            $form = $this->createForm(new SearchType(), $client);
       
//            $data = $request->request->all();
            $data = $request->query->all();
            if (isset($data['clientinformationform']['ssn'])) $client->setSsn($data['clientinformationform']['ssn']);
            if (isset($data['clientinformationform']['last_name'])) $client->setLastName($data['clientinformationform']['last_name']);
            if (isset($data['clientinformationform']['first_name'])) $client->setFirstName($data['clientinformationform']['first_name']);
            if (isset($data['clientinformationform']['alias'])) $client->setAlias($data['clientinformationform']['alias']);
            if (isset($data['clientinformationform']['current_address'])) $client->setCurrentAddress($data['clientinformationform']['current_address']);
            if (isset($data['clientinformationform']['prev_address1']))  $client->setPrevAddress1($data['clientinformationform']['prev_address1']);
            if (isset($data['clientinformationform']['other_adult_oneLastName'])) $client->setOtherAdultOneLastName($data['clientinformationform']['other_adult_oneLastName']);
            if (isset($data['clientinformationform']['other_adult_oneFirstName'])) $client->setOtherAdultOneFirstName($data['clientinformationform']['other_adult_oneFirstName']);
            if (isset($data['clientinformationform']['other_adult_twoLastName'])) $client->setOtherAdultTwoLastName($data['clientinformationform']['other_adult_twoLastName']);
            if (isset($data['clientinformationform']['other_adult_twoFirstName'])) $client->setOtherAdultTwoFirstName($data['clientinformationform']['other_adult_twoFirstName']);

            $form->setData($client);
//            }

            return $this->render('DorcasTabithaBundle:Search:searchformaction.html.twig', array(
                'form'   => $form->createView()
            ));
        }
        
        /**
        * Handles search requests
        */
        public function createAction($allrecs)
        {         
            $client  = new Client();

            $request = $this->getRequest();
            $form    = $this->createForm(new SearchType(), $client);
            $form->bindRequest($request);
            

            /* Array of database columns which should be read and sent back to DataTables. Use a space where
            * you want to insert a non-database field (for example a counter or static image)
            */
            $columns = array(   'is_active', // do not change this one - not searched - not displayed
                                'client_id', // not searched - not displayed
                                'ssn',
                                'last_name',
                                'first_name',
                                'alias',
                                'current_address',
                                'prev_address1',
                                'other_adult_oneLastName',
                                'other_adult_oneFirstName',
                                'other_adult_twoLastName',
                                'other_adult_twoFirstName',
                                'email'
                );
            $get['columns'] = &$columns;

            // STATIC SETTINGS usually passed from POST Request
            $get['sSearch_1'] = '10';
            $get['sSearch_2'] = $client->getSsn();
            $get['sSearch_3'] = $client->getLastName();
            $get['sSearch_4'] = $client->getFirstName();
            $get['sSearch_5'] = $client->getAlias();
            $get['sSearch_6'] = $client->getCurrentAddress();
            $get['sSearch_7'] = $client->getPrevAddress1();
            $get['sSearch_8'] = $client->getotheradultonelastname();
            $get['sSearch_9'] = $client->getotheradultonefirstname();
            $get['sSearch_10'] = $client->getotheradulttwolastname();
            $get['sSearch_11'] = $client->getotheradulttwofirstname();
            $get['bSearchable_0'] = false;
            $get['bSearchable_1'] = false;
            $get['bSearchable_2'] = true;
            $get['bSearchable_3'] = true;
            $get['bSearchable_4'] = true;
            $get['bSearchable_5'] = true;
            $get['bSearchable_6'] = true;
            $get['bSearchable_7'] = true;
            $get['bSearchable_8'] = true;
            $get['bSearchable_9'] = true;
            $get['bSearchable_10'] = true;
            $get['bSearchable_11'] = true;
            $get['bSearchable_12'] = false;

            // Show all records?
            if ($allrecs == 'false')
            {
                $get['iDisplayStart'] = 0;
                $get['iDisplayLength'] = 100;
            }

            // Get Matching Records
            $em = $this->getDoctrine()->getEntityManager();
            $rResult = $em->getRepository('DorcasTabithaBundle:Client')->clientSearch($get, true, false)->getArrayResult();

            // Get record count unlimited
            $rResultCount = ($em->getRepository('DorcasTabithaBundle:Client')->clientSearch($get, true, true)->getSingleResult());
            $iUnFilteredTotal = $rResultCount[1];
            
            /* Data set length after filtering */
            $iFilteredTotal = count($rResult);

            return $this->render('DorcasTabithaBundle:Search:searchformtwo.html.twig', array(
                'clients'  => $rResult,
                'numberrecords' => $iFilteredTotal,
                'allnumberrecords' => $iUnFilteredTotal,
                'form'    => $form->createView()
                ));

            //
            // The rest of this creates the JSON output that we are not using
            //


            /*
            * Output
            */
            $output = array(
            //"sEcho" => intval($get['client_id']),
            "iTotalRecords" => $em->getRepository('DorcasTabithaBundle:Client')->getCount(),
            "iTotalDisplayRecords" => $iFilteredTotal,
            "aaData" => array()
            );

            foreach($rResult as $aRow)
            {
            $row = array();
            for ( $i=0 ; $i<count($columns) ; $i++ ){
                if ( $columns[$i] == "version" ){
                /* Special output formatting for 'version' column */
                $row[] = ($aRow[ $columns[$i] ]=="0") ? '-' : $aRow[ $columns[$i] ];
                }elseif ( $columns[$i] != ' ' ){
                /* General output */
                $row[] = $aRow[ $columns[$i] ];
                }
            }
            $output['aaData'][] = $row;
            }

            unset($rResult);

            return new Response(
            json_encode($output)
            );


                    echo "SHOULD NEVER GET HERE";
                    return $this->render('DorcasTabithaBundle:Search:searchform.html.twig', array(
        //                'user' => $user,
        //                'users'=> $users,
                        'form'    => $form->createView()
            ));
    }
    
        /**
        * Handles client delete requests
        */
        public function deleteAction($client_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();
            $client = $em->getRepository('DorcasTabithaBundle:Client')->find($client_id);
            $client->setIsActive(false);
            $em->persist($client);
            $em->flush();
            
//            $this->get('session')->setFlash('notice', 'Client has been Deleted!');
            
            // Redirect to REFERER
            return $this->redirect($referer);
        }
    
}
