<?php

namespace Dgcl\ProjectsBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
/**
 * Ajax controller.
 *
 */
class AjaxController extends Controller
{

    public function selectAction(Request $request)
    {

        $parentEntity = $request->get('parentEntity');
        $chieldEntity = $request->get('chieldEntity');
        $idParent = $request->get('idParent');
        $idSecondParent = $request->get('idSecondParent',-1);
        $secondParent = $request->get('secondParent');
        $secondReferencedAttribute = $request->get('secondReferencedAttribute');
        $referencedAttribute = $request->get('referencedAttribute');
        $etatAttribute = $request->get('etatAttribute',NULL);
        $etats = $request->get('etats');
        $selected = $request->get('selected');
        
        if(count($etats)>0){
        $etats = explode('_', $etats);
        }

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

        $qb = $em->createQueryBuilder();

        $query = $qb->select('C')
                    ->from('DgclProjectsBundle:'.$chieldEntity,'C')
                    ->where('C.'.$referencedAttribute.' = :PARENT_ID') 
                    ->setParameter('PARENT_ID',$idParent);

        if($idSecondParent > 0){
             $query->andWhere('C.'.$secondReferencedAttribute.' = :SECOND_PARENT_ID') 
                    ->setParameter('SECOND_PARENT_ID',$idSecondParent);
        }       
        
        
        if($etatAttribute != null && !empty($etats)){
             $query->andWhere('C.'.$etatAttribute.' IN (:ETATS) ')
                   ->setParameter('ETATS',$etats);
        }

        // echo $query->getQuery()->getSql();die();
        $entities = $query->getQuery()->getResult();
        return $this->render('DgclProjectsBundle:Ajax:options.html.twig', array(
            'entities' => $entities,
            'selected'=> $selected
        ));

    }
    
}