<?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\AssistanceType;
use Dorcas\TabithaBundle\Entity\Assistance;
use Dorcas\TabithaBundle\Form\Type\AssistanceEditType;
use Dorcas\TabithaBundle\Entity\History;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Dorcas\TabithaBundle\Form\Type\AssistanceEditSPType;



class AssistanceController extends Controller
{
    protected function getClient($client_id)
    {
        $em = $this->getDoctrine()
                    ->getEntityManager();

        $client = $em->getRepository('DorcasTabithaBundle:Client')->find($client_id);

        if (!$client) {
            throw $this->createNotFoundException('Unable to find client.');
        }

        return $client;
    }
    
    /**
     * Render an assistance entry as New Assistance
     */
    public function newAction($client_id, $history)
    {
        $client = $this->getClient($client_id);
               
        $assistance = new Assistance();
        $assistance->setClient($client);
        $form   = $this->createForm(new AssistanceType(), $assistance);
        
        return $this->render('DorcasTabithaBundle:Assistance:assistanceformaction.html.twig', array(
            'assistance' => $assistance,
            'history' => $history,
            'form'   => $form->createView()
        ));
    }
    
    /**
     * Like newAction with refueling of fields of an assistance entry
     */
     public function renewAction($client_id, $history)
    {
        $client = $this->getClient($client_id);

        // New - Get fields from query - switched back to request and works!
        $request = $this->getRequest();
        $data = $request->request->all();
                            
        $assistance = new Assistance();
        $assistance->setClient($client);
        $form   = $this->createForm(new AssistanceType(), $assistance);

        
        // NEW - Add (Refuel) the fields back into the form
        if ($data != null) {

          if (isset($data['assistanceform']['food_given'])) $assistance->setFoodGiven(true);
           
          if ($data['assistanceform']['food_given_date']) 
          {
              $foodGivenDateString = $data['assistanceform']['food_given_date'];
              $dateTime = \Datetime::createfromformat('m/d/Y',$foodGivenDateString); 
              $assistance->setFoodGivenDate($dateTime);
          }
          // Fixed CheckPurpose dropdown - very cool - use as reference for joined tables
          $em = $this->getDoctrine()->getEntityManager();
          $checkpurpose = $em->getRepository('DorcasTabithaBundle:CheckPurpose')->find($data['assistanceform']['checkpurpose']);
          $assistance->setCheckpurpose($checkpurpose);

          if ($data['assistanceform']['checks_issued_date']) 
          {
              $checksIssuedDateString = $data['assistanceform']['checks_issued_date'];
              $dateTime = \Datetime::createfromformat('m/d/Y',$checksIssuedDateString); 
              $assistance->setChecksIssuedDate($dateTime);
          }
          $assistance->setChecksIssuedPayee($data['assistanceform']['checks_issued_payee']);
          
          if ($data['assistanceform']['check_dorcas'])  $assistance->setCheckDorcas($data['assistanceform']['check_dorcas']);
          if ($data['assistanceform']['check_oasis'])  $assistance->setCheckOasis($data['assistanceform']['check_oasis']);
          if ($data['assistanceform']['check_sfumc'])  $assistance->setCheckSfumc($data['assistanceform']['check_sfumc']);
          if ($data['assistanceform']['check_other'])  $assistance->setCheckOther($data['assistanceform']['check_other']);
          
          // Add refueling of the Special Programs fields
          if ($data['assistanceform']['special_program_check'])  $assistance->setSpecialProgramCheck($data['assistanceform']['special_program_check']);
          if ($data['assistanceform']['special_program_recipient_name'])  $assistance->setSpecialProgramRecipientName($data['assistanceform']['special_program_recipient_name']);
          if ($data['assistanceform']['special_program_parent_name'])  $assistance->setSpecialProgramParentName($data['assistanceform']['special_program_parent_name']);
          
          $specialprogram = $em->getRepository('DorcasTabithaBundle:SpecialProgram')->find($data['assistanceform']['special_program']);
          $assistance->setSpecialProgram($specialprogram);
          
          if ($data['assistanceform']['special_program_date']) 
          {
              $checksIssuedDateString = $data['assistanceform']['special_program_date'];
              $dateTime = \Datetime::createfromformat('m/d/Y',$checksIssuedDateString); 
              $assistance->setSpecialProgramDate($dateTime);
          }
          
          
          // Set into the form
         $form->setData($assistance);
        }

        return $this->render('DorcasTabithaBundle:Assistance:assistanceformaction.html.twig', array(
            'assistance' => $assistance,
            'history' => $history,
            'form'   => $form->createView()
        ));
    }

    /**
     * Show an assistance entry
     */
    public function showAction($client_id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $client = $em->getRepository('DorcasTabithaBundle:Client')->find($client_id);

        if (!$client) {
//            throw $this->createNotFoundException('Dorcas: Unable to find client.');
            return $this->redirect($this->generateUrl('DorcasTabithaBundle_clientinformation_new')
            );
        }
      
        $assistances = $em->getRepository('DorcasTabithaBundle:Assistance')
                   ->getAssistancesForClient($client->getClientId());
        
        $history = $em->getRepository('DorcasTabithaBundle:History')->findOneByClientid($client_id);

        
    return $this->render('DorcasTabithaBundle:Assistance:assistanceform.html.twig', array(
        'client'      => $client,
        'assistances'  => $assistances,
        'history'  => $history
        ));
    }
    
    
    public function createAction($client_id)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $client = $this->getClient($client_id);
        $history = $em->getRepository('DorcasTabithaBundle:History')->findOneByClientid($client_id);
        $assistance  = new Assistance();
        $assistance->setClient($client);
        $request = $this->getRequest();
        $form    = $this->createForm(new AssistanceType(), $assistance);       
        $form->bindRequest($request);
        
        // This was flipped to query to read GET instead of POST data - flipped back
        // because it was too easy for the user to refresh the page and create a duplicate record
        $navnumber = $request->request->get("passnav");
        
        // Check for Checks Issues dropdown not selected
        $ciDropdownSelected = true;
        if ($assistance->getCheckpurpose() && $assistance->getCheckpurpose()->getId() == 1 )
        {
            $ciDropdownSelected = false;
        }
        
         // Check for Special Programs dropdown not selected
        $spDropdownSelected = true;
        if ($assistance->getSpecialProgram() && $assistance->getSpecialProgram()->getId() == 1 )
        {
            $spDropdownSelected = false;
        }
        
       if (($form->isValid() && $ciDropdownSelected && !$spDropdownSelected && !$assistance->getSpecialProgramCheck())
               || ($form->isValid() && $ciDropdownSelected && ($spDropdownSelected && $assistance->getSpecialProgramCheck())) ) 
       {
            
            // Make sure at least one of these values were set
            if(($assistance->getFoodGiven() == true && $assistance->getFoodGivenDate()) || $assistance->getCheckDorcas()
                    || $assistance->getCheckOasis() || $assistance->getCheckOther() || $assistance->getCheckSfumc())
            {
                
//                echo 'AT STOP 1';
                $em = $this->getDoctrine()
                        ->getEntityManager();
                
                // Read Assistance table for existing record
                $duplicates = $em->getRepository('DorcasTabithaBundle:Assistance')
                    ->findBy(array('client_id' => $client_id, 
                        'checks_issued_payee' => $assistance->getChecksIssuedPayee(),
                        'check_dorcas' => $assistance->getCheckDorcas(),
                        'check_sfumc' => $assistance->getCheckSfumc(),
                        'check_oasis' => $assistance->getCheckOasis(),
                        'check_other' => $assistance->getCheckOther(),
                        'food_given' => $assistance->getFoodGiven(),
                        'food_given_date' => $assistance->getFoodGivenDate()),                        
                        array('created_dt' => 'DESC'));
                
                if ($duplicates)
                {
                    // get the newest record - see above sort DESC
                    $createddate = $duplicates[0]->getCreatedDt();
                    // Convert to string
                    $strcreateddt = $createddate->format('Y-m-d H:i:s');
//                    echo 'CREATED DATE = ' . $createddate->format('Y-m-d H:i:s');
                    // Convert to integer representation for diff
                    $intcreateddt = strtotime($strcreateddt);
                    // Get the date right now as string
                    $rightnow 	 = date('Y-m-d H:i:s');
//                    echo 'RIGHT NOW IT IS: ' . $rightnow;
                    // Convert to integer representation for diff
                    $intrightnow = strtotime($rightnow);
                    // Get number of seconds diff
                    $intdiff = $intrightnow - $intcreateddt;
//                    echo 'DIFF = ' . $intdiff;   
                }

                    // If there are duplicates and it has been more than 1 hour then save
                    if ($duplicates && $intdiff > 3600) 
                    {
                        $em->persist($assistance);
                        $em->flush();
//                        echo 'SAVED WITH DUPLICATES SINCE IT HAS BEEN MORE THAN 5 MINUTES';
                    }
                    // If no duplicates then save
                    else if(!$duplicates)
                    {
                        $em->persist($assistance);
                        $em->flush();
//                        echo 'SAVED - NO DUPLICATES';
                    }
                    else
                    {
//                        echo 'NOT SAVED' . $createddate->format('Y-m-d H:i:s');
                    }
                
                // Set valid flag 
                $valid = true;
            //    $this->get('session')->setFlash('notice', 'New assistance information has been saved!');
            }
            else if($navnumber == null) {
                $this->get('session')->setFlash('info', ' Your input was not saved, please see message below.');
                $this->get('session')->setFlash('notice', 'Please make sure you have checked the Food Given checkbox or added check amounts!');
            // Set valid flag 
                $valid = false;
                if (!$ciDropdownSelected) $this->get('session')->setFlash('notice', ' Please Select a Purpose.');
            }
       
            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_referrals_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_assistance_show', array(
//                        'client_id' => $client->getClientId())));
                           $em = $this->getDoctrine()->getEntityManager();
                            $assistances = $em->getRepository('DorcasTabithaBundle:Assistance')
                                    ->getAssistancesForClient($client->getClientId());
                            return $this->render('DorcasTabithaBundle:Assistance:assistanceform.html.twig', array(
                            'client'      => $client,
                            'assistances'  => $assistances,
                            'history'  => $history,
                            'form'   => $form->createView(),
                            'valid' => $valid
                            ));
                    } 
            
                    /*
            return $this->redirect($this->generateUrl('DorcasTabithaBundle_assistance_show', array(
                'client_id' => $assistance->getClient()->getClientId())) . '#assistance-' . $assistance->getAssistanceId()
            ); */
           
        }
        
        // Not Valid Page Logic
              
        // If none of these values were set, then it is okay to redirect
            if(($assistance->getFoodGiven() == false && !$assistance->getFoodGivenDate()) && !$assistance->getCheckDorcas()
                    && !$assistance->getCheckOasis() && !$assistance->getCheckOther() && !$assistance->getCheckSfumc()
                    && !$assistance->getSpecialProgramCheck() && $spDropdownSelected == false && $ciDropdownSelected ==false)
                {
//                echo 'AT STOP 2';
                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_referrals_show', array(
                        'client_id' => $client->getClientId())));
                            break;
                        case "7":
                            return $this->redirect($this->generateUrl('DorcasTabithaBundle_users_show'));
                            break;
                        default:
                            if (!$ciDropdownSelected) 
                                {
//                                    $this->get('session')->setFlash('notice', ' Please Select a Purpose.');
                                }
                           $em = $this->getDoctrine()->getEntityManager();
                            $assistances = $em->getRepository('DorcasTabithaBundle:Assistance')
                                    ->getAssistancesForClient($client->getClientId());
                            $this->get('session')->setFlash('info', ' Your input was not saved, please see message below.');
                            $concatmessage = "  Please enter at least one Checks Issued dollar amount(2).";
                                $this->get('session')->setFlash('notice', $concatmessage);
                            if (!$ciDropdownSelected)
                            {
                                $concatmessage .= "  Please Select a Purpose(2).\n";
                                $this->get('session')->setFlash('notice', $concatmessage);
                            }

                            
                            return $this->render('DorcasTabithaBundle:Assistance:assistanceform.html.twig', array(
                            'client'      => $client,
                            'assistances'  => $assistances,
                            'history'  => $history,
                            'form'   => $form->createView(),
                            'blockmessage'  => false,
                            ));
                    }             
            }
            // if Food Given fields were entered and others are not entered, then cut, save and redirect
            else if($assistance->getFoodGiven() == true && $assistance->getFoodGivenDate()&& !$assistance->getCheckDorcas()
                    && !$assistance->getCheckOasis() && !$assistance->getCheckOther() && !$assistance->getCheckSfumc()
                    && !$assistance->getChecksIssuedDate() && !$assistance->getChecksIssuedPayee() && $ciDropdownSelected == false
                    && !$assistance->getSpecialProgramCheck() && !$assistance->getSpecialProgramParentName() 
                    && !$assistance->getSpecialProgramRecipientName() && $spDropdownSelected == false) 
            {
//                echo 'AT STOP 3';
                    // set Purpose, Date and Payee to null and save
//                    $assistance->setChecksIssuedPayee(null);
//                    $assistance->setChecksIssuedDate(null);
                  //  $assistance->setCheckpurpose("");
                     $em = $this->getDoctrine()
                        ->getEntityManager();
                    $em->persist($assistance);
                    $em->flush();
                    
                    // redirect to another page
                    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_referrals_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_assistance_show', array(
                        'client_id' => $client->getClientId())));
                    } 
                }
          
            // if Special Programs required fields were entered and others are not entered, then cut, save and redirect
            else if($assistance->getSpecialProgramCheck() && $spDropdownSelected == true && !$assistance->getCheckDorcas()
                    && !$assistance->getCheckOasis() && !$assistance->getCheckOther() && !$assistance->getCheckSfumc()
                    && !$assistance->getChecksIssuedDate() && !$assistance->getChecksIssuedPayee() 
//                    && $assistance->getFoodGiven() == false && !$assistance->getFoodGivenDate()
                    )

            {
//                echo 'AT STOP 4';
                    // REDUNDANT - DECIDE WHAT TO DO -- set Purpose, Date and Payee to null and save
//                    $assistance->setChecksIssuedPayee(null);
//                    $assistance->setChecksIssuedDate(null);
                  //  $assistance->setCheckpurpose("");
                     $em = $this->getDoctrine()
                        ->getEntityManager();
                    $em->persist($assistance);
                    $em->flush();
                    
                    // redirect to another page
                    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_referrals_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_assistance_show', array(
                        'client_id' => $client->getClientId())));
                    } 
                }
/*               
                // Get here if none of the exceptions are true
//                echo 'AT STOP 5';
                $concatmessage = '';
                $this->get('session')->setFlash('info', ' Your input was not saved, please see message below.');
                if (!$form->isValid()) $blockmessage = false;
                if (!$spDropdownSelected && $assistance->getSpecialProgramCheck()) 
                {
                    $concatmessage = " Please Select a Special Programs Program(5).\n";
                    $this->get('session')->setFlash('notice', $concatmessage);
                    $blockmessage = true;
                }
                if (!$assistance->getSpecialProgramCheck() && $spDropdownSelected)
                {
                    $concatmessage .= " Please enter a Special Program Amount(5). \r\n";
                    $this->get('session')->setFlash('notice', $concatmessage);
                    $blockmessage = true;
                }
                if ($ciDropdownSelected || $assistance->getChecksIssuedDate() || $assistance->getChecksIssuedPayee()) 
                {          
                    $blockmessage = false;
                    if (!$ciDropdownSelected) 
                    {
                        $concatmessage .= "  Please Select a Purpose(5).\n";
                        $this->get('session')->setFlash('notice', $concatmessage);
                    }
                }   
                if (($assistance->getChecksIssuedPayee() || $assistance->getChecksIssuedDate() || $ciDropdownSelected) && !$assistance->getCheckDorcas() && !$assistance->getCheckOasis() && !$assistance->getCheckOther() && !$assistance->getCheckSfumc())   
                {
                    $concatmessage .= "  Please enter at least one Checks Issued dollar amount(5).\n";
                    $this->get('session')->setFlash('notice', $concatmessage);
                }
//                if ($form->isValid() && $spDropdownSelected) 
//                {
//                    $concatmessage .= " Please UnSelect the Special Programs Program.\n";
//                    $this->get('session')->setFlash('notice', $concatmessage);
//                }
//                if ($form->isValid() && $assistance->getSpecialProgramCheck())
//                {
//                    $concatmessage .= " Please clear the Special Programs Amount.\n";
//                    $this->get('session')->setFlash('notice', $concatmessage);
//                }
*/               
               $blockmessage = false;
                echo "If you see this message please tell John -> Assistance Controller has no step for this validation (step 5)!";
                $em = $this->getDoctrine()->getEntityManager();
                $assistances = $em->getRepository('DorcasTabithaBundle:Assistance')
                        ->getAssistancesForClient($client->getClientId());
                return $this->render('DorcasTabithaBundle:Assistance:assistanceform.html.twig', array(
                'client'      => $client,
                'assistances'  => $assistances,
                'history'  => $history,
                'form'   => $form->createView(),
                'blockmessage'  => $blockmessage,
                ));     
    }
    
    
    /**
     * Used by Assistance EDIT for Checks Issued
     */
        public function updateAction($assistance_id)
        {   
            $request = $this->get('request');

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

            $em = $this->getDoctrine()->getEntityManager();
            $assistance = $em->getRepository('DorcasTabithaBundle:Assistance')->find($assistance_id);
            $form = $this->createForm(new AssistanceEditType(), $assistance);

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

                if ($form->isValid()) {
                    // save the object to the database
                    $em->flush();

                    $this->get('session')->setFlash('info', 'Your edit has succeeded!');

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

                    
//                    return $this->redirect($this->generateUrl('DorcasTabithaBundle_assistance_show', array(
//                        'client_id' => $client->getClientId())));
//                     Commented because I close the window right away
//                    return $this->render('DorcasTabithaBundle:Assistance:assistanceformedit.html.twig', array(
//                    'assistance'      => $assistance,
//                    'form' => $form->createView(),
//                    ));
                }
                 $this->get('session')->setFlash('info', 'Your edit failed, please retry!');
                 // Exit now!  Window closing.
                exit();
            }
            return $this->render('DorcasTabithaBundle:Assistance:assistanceformedit.html.twig', array(
            'assistance'      => $assistance,
            'form' => $form->createView(),
            ));
        }
        
            
    /**
     * Used by Assistance EDIT for Special Programs
     */
        public function updatespAction($assistance_id)
        {   
            $request = $this->get('request');

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

            $em = $this->getDoctrine()->getEntityManager();
            $assistance = $em->getRepository('DorcasTabithaBundle:Assistance')->find($assistance_id);
            $form = $this->createForm(new AssistanceEditSPType(), $assistance);

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

//                if ($form->isValid()) {
                    // save the object to the database
                    $em->flush();

                    $this->get('session')->setFlash('info', 'Your edit has succeeded!');

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

                    
//                    return $this->redirect($this->generateUrl('DorcasTabithaBundle_assistance_show', array(
//                        'client_id' => $client->getClientId())));
//                     Commented because I close the window right away
//                    return $this->render('DorcasTabithaBundle:Assistance:assistanceformedit.html.twig', array(
//                    'assistance'      => $assistance,
//                    'form' => $form->createView(),
//                    ));
//                }
//                 $this->get('session')->setFlash('notice', 'Your edit failed, please retry!');
                 // Exit now!  Window closing.
//                exit();
            }
            return $this->render('DorcasTabithaBundle:Assistance:assistanceformeditsp.html.twig', array(
            'assistance'      => $assistance,
            'form' => $form->createView(),
            ));
        }
        
      /**
        * Handles Checks Issued delete requests
        */
    public function deleteCheckAction($assistance_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();
        $assistance = $em->getRepository('DorcasTabithaBundle:Assistance')->find($assistance_id);
        $assistance->setIsActiveCheck(false);
        $em->persist($assistance);
        $em->flush();

        // Redirect to REFERER
        return $this->redirect($referer);
    }
    
     /**
        * Handles Food Given delete requests
        */
    public function deleteFoodAction($assistance_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();
        $assistance = $em->getRepository('DorcasTabithaBundle:Assistance')->find($assistance_id);
        $assistance->setIsActiveFood(false);
        $em->persist($assistance);
        $em->flush();

        // Redirect to REFERER
        return $this->redirect($referer);
    }
    
         /**
        * Handles Food Given delete requests
        */
    public function deleteProgramAction($assistance_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();
        $assistance = $em->getRepository('DorcasTabithaBundle:Assistance')->find($assistance_id);
        $assistance->setIsActiveProgram(false);
        $em->persist($assistance);
        $em->flush();

        // Redirect to REFERER
        return $this->redirect($referer);
    }
    
    /**
        * Handles History delete requests
        */
    public function deleteHistoryAction($history_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();
        $history = $em->getRepository('DorcasTabithaBundle:History')->find($history_id);
        $history->setIsActive(false);
        $em->persist($history);
        $em->flush();

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