<?php

namespace Site\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Site\FrontendBundle\Entity\Users;
use Site\FrontendBundle\Entity\Data;
use Site\FrontendBundle\Entity\Categories;
use Site\FrontendBundle\Entity\Events;
use Site\FrontendBundle\Form\RegisterType;
use Site\FrontendBundle\Form\ContactType;
use Site\FrontendBundle\Form\UploadType;
use Site\FrontendBundle\Form\EventType;
use Symfony\Component\Validator\Constraints\Count;


class DefaultController extends Controller
{
    public $email_admin = 'jordixaubet@gmail.com';


    public function defaultAction()
    {
        $user = $this->get('security.context')->getToken()->getUser();
        $name = $user->getName();

        if ($this->get('security.context')->isGranted('ROLE_USER')) {

        }
        elseif ($this->get('security.context')->isGranted('ROLE_ADMIN')) {

        }

        if (false === $this->get('security.context')->isGranted('ROLE_ADMIN'))
        {
            throw new AccessDeniedException();
        }

    }

    public function homeAction(Request $request)
    {

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

        $this->saveLastConnection();

        $categories = $em->getRepository('FrontendBundle:Categories')->findBy(array(),
            array('nameeng' => 'ASC')
        );
        /*
        $data = $em->getRepository('FrontendBundle:Data')->findBy(array(),
            array('id' => 'DESC')
        );
        */

        $queryData = $em->createQuery(
            'SELECT d
               FROM FrontendBundle:Data d
              WHERE d.accepted = 1
           ORDER BY d.id DESC'
        );
        $data = $queryData->getResult();

        /* Data Pagination */
        if ($data) {

            $page_data = $request->get('page_data');
            $count_per_page_data = 10;

            $total_count_data = $this->getTotalData();
            $total_pages_data = ceil($total_count_data / $count_per_page_data);

            if (!is_numeric($page_data))
            {
                $page_data = 1;
            }
            else
            {
                $page_data = floor($page_data);
            }

            if (($page_data * $count_per_page_data) > $total_count_data)
            {
                $page_data = $total_pages_data;
            }

            if ($total_count_data <= $count_per_page_data)
            {
                $page_data = 1;
            }

            $offset = 0;

            if ($page_data > 1)
            {
                $offset = $count_per_page_data * ($page_data - 1);
            }


            $countQueryData = $em->createQueryBuilder()
                ->select('c')
                ->from('FrontendBundle:Data', 'c')
                ->where('c.accepted = 1')
                ->setFirstResult($offset)
                ->setMaxResults($count_per_page_data);
            $finalQueryData = $countQueryData->getQuery();

            $countData = $finalQueryData->getArrayResult();
        } else {
            throw $this->createNotFoundException(
                'It has been impossible to throw the list of files.'
            );
        }


        $queryEvents = $em->createQuery(
            'SELECT e
               FROM FrontendBundle:Events e
              WHERE e.accepted = 1
           ORDER BY e.id DESC'
        );
        $events = $queryEvents->getResult();

        /* Events Pagination */
        if ($events) {

            $page_events = $request->get('page_events');
            $count_per_page_events = 10;

            $total_count_events = $this->getTotalEvents();
            $total_pages_events = ceil($total_count_events / $count_per_page_events);

            if (!is_numeric($page_events))
            {
                $page_events = 1;
            }
            else
            {
                $page_events = floor($page_events);
            }

            if (($page_events * $count_per_page_events) > $total_count_events)
            {
                $page_events = $total_pages_events;
            }

            if ($total_count_events <= $count_per_page_events)
            {
                $page_events = 1;
            }

            $offset = 0;

            if ($page_events > 1)
            {
                $offset = $count_per_page_events * ($page_events - 1);
            }


            $countQueryEvents = $em->createQueryBuilder()
                ->select('c')
                ->from('FrontendBundle:Events', 'c')
                ->where('c.accepted = 1')
                ->setFirstResult($offset)
                ->setMaxResults($count_per_page_events);
            $finalQueryEvents = $countQueryEvents->getQuery();

            $countEvents = $finalQueryEvents->getArrayResult();
        } else {
            throw $this->createNotFoundException(
                'It has been impossible to throw the list of events.'
            );
        }

        return $this->render(
            'FrontendBundle:Default:home.html.twig', array(
                'categories' => $categories,
                'data' => $data,
                'count_data' => $countData,
                'total_pages_data' => $total_pages_data,
                'current_page_data' => $page_data,
                //'name_category' => $nameCategory,
                'events' => $events,
                'count_events' => $countEvents,
                'total_pages_events' => $total_pages_events,
                'current_page_events' => $page_events,
        ));
    }

    public function getTotalData()
    {
        $em = $this->getDoctrine()->getManager();

        $countQuery = $em->createQueryBuilder()
            ->select('Count(c)')
            ->from('FrontendBundle:Data', 'c')
            ->where('c.accepted = 1');
        $finalQuery = $countQuery->getQuery();
        $total = $finalQuery->getSingleScalarResult();

        return $total;
    }

    public function getTotalEvents()
    {
        $em = $this->getDoctrine()->getManager();

        $countQuery = $em->createQueryBuilder()
            ->select('Count(c)')
            ->from('FrontendBundle:Events', 'c')
            ->where('c.accepted = 1');
        $finalQuery = $countQuery->getQuery();
        $total = $finalQuery->getSingleScalarResult();

        return $total;
    }

    public function loginAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();

        $error = $request->attributes->get(
            SecurityContext::AUTHENTICATION_ERROR,
            $session->get(SecurityContext::AUTHENTICATION_ERROR)
        );


        return $this->render('FrontendBundle:Default:login.html.twig', array(
            'last_username' => $session->get(SecurityContext::LAST_USERNAME),
            'error' => $error
        ));
    }

    public function saveLastConnection()
    {
        /* Save last connection in the 'users' table */
        $em = $this->getDoctrine()->getManager();
        $user = $this->get('security.context')->getToken()->getUser();

        if (is_object($user)) {
            $setLastConnection = $user->setLastConnection(new \DateTime());

            $em->flush();
        }
    }

    public function logoutAction()
    {
        return $this->render('FrontendBundle:Default:login.html.twig');
    }

    public function registerAction()
    {
        $request = $this->getRequest();

        $user = new Users();

        $form = $this->createForm(new RegisterType(), $user);

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

            if ($form->isValid()) {
                $encoder = $this->get('security.encoder_factory')->getEncoder($user);
                $user->setSalt(md5(time()));
                $codifiedPassword = $encoder->encodePassword(
                    $user->getPassword(),
                    $user->getSalt()
                );

                $user->setPassword($codifiedPassword);
                $user->setLastConnection(new \DateTime());
                $user->setActive(0);

                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();

                $message = \Swift_Message::newInstance()
                    ->setSubject('[OPEN DATA PORTAL] Register succesfully')
                    ->setFrom('opendata.portal.project@gmail.com')
                    ->setTo($form->get('email')->getData())
                    ->setBody(
                        $this->renderView(
                            'FrontendBundle:Mail:register_mail.html.twig',
                            array(
                                'ip' => $request->getClientIp(),
                                'email' => $form->get('email')->getData(),
                                'subject' => '[OPEN DATA PORTAL] Register succesfully',
                            )
                        )
                    );

                $message_admin = \Swift_Message::newInstance()
                    ->setSubject('[OPEN DATA PORTAL] Register succesfully')
                    ->setFrom('opendata.portal.project@gmail.com')
                    ->setTo($this->email_admin)
                    ->setBody(
                        $this->renderView(
                            'FrontendBundle:Mail:register_mail.html.twig',
                            array(
                                'ip' => $request->getClientIp(),
                                'email' => $form->get('email')->getData(),
                                'subject' => '[OPEN DATA PORTAL] Register succesfully',
                            )
                        )
                    );

                $this->get('mailer')->send($message);
                $this->get('mailer')->send($message_admin);

                $this->get('session')->getFlashBag()->add('reg_success',
                    'Congratulations! You have been registered succesfully. Soon the administrator of the site will validate your user.'
                );

                return $this->redirect($this->generateUrl('home'));
            }
        }

        return $this->render(
            'FrontendBundle:Default:register.html.twig',
            array('form' => $form->createView())
        );
    }

    public function profileAction()
    {
        $user = $this->get('security.context')->getToken()->getUser();
        $form = $this->createForm(new RegisterType(), $user);

        $request = $this->getRequest();

        if ($request->getMethod() == 'POST') {
            $originalPassword = $form->getData()->getPassword();

            $form->bind($request);

            if ($form->isValid()) {

                if (null == $user->getPassword()) {
                    $user->setPassword($originalPassword);
                } else {
                    $encoder = $this->get('security.encoder_factory')->getEncoder($user);
                    $originalPassword = $encoder->encodePassword(
                        $user->getPassword(),
                        $user->getSalt()
                    );
                    $user->setPassword($originalPassword);
                }

                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();

                $this->get('session')->getFlashBag()->add('profile_updated',
                    'Profile updated successfully.'
                );
                return $this->redirect($this->generateUrl('profile'));
            }
        }
        return $this->render('FrontendBundle:Default:profile.html.twig', array(
            'user' => $user,
            'form' => $form->createView()
        ));
    }

    public function contactAction(Request $request)
    {
        $form = $this->createForm(new ContactType());

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

            if ($form->isValid()) {
                $message_admin = \Swift_Message::newInstance()
                    ->setSubject('[OPEN DATA PORTAL] Contact Form')
                    ->setFrom($form->get('email')->getData())
                    ->setTo($this->email_admin)
                    ->setBody(
                        $this->renderView(
                            'FrontendBundle:Mail:contact_mail.html.twig',
                            array(
                                'ip' => $request->getClientIp(),
                                'name' => $form->get('fullName')->getData(),
                                'email' => $form->get('email')->getData(),
                                'subject' => $form->get('subject')->getData(),
                                'message' => $form->get('message')->getData()
                            )
                        )
                    );

                $this->get('mailer')->send($message_admin);

                $request->getSession()->getFlashBag()->add('contact_success', 'Your email has been sent! Thanks!');

                return $this->redirect($this->generateUrl('contact'));
            }
        }

        return $this->render(
            'FrontendBundle:Default:contact.html.twig',
            array('form' => $form->createView())
        );
    }

    public function uploadAction()
    {

        $request = $this->getRequest();

        $data = new Data();

        $form = $this->createForm(new UploadType(), $data);

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

            if ($form->isValid()) {

                $user = $this->get('security.context')->getToken()->getUser();
                $idUser = $user->getId();
                $emailUser = $user->getEmail();

                $dir = "uploads/";
                $file = $form->get('file')->getData();
                $filename = rand(1, 99999).'-'.$file->getClientOriginalName();
                $file->move($dir, $filename);


                //$extension = $file->getExtension();
                $extension = pathinfo($filename, PATHINFO_EXTENSION);
                if (!$extension) {
                    // extension cannot be get
                    $extension = 'Not found';
                }

                $size = $file->getClientSize();
                $nameCat = "";
                $nameSpa = "";

                $web = $form->get('web')->getData();
                if ($web == null) $web = "";

                $metadata = $form->get('metadata')->getData();
                if ($metadata == null) $metadata = "";

                $data->setIdUser($idUser);
                $data->setWeb($web);
                $data->setFile($filename);
                $data->setSize($size);
                $data->setType(strtoupper($extension));
                $data->setNameCat($nameCat);
                $data->setNameSpa($nameSpa);
                $data->setMetadata($metadata);
                $data->setViews(0);
                $data->setAccepted(0);


                $em = $this->getDoctrine()->getManager();
                $em->persist($data);
                $em->flush();

                $message = \Swift_Message::newInstance()
                    ->setSubject('[OPEN DATA PORTAL] Upload succesfully')
                    ->setFrom('opendata.portal.project@gmail.com')
                    ->setTo($emailUser)
                    ->setBody(
                        $this->renderView(
                            'FrontendBundle:Mail:upload_file_mail.html.twig',
                            array(
                                'ip' => $request->getClientIp(),
                                'email' => $emailUser,
                                'file' => $file->getClientOriginalName(),
                                'subject' => '[OPEN DATA PORTAL] Upload succesfully',
                            )
                        )
                    );

                $message_admin = \Swift_Message::newInstance()
                    ->setSubject('[OPEN DATA PORTAL] Upload succesfully')
                    ->setFrom('opendata.portal.project@gmail.com')
                    ->setTo($this->email_admin)
                    ->setBody(
                        $this->renderView(
                            'FrontendBundle:Mail:upload_file_mail.html.twig',
                            array(
                                'ip' => $request->getClientIp(),
                                'email' => $this->email_admin,
                                'file' => $file->getClientOriginalName(),
                                'subject' => '[OPEN DATA PORTAL] Upload succesfully',
                            )
                        )
                    );

                $this->get('mailer')->send($message);
                $this->get('mailer')->send($message_admin);

                $this->get('session')->getFlashBag()->add('upload_success',
                    'Your file has been uploaded succesfully. Soon the administrator of the site will validate your file.'
                );

                return $this->redirect($this->generateUrl('home'));
            }
        }

        return $this->render(
            'FrontendBundle:Default:upload.html.twig',
            array('form' => $form->createView())
        );
    }

    public function add_eventAction()
    {
        $request = $this->getRequest();

        $event = new Events();

        $form = $this->createForm(new EventType(), $event);


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

            if ($form->isValid()) {

                $user = $this->get('security.context')->getToken()->getUser();
                $idUser = $user->getId();
                $emailUser = $user->getEmail();

                $titleCat = "";
                $titleSpa = "";

                $link = $form->get('link')->getData();
                if ($link == null) $link = "";

                $event->setIdUser($idUser);
                $event->setLink($link);
                $event->setTitleCat($titleCat);
                $event->setTitleSpa($titleSpa);
                $event->setViews(0);
                $event->setAccepted(0);

                $titleEng = $event->getTitleEng();

                $em = $this->getDoctrine()->getManager();
                $em->persist($event);
                $em->flush();

                $message = \Swift_Message::newInstance()
                    ->setSubject('[OPEN DATA PORTAL] Event added succesfully')
                    ->setFrom('opendata.portal.project@gmail.com')
                    ->setTo($emailUser)
                    ->setBody(
                        $this->renderView(
                            'FrontendBundle:Mail:add_event_mail.html.twig',
                            array(
                                'ip' => $request->getClientIp(),
                                'email' => $emailUser,
                                'titleEng' => $titleEng,
                                'subject' => '[OPEN DATA PORTAL] Event added succesfully',
                            )
                        )
                    );

                $message_admin = \Swift_Message::newInstance()
                    ->setSubject('[OPEN DATA PORTAL] Event added succesfully')
                    ->setFrom('opendata.portal.project@gmail.com')
                    ->setTo($this->email_admin)
                    ->setBody(
                        $this->renderView(
                            'FrontendBundle:Mail:add_event_mail.html.twig',
                            array(
                                'ip' => $request->getClientIp(),
                                'email' => $emailUser,
                                'titleEng' => $titleEng,
                                'subject' => '[OPEN DATA PORTAL] Event added succesfully',
                            )
                        )
                    );

                $this->get('mailer')->send($message);
                $this->get('mailer')->send($message_admin);

                $this->get('session')->getFlashBag()->add('add_event_success',
                    'Your event has been added succesfully. Soon the administrator of the site will validate your event.'
                );

                return $this->redirect($this->generateUrl('home'));
            }
        }

        return $this->render(
            'FrontendBundle:Default:add_event.html.twig',
            array('form' => $form->createView())
        );
    }

    public function fileAction($id_file)
    {

        $em = $this->getDoctrine()->getManager();
        $data = $em->getRepository('FrontendBundle:Data')->findById($id_file);

        $idCategory = $data[0]->getIdCategory();
        $categoryObject = $em->getRepository('FrontendBundle:Categories')->find($idCategory);
        $nameCategory = $categoryObject->getNameEng();


        $currentViews = $data[0]->getViews();
        $newViews = $data[0]->setViews($currentViews + 1);

        $em->flush();

        return $this->render('FrontendBundle:Default:file.html.twig', array(
            'data' => $data,
            'id_file' => $id_file,
            'name_category' => $nameCategory
        ));
    }

    public function eventAction($id_event)
    {

        $em = $this->getDoctrine()->getManager();
        $event = $em->getRepository('FrontendBundle:Events')->findById($id_event);

        $currentViews = $event[0]->getViews();
        $newViews = $event[0]->setViews($currentViews + 1);

        $em->flush();

        return $this->render('FrontendBundle:Default:event.html.twig', array(
            'events' => $event,
            'id_event' => $id_event,
            //'name_user' => $nameUser
        ));
    }
}
