<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Connection;
use AppBundle\Entity\Application;
use AppBundle\Entity\Port;
use AppBundle\Form\Type\OrderFirstType;
use AppBundle\Form\Type\OrderSecondType;
use AppBundle\Form\Type\OrderThirdType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class OrderController extends Controller
{
    /**
     * @Template()
     *
     * @param Request $request
     * @return array
     */
    public function firstAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $application = new Application();
        $form = $this->createForm(new OrderFirstType(), $application, array(
            'em' => $em,
            'action' => $this->generateUrl('app.order.first')
        ));
        $form->handleRequest($request);

        if($request->query->get('loading') && $request->query->get('unloading')) {
            $connection = $em->getRepository('AppBundle:Connection')->findOneByPortNames(
                $request->query->get('loading'), $request->query->get('unloading')
            );

            if($connection) {
                $form->get('loading')->setData($connection->getLoading());
                $form->get('unloading')->setData($connection->getUnloading());
            }
        }

        if ($form->isValid()) {
            return $this->forward('AppBundle:Order:second', array(), array('forward' => true));
        } elseif ($request->getMethod() == 'POST') {
            return new Response('//not-valid//');
        }

        return $this->render(
            'AppBundle:Order:first.html.twig',
            array(
                'form' => $form->createView()
            )
        );
    }

    /**
     * @Template()
     *
     * @param Request $request
     * @return array
     */
    public function secondAction(Request $request)
    {
        $isForwarded = $request->query->get('forward');
        $application = new Application();
        $form = $this->createForm(new OrderSecondType($isForwarded), $application, array(
            'em' => $this->getDoctrine()->getManager(),
            'action' => $this->generateUrl('app.order.second')
        ));
        $form->handleRequest($request);

        if (!$form->isValid() && $request->getMethod() == 'POST' && $request->request->get('initial')) {
            return new Response('//not-valid//');
        }

        $this->countCosts($application);
        $setting = null;
        if($application->getConnection()->getUseeuro() == 1){
            $setting = $this->getSettingEuro();
        }
        else{
          $setting = $this->getSettings();
        }

        if (!$isForwarded && $form->isValid()) {
            return $this->forward('AppBundle:Order:third', array(), array('forward' => true));
        } elseif (!$isForwarded && $request->getMethod() == 'POST') {
            echo '//not-valid//';
        }

        return $this->render(
            'AppBundle:Order:second.html.twig',
            array(
                'form' => $form->createView(),
                'application' => $application,
                'settings' => $setting,
            )
        );
    }

    /**
     * @Template()
     *
     * @param Request $request
     * @return array
     */
    public function thirdAction(Request $request)
    {
        $isForwarded = $request->query->get('forward');
        $em = $this->getDoctrine()->getManager();
        $application = new Application();
        $form = $this->createForm(new OrderThirdType($isForwarded), $application, array(
            'em' => $em,
            'action' => $this->generateUrl('app.order.third')
        ));

        $form->handleRequest($request);

        $this->countCosts($application);
        $setting = null;
        if($application->getConnection()->getUseeuro() == 1){
            $setting = $this->getSettingEuro();
        }
        else{
          $setting = $this->getSettings();
        }

        if (!$isForwarded && $form->isValid()) {
            $this->setVoucher($application, $form->get('voucher')->getData());
            $em->persist($application);
            $em->flush();

            $this->addEmailToNewsletter($application);

            $mailer = $this->get('app.service.mailer');
            $mailer->sendNewOrderUser($application);
            $mailer->sendNewOrderConsultant($application);

            return $this->RedirectToRoute('app.order.four', array('application'=>$application));
        } elseif (!$isForwarded && $request->getMethod() == 'POST') {
            echo '//not-valid//';
        }

        return $this->render(
            'AppBundle:Order:third.html.twig',
            array(
                'form' => $form->createView(),
                'application' => $application,
                'settings' => $setting,
            )
        );
    }

    public function fourAction(Request $request)
    {
        $ap = $request->request->get('email');

        return $this->render(
            'AppBundle:Order:four.html.twig', array('appxx'=>$ap,)
        );
    }

    private function getErrorMessages(\Symfony\Component\Form\Form $form)
    {
        $errors = array();

        foreach ($form->getErrors() as $key => $error) {
            if ($form->isRoot()) {
                $errors['#'][] = $error->getMessage();
            } else {
                $errors[] = $error->getMessage();
            }
        }

        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                $errors[$child->getName()] = $this->getErrorMessages($child);
            }
        }

        return $errors;
    }

    /**
     * @Template()
     *
     * @param Application $application
     * @return array
     */
    public function previewAction(Application $application)
    {
        return array(
            'application' => $application
        );
    }

    /**
     * @return JsonResponse
     */
    public function connectionsAction()
    {
        $em = $this->getDoctrine()->getManager();
        $connections = $em->getRepository('AppBundle:Connection')->findAllData();

        return new JsonResponse($connections);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function voucherCheckAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $voucher = $em->getRepository('AppBundle:Voucher')->findOneBy(array(
            'code' => $request->request->get('voucher'),
            'isActive' => true
        ));

        return new JsonResponse(array(
            'success' => $voucher ? true : false,
            'value' => $voucher ? $voucher->getValue() : false
        ));
    }

    private function getSettings()
    {
        $em = $this->getDoctrine()->getManager();

        return $em->getRepository('AppBundle:Setting')->findAllData();
    }

    private function getSettingEuro(){

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

      return $em->getRepository('AppBundle:SettingEuro')->findAllData();
    }
    private function countValue($volume, $weight)
    {
        $volume = (float)str_replace(',', '.', $volume);
        $weight = (float)str_replace(',', '.', $weight);

        $weight /= 1000;
        $value = $volume > $weight ? $volume : $weight;

        return $value < 1 ? 1 : $value;
    }

    private function countCosts(Application $application)
    {
        $em = $this->getDoctrine()->getManager();
        $connection = $em->getRepository('AppBundle:Connection')
            ->findOneByPorts($application->getLoading(), $application->getUnloading());
        $application->setConnection($connection);

        //$settings = $this->getSettings();

        $settings = null;
        if($application->getConnection()->getUseeuro() == 1){
            $settings = $this->getSettingEuro();
        }
        else{
          $settings = $this->getSettings();
        }
        $value = $this->countValue($application->getVolume(), $application->getWeight());
        $weight = (float)str_replace(',', '.', $application->getWeight()) / 1000;
        $weight = $weight < 1 ? 1 : $weight;

        $application
            ->setDocumentary($settings['documentary'])
            ->setConnectionCost($connection->getCost() * $value);

        if($application->getLoading()->getCountry() == 'Polska') {
            $application->setWarehouse($settings['warehouse'] * $value);
        } else {
            $application
                ->setThc($settings['thc'] * $value)
                ->setIsps($settings['isps'] * $weight);
        }
        if($application->getConnection()->getUseeuro() == 1 && $application->getUnloading()->getName() == 'Hamburg'){
          if($application->getThc() < 90){
            $application->setThc(90);
          }
        }

        if (!$application->getTransport()) {
            $application->setTransport(false);
        }

        if ($application->getCustoms()) {
            $application->setCustoms($settings['customs']);
        }

        $application->setCost(
            $application->getDocumentary() + $application->getThc() + $application->getIsps() +
            $application->getWarehouse() + $application->getConnectionCost() + $application->getCustoms()
        );

        $exchangeRate = $this->get('app.service.exchange_rate')->getAndUpdate();
        $application->setExchangeRate($exchangeRate);

        $exchangeRate_e = $this->get('app.service.exchange_rate')->getAndUpdate('e');
        $application->setExchangeRateeuro(floatval($exchangeRate_e));

    }

    private function setVoucher(Application $application, $voucher = null)
    {
        if ($voucher) {
            $em = $this->getDoctrine()->getManager();

            $voucher = $em->getRepository('AppBundle:Voucher')->findOneBy(array(
                'code' => $voucher,
                'isActive' => true
            ));

            if ($voucher) {
                $application->setVoucher($voucher);
                $application->setConnectionCost(
                    $application->getConnectionCost() * (100 - $voucher->getValue()) / 100
                );
                $application->setCost(
                    $application->getDocumentary() + $application->getThc() + $application->getIsps() +
                    $application->getWarehouse() + $application->getConnectionCost() + $application->getCustoms()
                );
            }
        }
    }

    private function addEmailToNewsletter(Application $application)
    {

         $nameParts = explode(' ', $application->getFullName());
        $firstName = array_shift($nameParts);
        $lastName = implode(' ', $nameParts);
        $params = array(
            'first_name' => $firstName,
            'last_name' => $lastName,
            'email' => $application->getEmail(),
            'custom_company' => $application->getCompany(),
            'custom_mobile_phone' => $application->getPhone(),
            'custom_loadc' => $application->getLoading()->getCountry(),
            'custom_load' => $application->getLoading()->getName(),
            'custom_unloadc' => $application->getUnloading()->getCountry(),
            'custom_unload' => $application->getUnloading()->getName(),
            'custom_volume' => $application->getVolume(),
            'custom_weight' => $application->getWeight() / 1000,
            'custom_customs' => $application->getCustoms() ? 'Yes' : 'No',
            'custom_transport' => $application->getTransport() ? 'Yes' : 'No',
            'campaign_token' => $this->container->getParameter('campaign_token')
        );
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,"https://app.getresponse.com/add_subscriber.html");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$params);

        // in real life you should use something like:
        // curl_setopt($ch, CURLOPT_POSTFIELDS,
        //          http_build_query(array('postvar1' => 'value1')));

        // receive server response ...
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec ($ch);

        curl_close ($ch);

//        $mailChimp = $this->get('MailChimp');
//        $list = $mailChimp->getList();
//        $list->setDoubleOptin(false);
//
//        $nameParts = explode(' ', $application->getFullName());
//        $firstName = array_shift($nameParts);
//        $lastName = implode(' ', $nameParts);
//
//        $list->setMerge(array(
//            'FNAME' => $firstName,
//            'LNAME' => $lastName,
//            'COMPANY' => $application->getCompany(),
//            'PHONE' => $application->getPhone(),
//            'LOADC' => $application->getLoading()->getCountry(),
//            'LOAD' => $application->getLoading()->getName(),
//            'UNLOADC' => $application->getUnloading()->getCountry(),
//            'UNLOAD' => $application->getUnloading()->getName(),
//            'VOLUME' => $application->getVolume(),
//            'WEIGHT' => $application->getWeight() / 1000,
//            'CUSTOMS' => $application->getCustoms() ? 'Yes' : 'No',
//            'TRANSPORT' => $application->getTransport() ? 'Yes' : 'No'
//        ));
//
//        $list->setUpdateExisting(true);
//        $list->setEmail($application->getEmail());
//        $list->mergeVars();
//        $list->Subscribe();
    }
}
