<?php

namespace AppBundle\Controller;

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller,
    Symfony\Component\HttpFoundation\Request,
    Symfony\Component\HttpFoundation\Response,
    DateTime,
	AppBundle\Entity\Event,
	AppBundle\Entity\Applicant,
	AppBundle\Entity\Job;

class FormController extends Controller
{
    
    public function submitAction(Request $request)
    {
        $keys = array(
            "enterprise",
            "name",
            "surname",
            "function",
            "email",
            "message"
        );
        $result = $this->checkForm($keys,$request);
        return new Response($result);
    }
	
    public function addEventAction(Request $request)
    {
		 return $this->createEvent($request);
    }
	
    public function addJobAction(Request $request)
    {
		return $this->createJob($request);
    }
	
    public function addApplicantAction(Request $request)
    {
        return $this->createApplicant($request);
    }    
	
	public function addApplicant2Action(Request $request)
    {
       echo "jjjjj";
	   return new Response();
    }    
	
    protected function checkForm($keys,$request)
    {
        //$request = $this->getRequest();
        if ($request->getMethod() == 'POST') {
            $message = array();
            $data = $request->request->all();
            foreach( $keys as $key ) {
                if( !isset($data[$key]) ) {
                    return "KO";
                }
				if($data[$key]["value"]!=""){
					$message[] = strip_tags($data[$key]["name"]) . ":";
					$message[] = strip_tags($data[$key]["value"]);
					$message[] = "";
				}
            }
			$html = implode (" <br /> " , $message );
            $message = \Swift_Message::newInstance()
                ->setSubject('Contact Formulaire Healthvalley')
                ->setFrom('info@republic-of-innovation.org')
				->setTo(array('juliette.lemaignen@inartis.ch','f.rousseaux74@gmail.com'))
                // ->setTo('info@nextrends.ch')
                // ->setTo('romain@messaggio.agency')
                ->setBody($html, 'text/html')
            ;
            $this->get('mailer')->send($message);
            return "OK";
        }
        return "KO";
    }

	
	protected function createEvent($request)
    {
        $data=$request->request->all();
        if ($request->getMethod() == 'POST') {
			$date=  explode ("/" ,$data['date']["value"]);
			$ev= new Event();
			$ev	->setTitle($data['name']["value"])
				->setDateStart(new \DateTime($date[1].'/'.$date[0].'/'.$date[2].'T'.$data['hour']["value"].':'.$data['minute']["value"]));
			
			$date= explode ("/" ,$data['dateEnd']["value"]);	
			if($date[0]!=''){
				$ev	->setDateEnd(new \DateTime($date[1].'/'.$date[0].'/'.$date[2].'T'.$data['hourEnd']["value"].':'.$data['minuteEnd']["value"]));
			}
			
			$ev ->setDescription($data['description']["value"])
				->setLatLng($data['latlng']["value"]);
			if(isset($data['route']))	
			$ev	->setStreet($data['route']["value"]);
			if(isset($data['street_number']))
			$ev ->setNumber($data['street_number']["value"]);
			if(isset($data['postal_code']))
			$ev	->setZip($data['postal_code']["value"]);
			if(isset($data['locality']))
			$ev	->setCity($data['locality']["value"]);
			$ev->setOrganizer($data['organizer']["value"])
				->setRegistration($data['registration']["value"])
				->setLink($data['eventform_link']["value"])
				->setPrice($data['price']["value"])
				->setAuthorname($data['eventform_name']["value"])
				->setAuthoremail($data['eventform_email']["value"])
				->setAuthorphonenumber($data['eventform_phoneNumber']["value"])
				->setPublished(false);
			$em = $this->getDoctrine()->getManager();
			$repository = $em->getRepository('AppBundle:Event');
			$em->persist($ev); 
			$em->flush();
			
			$route = $this->get('router')->generate('admin_app_event_edit', 
			array("_sonata_admin" => "admin.event", "_sonata_name" => "admin_app_event_edit", "id" => $ev->getId(),UrlGeneratorInterface::ABSOLUTE_URL)
			);
			
			 $html = "<p>Vous venez de recevoir un événement à valider sur <a href='http://www.republic-of-innovation.org/HealthValley/admin'>Health Valley</a></p> <p>Evenement : <strong>".$ev->getTitle()."</strong>, le ".$ev->getDateStart()->format('d/m/Y')."<br />".$ev->getDescription()."</p><p>Par <strong>".$ev->getAuthorname()."</strong>, ".$ev->getAuthoremail()."</p>";
				$message = \Swift_Message::newInstance()
				  ->setSubject('Vous avez reçu un événement sur Healthvalley')
                ->setFrom('info@republic-of-innovation.org')
  				->setTo(array('juliette.lemaignen@inartis.ch','f.rousseaux74@gmail.com'))
                // ->setTo('info@nextrends.ch')
                // ->setTo('romain@messaggio.agency')
                ->setBody($html, 'text/html')
            ;
            $this->get('mailer')->send($message);
		
			return new Response('Saved new product with id '.$ev->getId().'! Lien :'.$route);
        }
        return  new Response("KO");
    }
	
	
	protected function createJob($request)
    {
		
        $data=$request->request->all();
        if ($request->getMethod() == 'POST') {
			$date=  explode ("/" ,$data['jobform_date']["value"]);
			$ev= new Job();
			$ev	->setName($data['jobform_name']["value"])
				->setDeadline(new \DateTime($date[1].'/'.$date[0].'/'.$date[2]))
				->setJobDescription($data['jobform_description']["value"])
				->setLatLng($data['latlng']["value"]);
			if(isset($data['route']))	
			$ev	->setStreet($data['route']["value"]);
			if(isset($data['street_number']))
			$ev ->setNumber($data['street_number']["value"]);
			if(isset($data['postal_code']))
			$ev	->setZip($data['postal_code']["value"]);
			if(isset($data['locality']))
			$ev	->setCity($data['locality']["value"])
    			->setContact($data['jobform_contact']["value"])
    			->setCompany($data['jobform_enterprise']["value"])
    			->setCompanyDescription($data['jobform_company_description']["value"])
    			->setFonction($data['jobform_function']["value"])
    			->setSector($data['jobform_sector']["value"])
				->setContact($data['jobform_authorname']["value"])
				->setAuthorphonenumber($data['jobform_phoneNumber']["value"])
				->setPublished(false);
			$em = $this->getDoctrine()->getManager();
			$repository = $em->getRepository('AppBundle:Job');
			$em->persist($ev); 
			$em->flush();
			
			$route =$this->get('router')->generate('admin_app_job_edit', 
			array("_sonata_admin" => "admin.job", "_sonata_name" => "admin_app_job_edit", "id" => $ev->getId()), UrlGeneratorInterface::ABSOLUTE_URL
			);
			
				$html = "<p>Vous venez de recevoir une proposition d'emploi à publier sur <a href='http://www.republic-of-innovation.org/HealthValley/admin'>Health Valley</a></p><p>Offre : <strong>".$ev->getName()."</strong>, dans l'entreprise <strong>".$ev->getCompany()."</strong> ( ".$ev->getContact()." )<br /> Cette proposition n'apparaitera pas tant que vous n'aurez pas choisi de la publier via <a href='".$route."'>l'interface administrateur</a>.</p>";
				$message = \Swift_Message::newInstance()
				  ->setSubject('Proposition d\'offre d\'emploi à publier sur Healthvalley')
				  ->setFrom('info@republic-of-innovation.org')
  				  ->setTo(array('juliette.lemaignen@inartis.ch','f.rousseaux74@gmail.com'))
				  // ->setTo('bisognano_c@me.com')
				  //->setTo('info@nextrends.ch')
				  
				  ->setBody($html, 'text/html')
            ;
            $this->get('mailer')->send($message);
			return new Response($html);
		}
		return new Response("KO");
	}
	
	protected function createApplicant($request){
		
        $data=$request->request->all();
        if ($request->getMethod() == 'POST') {
			//$date=  explode ("/" ,$data['applicantform_date']["value"]);
			$ev= new Applicant();	
			$ev ->setFirstname($data['applicantform_firstname']["value"])
				->setName($data['applicantform_name']["value"])
				->setEmail($data['applicantform_email']["value"])
				//->setBirthdate(new \DateTime($date[1].'/'.$date[0].'/'.$date[2]))
				->setJobTitle($data['applicantform_job']["value"])
				->setLatLng($data['latlng']["value"])
				->setAddress($data['applicantform_address']["value"])
    			->setLinkedInProfilURL($data['applicantform_LinkedInProfilURL']["value"])
				//->setGender($data['gender']["value"])
				->setResume($data['applicantform_resume']["value"])
				->setPublished(false);
			$em = $this->getDoctrine()->getManager();
			$repository = $em->getRepository('AppBundle:Applicant');
			$em->persist($ev); 
			$em->flush();
			
			$route =$this->get('router')->generate('admin_app_applicant_edit', 
			array("_sonata_admin" => "admin.applicant", "_sonata_name" => "admin_app_applicant_edit", "id" => $ev->getId()), UrlGeneratorInterface::ABSOLUTE_URL
			);
			
			
			 $html = "<p>Vous venez de recevoir une proposition de demande d'emploi à publier sur <a href='http://www.republic-of-innovation.org/HealthValley/admin'>Health Valley</a></p> <p>Evenement : <strong>".$ev->getFirstname()." ".$ev->getName()."</strong>, ".$ev->getEmail()."<br />".$ev->getJobTitle()."</p>";
				$message = \Swift_Message::newInstance()
				  ->setSubject('Vous avez reçu une demande d\'emploi sur Healthvalley')
                ->setFrom('info@republic-of-innovation.org')
  				->setTo(array('juliette.lemaignen@inartis.ch','f.rousseaux74@gmail.com'))
                // ->setTo('info@nextrends.ch')
                // ->setTo('romain@messaggio.agency')
                ->setBody($html, 'text/html')
            ;
            $this->get('mailer')->send($message);
			
			return new Response($route);
		 }
		return new Response("KO");
	}
}