<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\FrequentlyAskedQuestionEntity;
use RxConnexionBundle\Entity\FrequentlyAskedQuestionFileEntity;
use RxConnexionBundle\Entity\TicketNoteEntity;
use RxConnexionBundle\Form\FrequentlyAskedQuestionForm;
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\Form\TicketForm;

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

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

        return $this->render('@RxConnexion/Faq/index.html.twig', array(
            'title' => 'Manage Faq',
            'page_title' => 'Manage Faq',
            'javascripts' => array('rxconnexion/admin/js/faq/faq.js?v=1.0.6')
        ));
    }

    /**
     * @Route("/ajax_list", name="faq_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 Faq Update'), false);

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

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

                $id = base64_encode($row['id']);
                $action = '';

                if($hasUpdate) {
                    $url = $this->generateUrl('faq_form', array(
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }

                $attachmentWithLink = '';
                if(isset($row['attachmentFile'])){
                    $attachmentWithLinks = array();
                    $attachmentDetails = explode(',' , $row['attachmentFile']);
                    foreach ($attachmentDetails as $attachmentDetail){
                        $attachmentDetailForIds = explode('~', $attachmentDetail);
                        $attachmentLink = !empty($attachmentDetailForIds[0]) ? $this->generateUrl('faq_file_download', array(
                            'faq_id' => base64_encode($attachmentDetailForIds[0])
                        )) : 'javascript:void(0)';
                        $attachmentWithLinks[] = isset($attachmentDetailForIds[1]) ? "<a href='$attachmentLink' target='_blank'> $attachmentDetailForIds[1]</a>" : '';
                    }
                    $attachmentWithLink = implode('<br />' ,$attachmentWithLinks);
                }

                $values = array(
                    $row['fileTypeDesc'],
                    $row['description'],
                    $attachmentWithLink,
                    $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 = "faq_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 Faq New', 'Admin Faq Update'))) return $authService->redirectToHome();

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

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

        $formOptions = array('action' => $action);
        $form = $this->createForm(FrequentlyAskedQuestionForm::class, $faq, $formOptions);
        if($request->getMethod() === 'POST') {

            $faq_form = $request->get($form->getName());
            $result = $this->processForm($faq_form, $faq, $form, $request);

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

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

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

    private function processForm($faq_form, $faq, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:FrequentlyAskedQuestionEntity')->validate($faq_form);

        if(!count($errors)) {

            switch($faq_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $em->persist($faq);

                        if(isset($_FILES['files']['tmp_name'])) {
                            foreach($_FILES['files']['tmp_name'] as $key => $tmpName) {
                                if(!empty($tmpName)) {

                                    $faqFile = new FrequentlyAskedQuestionFileEntity();
                                    $faqFile->setFrequentlyAskedQuestion($faq);

                                    $baseName = rand(0,999) . '-' . time() . '.' . pathinfo($_FILES['files']['name'][$key], PATHINFO_EXTENSION);
                                    $uploadFile = $faqFile->getUploadRootDir() . '/' . $baseName;
                                    if(move_uploaded_file($tmpName, $uploadFile)) {
                                        $faqFile->setFileDesc($_FILES['files']['name'][$key]);
                                        $faqFile->setParsedFileDesc($baseName);
                                        $em->persist($faqFile);
                                        $em->flush();
                                    }
                                }
                            }
                        }

//                        $newAT = new AuditTrailEntity(
//                            'FAQ',
//                            $em->getClassMetadata(FrequentlyAskedQuestionEntity::class)->getTableName(),
//                            AuditTrailEntity::AXN_NEW
//                        );
//                        $newAT->entity = $faq;
//                        $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(
//                        'FAQ',
//                        $em->getClassMetadata(FrequentlyAskedQuestionEntity::class)->getTableName(),
//                        AuditTrailEntity::AXN_UPDATE
//                    );
//                    $newAT->entity = $faq;
//                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);

                    if ($form->isValid()) {
//
//                        $newAT->parseDetails();
//                        $em->persist($newAT);

                        $formFaqFile = $request->get('otherForm');
                        $faqFile = $em->getRepository('RxConnexionBundle:FrequentlyAskedQuestionFileEntity')->findBy(array(
                            'frequentlyAskedQuestion' => $faq->getId()
                        ));


                        if(isset($_FILES['files']['tmp_name'])) {
                            foreach($_FILES['files']['tmp_name'] as $key => $tmpName) {
                                if(!empty($tmpName)) {

                                    $newFaqFile = new FrequentlyAskedQuestionFileEntity();
                                    $newFaqFile->setFrequentlyAskedQuestion($faq);

                                    $baseName = rand(0,999) . '-' . time() . '.' . pathinfo($_FILES['files']['name'][$key], PATHINFO_EXTENSION);
                                    $uploadFile = $newFaqFile->getUploadRootDir() . '/' . $baseName;

                                    if(move_uploaded_file($tmpName, $uploadFile)) {
                                        $newFaqFile->setFileDesc($_FILES['files']['name'][$key]);
                                        $newFaqFile->setParsedFileDesc($baseName);
                                        $em->persist($newFaqFile);
                                        $em->flush();
                                    }
                                }
                            }
                        }

                        if(isset($formFaqFile)) {
                            foreach($formFaqFile['files'] as $fplf) {
                                foreach($faqFile as $plf) {
                                    if(base64_decode($fplf) != $plf->getId()) {
                                        $faqFile2 = $em->getRepository('RxConnexionBundle:FrequentlyAskedQuestionFileEntity')->find($plf->getId());
                                        $faqFile2->removeFile();
                                        $faqFile2->setIsDeleted(true);
                                        $em->flush();
                                    }
                                }
                            }
                        } else {
                            foreach ($faqFile as $plf2) {
                                $plf2->removeFile();
                                $plf2->setIsDeleted(true);
                                $em->flush();
                            }

                        }

                        $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(
//                        'FAQ',
//                        $em->getClassMetadata(FrequentlyAskedQuestionEntity::class)->getTableName(),
//                        AuditTrailEntity::AXN_DELETE
//                    );
//                    $newAT->entity = $faq;
//                    $newAT->parseDetails();
//                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($faq);
                        $faq->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/{faq_id}",
     *
     *      name = "faq_file_download"
     * )
     */
    public function faq_file_downloadAction($faq_id){

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

            $faqFile = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:FrequentlyAskedQuestionFileEntity')->find(base64_decode($faq_id));

            header('Content-Disposition: attachment; filename="' . $faqFile->getFileDesc() . '"');

            $handle = fopen(realpath($faqFile->getUploadRootDir()) . '/' . $faqFile->getParsedFileDesc(), '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="faq_autocomplete")
     */
    public function autocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }
}
