<?php
/**
 * Form Submit Handler
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\Helper;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use VisualM\FormBundle\Email\EmailSender;
use VisualM\FormBundle\Entity\Form as FormEntity;
use VisualM\FormBundle\Entity\FormEntry as FormEntryEntity;
use VisualM\FormBundle\Entity\FormEntryRepository;
use VisualM\FormBundle\Renderer\EmailRenderer;
use VisualM\FormBundle\Renderer\FormRenderer;

/**
 * Form Submit Handler
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class SubmitHandler
{

    /**
     * Form Renderer
     * @var FormRenderer
     */
    private $formRenderer;

    /**
     * E-mail Renderer
     * @var EmailRenderer
     */
    private $emailRenderer;

    /**
     * E-mail Sender
     * @var EmailSender
     */
    private $emailSender;

    /**
     * Form Entry Manager
     * @var FormEntryRepository
     */
    private $formEntryRepository;

    /**
     * Status Options
     * @var string
     */
    private $defaultStatus;

    /**
     * Constructor
     * 
     * @param FormRenderer        $formRenderer        Form Renderer
     * @param EmailRenderer       $emailRenderer       E-mail Renderer
     * @param EmailSender         $emailSender         E-mail Sender
     * @param FormEntryRepository $formEntryRepository Form Entry Repository
     * @param string              $defaultStatus       Default E-mail Entry Status
     */
    public function __construct(FormRenderer $formRenderer, EmailRenderer $emailRenderer, EmailSender $emailSender, FormEntryRepository $formEntryRepository, $defaultStatus)
    {
        $this->formRenderer = $formRenderer;
        $this->emailRenderer = $emailRenderer;
        $this->emailSender = $emailSender;
        $this->formEntryRepository = $formEntryRepository;
        $this->defaultStatus = $defaultStatus;
    }

    
    /**
     * Handle the submit of the form
     *
     * @param Request $request Request
     * 
     * @return null|Response Response to send or null if no response
     */
    public function handleSubmit(Request $request)
    {
        foreach ($this->formRenderer->getRenderedForms() as $renderedForm) {
            list($form, $formEntity, $customRedirect) = $renderedForm;
            if ($form->isValid()) {
                $data = $form->getData()->all();
                $entry = $this->saveEntry($request, $data, $formEntity);
                $this->emailSender->sendEmails($entry);
                return new RedirectResponse(
                    $customRedirect !== null ? $customRedirect : $formEntity->getRedirectPath()
                );
            }
        }
        return null;
    }

    /**
     * Save Entry to database
     *
     * @param Request    $request    Request
     * @param array      $data       Data
     * @param FormEntity $formEntity Form Entity
     *
     * @return FormEntryEntity
     */
    protected function saveEntry(Request $request, array $data, FormEntity $formEntity)
    {

        $emailHtml = $this->emailRenderer->renderEmail($formEntity, $data);
        $kopieEmailHtml = $this->emailRenderer->renderKopieEmail($formEntity, $data);

        $form_entry = new FormEntryEntity();
        $form_entry->setStatus($this->defaultStatus);
        $form_entry->setForm($formEntity);
        $form_entry->setRemoteAddr($request->getClientIp());
        $form_entry->setBrowser($request->headers->get('User-Agent', ''));

        $form_entry->setLandingUrl($request->getSession()->get('userinfo.landing_page', null));
        $form_entry->setLandingReferer($request->getSession()->get('userinfo.landing_referer', null));
        $form_entry->setTimeOnSiteInSec($request->getSession()->has('userinfo.landing_time') ? (time() - $request->getSession()->get('userinfo.landing_time')) : null);
        $form_entry->setLandingUrl($request->getSession()->get('userinfo.landing_page'));
        $form_entry->setUrl($request->getSchemeAndHttpHost() . $request->getRequestUri());
        $form_entry->setRawdata($data);
        $form_entry->setEmailHtml($emailHtml);
        $form_entry->setKopieEmailHtml($kopieEmailHtml);

        $this->formEntryRepository->saveItem($form_entry);

        return $form_entry;
    }

}
