<?php
/**
 * ManageFormEntry Controller
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\Controller;

use IntlDateFormatter;
use PHPExcel_Cell;
use PHPExcel_Style_Alignment;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use VisualM\BlockManagerBundle\Annotation\Block;
use VisualM\BlockManagerBundle\Annotation\BlockLayout;
use VisualM\FormBundle\Entity\FormEntry;

/**
 * ManageFormEntry
 *
 * @BlockLayout(layout="backend")
 * @Block(view="page_header", position="titlebar", priority=1)
 * @Block(view="flashmessages", position="flashmessages")
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class ManageFormEntryController extends Controller
{

    /**
     * Show list of Form Entries
     *
     * @Block(view="VisualMFormBundle:ManageFormEntry:index.html.twig", position="main")
     * @Block(view="VisualMFormBundle:ManageFormEntry:indexFilter.html.twig", position="main")
     * @Block(view="VisualMFormBundle:ManageFormEntry:indexActions.html.twig", position="titlebar-actions")
     *
     * @return array View data
     */
    public function indexAction()
    {
        $translator = $this->get('translator');
        $security_context = $this->get('security.context');

        if (!$security_context->isGranted('ROLE_PERM_LIST_FORM_ENTRY')) {
             throw new AccessDeniedHttpException($translator->trans('form_entry.access_denied', array(), 'exception'));
        }

		$admin_list = $this->get('visualm.form.admin_list.form_entry');

        return array(
            'page_title' => $translator->trans('form_entry.index.page_title', array(), 'backend'),
            'admin_list' => $admin_list,
            'forms' => $this->get('visualm.form.manager.form')->getIndex([], [ [ 'titel', 'ASC' ]]),
            'status_waarden' => $this->container->getParameter('visualm.form.status_waarden')
        );

    }


    /**
     * Wijzig de status van een Form Entry
     *
     * @param Request $request Request
     * @param int     $id      Form Entry Id
     * @param string  $status  Status
     *
     * @return Response Response
     */
    public function editStatusAction(Request $request, $id, $status)
    {
        $translator = $this->get('translator');

        if (!$this->get('security.context')->isGranted('ROLE_PERM_WORKFLOW_FORM')) {
             throw new AccessDeniedHttpException($translator->trans('form_entry.access_denied', array(), 'exception'));
        }

        // Get Manager
        $form_entry_manager = $this->get('visualm.form.manager.form_entry');

        if (null === ($entry = $form_entry_manager->getFirst([ 'id' => $id ]))) {
            throw $this->createNotFoundException($translator->trans('form_entry.not_found', array(), 'exception'));
        }

        $entry->setStatus($status);
        $form_entry_manager->saveItem($entry);

        $this->get('session')->getFlashBag()->add(
            'success', $translator->trans('form_entry.status.saved', array(), 'flashmessage')
        );

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


    /**
     * Show details for Form Entry
     *
     * @Block(view="VisualMFormBundle:ManageFormEntry:view.html.twig", position="main")
     * @Block(view="VisualMFormBundle:ManageFormEntry:toIndex.html.twig", position="titlebar")
     *
     * @param int $id Form Entry Id
     *
     * @return array View data
     */
    public function viewAction($id)
    {

        $translator = $this->get('translator');
        $security_context = $this->get('security.context');

        if (!$security_context->isGranted('ROLE_PERM_VIEW_FORM_ENTRY')) {
             throw new AccessDeniedHttpException($translator->trans('form_entry.access_denied', array(), 'exception'));
        }

        // Get Manager
        $form_entry_manager = $this->get('visualm.form.manager.form_entry');

        // Load Form
        if (null === ($form_entry = $form_entry_manager->getFirst(array('id' => $id)))) {
            throw $this->createNotFoundException($translator->trans('form_entry.not_found', array(), 'exception'));
        }

        return array(
            'page_title' => $translator->trans('form_entry.view.page_title', array(), 'backend'),
            'form_entry' => $form_entry
        );

    }

    /**
     * Export HTML for Email
     *
     * @param int $id Form Entry Id
     *
     * @return Response Response
     */
    public function ajaxViewEmailAction($id)
    {
        $translator = $this->get('translator');
        $security_context = $this->get('security.context');

        if (!$security_context->isGranted('ROLE_PERM_VIEW_FORM_ENTRY')) {
             throw new AccessDeniedHttpException($translator->trans('form_entry.access_denied', array(), 'exception'));
        }

        // Get Manager
        $form_entry_manager = $this->get('visualm.form.manager.form_entry');

        // Load Form
        if (null === ($form_entry = $form_entry_manager->getFirst(array('id' => $id)))) {
            throw $this->createNotFoundException($translator->trans('form_entry.not_found', array(), 'exception'));
        }

        // Disable profiler if enabled
        if ($this->container->has('profiler')) {
            $this->container->get('profiler')->disable();
        }

        return new Response($form_entry->getEmailHtml());
    }

    /**
     * Exporteer list to Excel
     *
     * @param Request $request Request
     *
     * @return Response Response
     */
    public function exportAction(Request $request)
    {
        $translator = $this->get('translator');
        $security_context = $this->get('security.context');

        if (!$security_context->isGranted('ROLE_PERM_EXPORT_FORM_ENTRY')) {
            throw new AccessDeniedHttpException($translator->trans('form_entry.access_denied', array(), 'exception'));
        }

        // Get Entries
        $form_entry_manager = $this->get('visualm.form.manager.form_entry');
        $form_entries = $form_entry_manager->getIndex([
            'form_id' => $request->query->get('form_id', ''),
            'search' => $request->query->get('search', '')
        ]);

        // Get distinct forms used
        $forms = [];
        foreach($form_entries as $form_entry) {
            if (!isset($forms[$form_entry->getForm()->getId()])) {
                $forms[$form_entry->getForm()->getId()] = $form_entry->getForm();
            }
        }

        // Create Excel
        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
        $phpExcelObject->getProperties()
            ->setCreator($translator->trans('form_entry.export.creator', [], 'backend'))
            ->setTitle($translator->trans('form_entry.export.title', [], 'backend'))
            ->setSubject($translator->trans('form_entry.export.subject', [], 'backend'));


        // Create headers
        $colindex = 1;
        $phpExcelObject->setActiveSheetIndex(0);
        $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex($colindex) . '1', $translator->trans('form_entry.export.header.toegevoegd', [], 'backend'));
        $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . '1', $translator->trans('form_entry.export.header.form', [], 'backend'));

        foreach($forms as $form) {
            foreach($form->getFields() as $field) {
                $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . '1', $field->getTitel());
            }
        }

        $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . '1', $translator->trans('form_entry.export.header.url', [], 'backend'));
        $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . '1', $translator->trans('form_entry.export.header.remote_addr', [], 'backend'));
        $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . '1', $translator->trans('form_entry.export.header.browser', [], 'backend'));
        $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . '1', $translator->trans('form_entry.export.header.landing_url', [], 'backend'));
        $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . '1', $translator->trans('form_entry.export.header.landing_referer', [], 'backend'));
        $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . '1', $translator->trans('form_entry.export.header.time_on_site_in_sec', [], 'backend'));

        $phpExcelObject->getActiveSheet()
            ->getStyle('A1:' . PHPExcel_Cell::stringFromColumnIndex($colindex) . '1')->getFont()->setBold(true);

        $datetime_formatter = new IntlDateFormatter(
            'nl',
            IntlDateFormatter::LONG,
            IntlDateFormatter::SHORT
        );

        // Add data
        $n = 2;
        foreach($form_entries as $form_entry) {
            /* @var $form_entry FormEntry */

            $rawdata = $form_entry->getRawdata();

            $colindex = 1;
            $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex($colindex) . $n, $datetime_formatter->format($form_entry->getToegevoegd()));
            $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . $n, $form_entry->getForm()->getTitel());

            foreach($forms as $form) {
                foreach($form->getFields() as $field) {
                    if ($form->getId() == $form_entry->getForm()->getId() AND isset($rawdata[$field->getReferentie()])) {
                        $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . $n, $rawdata[$field->getReferentie()]);
                    } else {
                        $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . $n, '');
                    }
                }
            }

            $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . $n, $form_entry->getUrl());
            $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . $n, $form_entry->getRemoteAddr());
            $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . $n, $form_entry->getBrowser());
            $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . $n, $form_entry->getLandingUrl());
            $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . $n, $form_entry->getLandingReferer());
            $phpExcelObject->getActiveSheet()->setCellValue(PHPExcel_Cell::stringFromColumnIndex(++$colindex) . $n, $form_entry->getTimeOnSiteInSec() !== null ? ($form_entry->getTimeOnSiteInSec() . ' sec.') : '');
            $n++;
        }

        // Set with to auto
        foreach (range('A', PHPExcel_Cell::stringFromColumnIndex($colindex)) as $col) {
            $phpExcelObject->getActiveSheet()
                ->getColumnDimension($col)
                ->setAutoSize(true);
        }

        // Set alignment
        foreach (range('A', PHPExcel_Cell::stringFromColumnIndex($colindex)) as $col) {
            foreach(range(1, $n) as $row) {
                $phpExcelObject->getActiveSheet()->getStyle($col . $row)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP);
                $phpExcelObject->getActiveSheet()->getStyle($col . $row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            }
        }

        // Name sheet
        $phpExcelObject->getActiveSheet()->setTitle($translator->trans('form_entry.export.sheetname', [], 'backend'));
        $phpExcelObject->setActiveSheetIndex(0);

        // Create the writer
        $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
        $response = $this->get('phpexcel')->createStreamedResponse($writer);

        // Add headers
        $response->headers->set('Content-Type', 'application/vnd.ms-excel; charset=utf-8');
        $response->headers->set('Pragma', 'public');
        $response->headers->set('Cache-Control', 'maxage=1');

        return $response;
    }


}
