<?php

namespace RxConnexionBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use RxConnexionBundle\Entity\HealthFacilityRegistrationEntity;
use RxConnexionBundle\Form\HealthFacilityRegistrationForm;


/**
 * @Route("")
 */
class FrontEndController extends Controller
{
    /**
     * @Route("", name="front_end")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        //$healthFacilityTypes = $em->getRepository('RxConnexionBundle:HealthFacilityTypeEntity')->findAll();

        /*return $this->render('@RxConnexion/Frontend/index.html.twig', array(
            'stylesheets' => array('css/frontend/frontend.css'),
            'javascripts' => array('js/frontend/frontend.js'),
            'healthFacilityTypes' => $healthFacilityTypes
        ));*/
        return $this->redirect($this->generateUrl('main'), 302);
    }

    public function search_resultAction(Request $request) {

        $params = array(
            'healthFacilityType' => $request->get('healthFacilityType'),
            'searchQuery' => $request->get('searchQuery'),
            'clinicNameQuery' => $request->get('clinicNameQuery'),
            'addressQuery' => $request->get('addressQuery'),
            'cityQuery' => $request->get('cityQuery'),
            'provinceQuery' => $request->get('provinceQuery'),
            'forSchedule' => $request->get('forSchedule'),
            'preferredDateQuery' => $request->get('preferredDateQuery'),
            'preferredTimeFromHourQuery' => $request->get('preferredTimeFromHourQuery'),
            'preferredTimeFromMinuteQuery' => $request->get('preferredTimeFromMinuteQuery'),
            'preferredTimeFromPeriodQuery' => $request->get('preferredTimeFromPeriodQuery'),
            'preferredTimeToHourQuery' => $request->get('preferredTimeToHourQuery'),
            'preferredTimeToMinuteQuery' => $request->get('preferredTimeToMinuteQuery'),
            'preferredTimeToPeriodQuery' => $request->get('preferredTimeToPeriodQuery')
        );

        $em = $this->em();

        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->getWithParams($params);

        $session = $this->get('session');
        $session->set('forScheduleQuery', array(
            'forSchedule' => $params['forSchedule'],
            'date' => $params['preferredDateQuery'],
            'fromHour' => $params['preferredTimeFromHourQuery'],
            'fromMinute' => $params['preferredTimeFromMinuteQuery'],
            'fromPeriod' => $params['preferredTimeFromPeriodQuery'],
            'toHour' => $params['preferredTimeToHourQuery'],
            'toMinute' => $params['preferredTimeToMinuteQuery'],
            'toPeriod' => $params['preferredTimeToPeriodQuery']
        ));

        return $this->render('RxConnexionBundle:FrontEnd:search_result.html.twig', array(
            'stylesheets' => array('css/frontend/search_result.css'),
            'googleMap' => true,
            'healthFacilities' => $healthFacilities
        ));
    }

    public function search_result_view_detailsAction($id) {

        $healthFacility = $this->em()->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($id);

        return $this->render('RxConnexionBundle:FrontEnd:search_result_view_details.html.twig', array(
            'stylesheets' => array('slick/slick.css', 'slick/slick-theme.css', 'css/frontend/search_result_view_details.css'),
            'javascripts' => array('slick/slick.min.js', 'js/frontend/search_result_view_details.js'),
            'googleMap' => true,
            'healthFacility' => $healthFacility
        ));
    }

    public function search_result_view_details_schedule_liveAction($id) {

        $healthFacility = $this->em()->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($id);

        return $this->render('RxConnexionBundle:FrontEnd:search_result_view_details_schedule_live.html.twig', array(
            'stylesheets' => array('slick/slick.css', 'slick/slick-theme.css'),
            'javascripts' => array('slick/slick.min.js'),
            'healthFacility' => $healthFacility
        ));
    }

    /**
     * @Route("/fe-health-facility-registration", name="health_facility_registration")
     */
    public function health_facility_registrationAction(Request $request) {

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

        $addressData = array('country' => '', 'province' => '', 'city' => '');

        $options = array('action' => 'new');
        $healthFacilityRegistration = new HealthFacilityRegistrationEntity();
        $form = $this->createForm(HealthFacilityRegistrationForm::class, $healthFacilityRegistration, $options);

        $countries = $em->getRepository('RxConnexionBundle:CountryEntity')->findAll();

        $errors = array();

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

            $healthFacilityRegistration_form = $request->get('healthFacilityRegistration');

            $errors = $em->getRepository('RxConnexionBundle:HealthFacilityRegistrationEntity')->validate($healthFacilityRegistration_form, $request);

            if(!count($errors)) {

                $form->handleRequest($request);

                if($form->isValid()) {

                    $city = $em->getRepository('RxConnexionBundle:CityEntity')->find($request->get('city'));

                    $healthFacilityRegistration->setCity($city);
                    $healthFacilityRegistration->setToken(md5(time()));
                    $healthFacilityRegistration->setStatus('Pending');
                    $em->persist($healthFacilityRegistration);
                    $em->flush();

                    $mailer = $this->get('mailer');

                    $emails = array();

                    $email = $healthFacilityRegistration->getEmail();
                    $emailTwo = $healthFacilityRegistration->getEmailTwo();
                    $emailThree = $healthFacilityRegistration->getEmailThree();

                    if(!empty($email)) $emails[] = $email;
                    if(!empty($emailTwo)) $emails[] = $emailTwo;
                    if(!empty($emailThree)) $emails[] = $emailThree;

                    foreach($emails as $email) {

                        $message = $mailer->createMessage()
                            ->setSubject('ZapConexion | Clinic Registration Email Confirmation')
                            ->setFrom('noreplay@rxgrab.com')
                            ->setTo($email)
                            ->setBody(
                                $this->renderView(
                                    '@RxConnexion/Frontend/health_facility_registration_email_body.html.twig',
                                    array(
                                        'healthFacilityRegistration' => $healthFacilityRegistration
                                    )
                                ),
                                'text/html'
                            );

                        $mailer->send($message);
                    }

                    return $this->render('@RxConnexionBundle/Frontend/health_facility_registration_success.html.twig', array(
                        'healthFacilityRegistration' => $healthFacilityRegistration
                    ));

                } else {

                    $errors[] = 'Unexpected error encountered. Please try again.';
                }

            } else {

                $form->get('healthFacilityType')->setData($healthFacilityRegistration_form['healthFacilityType']);
                $form->get('company_description')->setData($healthFacilityRegistration_form['company_description']);
                $form->get('branch_description')->setData($healthFacilityRegistration_form['branch_description']);
                $form->get('description')->setData($healthFacilityRegistration_form['description']);
                $form->get('street')->setData($healthFacilityRegistration_form['street']);
                $form->get('zip_code')->setData($healthFacilityRegistration_form['zip_code']);
                $form->get('mobile_no')->setData($healthFacilityRegistration_form['mobile_no']);
                $form->get('mobile_no_two')->setData($healthFacilityRegistration_form['mobile_no_two']);
                $form->get('mobile_no_three')->setData($healthFacilityRegistration_form['mobile_no_three']);
                $form->get('phone_no')->setData($healthFacilityRegistration_form['phone_no']);
                $form->get('phone_no_two')->setData($healthFacilityRegistration_form['phone_no_two']);
                $form->get('phone_no_three')->setData($healthFacilityRegistration_form['phone_no_three']);
                $form->get('email')->setData($healthFacilityRegistration_form['email']);
                $form->get('email_two')->setData($healthFacilityRegistration_form['email_two']);
                $form->get('email_three')->setData($healthFacilityRegistration_form['email_three']);

                $addressData = array(
                    'country' => $request->get('country'),
                    'province' => $request->get('province'),
                    'city' => $request->get('city')
                );
            }
        }

        return $this->render('@RxConnexion/Frontend/health_facility_registration.html.twig', array(
            'stylesheets' => array('css/generalUser/register.css'),
            'form' => $form->createView(),
            'countries' => $countries,
            'errors' => $errors,
            'addressData' => $addressData
        ));
    }

    public function health_facility_registration_email_confirmationAction($t, $i) {

        $em = $this->em();

        $success = false;

        $healthFacilityRegistration = $em->getRepository('RxConnexionBundle:HealthFacilityRegistrationEntity')->find($i);

        if($healthFacilityRegistration && $healthFacilityRegistration->getToken() === $t) {

            $success = true;

            $healthFacilityRegistration->setStatus('Pending');
            $em->flush();
        }

        return $this->render('RxConnexionBundle:FrontEnd:health_facility_registration_email_confirmation.html.twig', array(
            'success' => $success
        ));
    }

    public function schedule_requestAction($i) {

        $session = $this->get('session');

        $session->set('schedule_request_healthFacilityId', $i);

        return $this->redirect($this->generateUrl('rx_grab_general_user'), 302);
    }
}
