<?php

namespace RxConnexionBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

use RxConnexionBundle\Entity\AuditTrailEntity;
use RxConnexionBundle\Entity\PortalEntity;

use RxConnexionBundle\Form\PortalForm;

/**
 * @Route("/main/portal")
 */
class PortalController extends Controller
{
    /**
     * @Route("", name="portal")
     */
    public function indexAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Portal'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->findBy(array(
            'isDeleted' => false,
        ));

        return $this->render('@RxConnexion/Portal/index.html.twig', array(
            'title' => 'Manage Portal',
            'page_title' => 'Manage Portal',
            'javascripts' => array('rxconnexion/admin/js/portal/portal.js?v=1.0.0'),
            'companyList' => $company
        ));
    }

    /**
     * @Route("/ajax_list", name="portal_ajax_list")
     */
    public function ajax_list(Request $request) {

        $get = $request->query->all();

        $result = array(
            "draw" => intval($get['draw']),
            "recordsTotal" => 0,
            "recordsFiltered" => 0,
            "data" => array()
        );

        $authService = $this->get('rx_connexion.authService');
        if($authService->isLoggedIn()) {

            $hasUpdate = $authService->isUserHasAccesses(array('Admin Portal Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PortalEntity')->ajax_list($get, $this->get('session')->get('userData'));

            foreach($data['results'] as $row) {

                $id = base64_encode($row['id']);
                $action = '';
                $downloadUrl = $this->generateUrl('portal_file_download', array(
                    'id' => $id
                ));
                if($hasUpdate) {
                    $url = $this->generateUrl('portal_form', array(
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }

                $values = array(
                    $row['account_desc'],
                    $row['company_desc'],
                    $row['fileType_desc'],
                    "<a href='$downloadUrl'>". $row['description'] . "</a>" ,
                    $row['note'],
                    $action
                );

                $result['data'][] = $values;
            }

            $result['recordsTotal'] = $data['total'];
            $result['recordsFiltered'] = $data['total'];
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/form/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "portal_form"
     * )
     */
    public function formAction($action, $id, Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Portal New', 'Admin Portal Update'))) return $authService->redirectToHome();

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

        $portal = $em->getRepository('RxConnexionBundle:PortalEntity')->find(base64_decode($id));
        if(!$portal) {
            $portal = new PortalEntity();
        }

        $formOptions = array('action' => $action);
        $form = $this->createForm(PortalForm::class, $portal, $formOptions);

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

            $portal_form = $request->get($form->getName());
            $result = $this->processForm($portal_form, $portal, $form, $request);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('portal'), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('portal_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('portal_form'), 302);
                }
            } else {
                $form->submit($portal_form, false);
            }
        }

        $title = ($action === 'n' ? 'New' : 'Update') . ' File';

        return $this->render('@RxConnexion/Portal/form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/portal/portal_form.js?v=1.0.1'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id
        ));
    }

    private function processForm($portal_form, $portal, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:PortalEntity')->validate($portal_form);

        if(!count($errors)) {

            switch($portal_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $em->persist($portal);
                        $em->flush();
                        if(isset($_FILES['form']) && !empty($_FILES['form']['tmp_name']['file'])) {

                            $baseName = $portal->getId() . '-' . time() . '.' . pathinfo($_FILES['form']['name']['file'], PATHINFO_EXTENSION);
                            $uploadFile = $portal->getUploadRootDir() . '/' . $baseName;

                            if (move_uploaded_file($_FILES['form']['tmp_name']['file'], $uploadFile)) {
                                $portal->removeFile();
                                $portal->setDescription($_FILES['form']['name']['file']);
                                $portal->setParsedDescription($baseName);
                                $em->flush();

                            }
                        }

                        $newAT = new AuditTrailEntity(
                            'Portal',
                            $em->getClassMetadata(PortalEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $portal;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Saved.');

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Portal',
                        $em->getClassMetadata(PortalEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $portal;
                    $newAT->parseOriginalDetails();

                    $portal_obj = $em->getRepository('RxConnexionBundle:PortalEntity')->find($portal_form['id']);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $newAT->parseDetails();
                        $em->persist($newAT);

                        $em->flush();
                        if(isset($_FILES['form']) && !empty($_FILES['form']['tmp_name']['file'])) {

                            $baseName = $portal_obj->getId() . '-' . time() . '.' . pathinfo($_FILES['form']['name']['file'], PATHINFO_EXTENSION);
                            $uploadFile = $portal_obj->getUploadRootDir() . '/' . $baseName;

                            if (move_uploaded_file($_FILES['form']['tmp_name']['file'], $uploadFile)) {
                                $portal_obj->removeFile();
                                $portal_obj->setDescription($_FILES['form']['name']['file']);
                                $portal_obj->setParsedDescription($baseName);
                                $em->flush();

                            }
                        }

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Portal',
                        $em->getClassMetadata(PortalEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $portal;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($portal);
                        $portal->setIsDeleted(true);

                        $em->flush();

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Deleted.');

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;
            }

            $result['success'] = true;

        } else {

            foreach($errors as $error) {
                $this->get('session')->getFlashBag()->add('error_messages', $error);
            }

            $result['success'] = false;
        }

        return $result;
    }

    /**
     * @Route(
     *      "/file/download/{id}",
     *
     *      name = "portal_file_download"
     * )
     */

    public function patient_file_downloadAction($id){

        $em = $this->getDoctrine()->getManager();
        $portal = $em->getRepository('RxConnexionBundle:PortalEntity')->find(base64_decode($id));
        header('Content-Disposition: attachment; filename="' . $portal->getDescription() . '"');
        $handle = fopen(realpath($portal->getUploadRootDir()) . '/' . $portal->getParsedDescription(), 'rb');
        $chunkSize = 1024*1024;

        if($handle !== false) {

            while (!feof($handle)) {
                $buffer = fread($handle, $chunkSize);
                echo $buffer;
                ob_flush();
                flush();
            }

            fclose($handle);
        }

        exit();
    }

    /**
     * @Route("/autocomplete", name="portal_autocomplete")
     */
    public function autocompleteAction(Request $request) {

        $q = $request->get('query');

        $result = array(
            'query' => 'portals',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PortalEntity')->autocomplete_suggestions($q)
        );

        return new JsonResponse($result);
    }
}
