<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\AccountUserReminderEntity;
use RxConnexionBundle\Entity\reminderMessageEntity;
use RxConnexionBundle\Form\AccountUserReminderForm;
use RxConnexionBundle\Form\reminderForm;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use RxConnexionBundle\Entity\AuditTrailEntity;
use RxConnexionBundle\Form\AccountForm;

/**
 * @Route("/main/account-user/reminder")
 */
class AccountUserReminderController extends Controller
{
    /**
     * @Route("/", name="account_user_reminder")
     */
    public function indexAction(Request $request)
    {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Account User Reminder'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $reminderType = $em->getRepository('RxConnexionBundle:ReminderTypeEntity')->findBy(array(
            'isDeleted' => 0
        ));

        //Date Filter
        $monthNow = date('n');
        $yearNow = date('Y');
        $yr=$yearNow;
        $monthFilter = array();
        $i = 0;
        for ($m=$monthNow; $m > $monthNow-12; $m--) {
            if($m <0){
                $yr = $yearNow-1;
            }
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $yr.' - '.$month;
            $monthFilter[$i]['value'] = $yr.'|'.abs($m);
            $i++;
        }

        return $this->render('@RxConnexion/Reminder/index.html.twig', array(
            'title' => 'Manage Reminders',
            'page_title' => 'Manage Reminders',
            'monthFilter'  => $monthFilter,
            'reminderType' => $reminderType,
            'javascripts' => array('rxconnexion/admin/js/reminder/reminder.js?v=1.0.1'),
        ));
    }

    /**
     * @Route("/ajax_list", name="account_user_reminder_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 Account User Reminder Update'), false);

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

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

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

                if($hasUpdate) {
                    $action = "<a class='action-button-style' href='javascript:void(0)' onclick='global_reminder.form(\"u\", $id)'>View/Update</a>";
                }

                $values = array(
                    #$row['id'],
                    $row['reminderType_description'],
                    $row['assigned_to'],
                    $row['startDate'],
                    $row['createdBy'],
                    $row['status'],
                    $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 = "reminder_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 reminder New', 'Admin reminder Update'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $reminder= $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->find(base64_decode($id));

        if(!$reminder) {
            $reminder= new AccountUserReminderEntity();
        }

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

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

            $reminder_form = $request->get($form->getName());
            $result = $this->processForm($reminder_form, $reminder, $form, $request);

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

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

        return $this->render('@RxConnexion/reminder/form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'javascripts' => array('rxconnexion/admin/js/reminder/reminder_form.js?v=1.0.0'),
            'reminderCreatorId' => $reminder->getAccountUser() ?  $reminder->getAccountUser()->getId() : ''
        ));
    }

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

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/autocomplete-accounts", name="account_autocomplete_reminder_account_user_account")
     */
    public function reminderAutocompleteAccountUser(Request $request) {

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

        $result = array(
            'query' => 'account_users',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:AccountUserReminderEntity')->reminderAutocompleteAccountUser($q, $userData['id'])
        );

        return new JsonResponse($result);
    }




    private function processForm($accountUserReminder_form,AccountUserReminderEntity $accountUserReminder, $form, Request $request) {

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');

        $errors = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->validate($accountUserReminder_form,$userData);

        if(!count($errors)) {

            switch($accountUserReminder_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

                        $em->persist($accountUserReminder);
                        $em->flush();

                        /*$newAT = new AuditTrailEntity(
                            'reminder',
                            $em->getClassMetadata(AccountUserReminderEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $reminder;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();*/

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

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

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

                    break;

                case 'u': // update

                    /*$newAT = new AuditTrailEntity(
                        'reminder',
                        $em->getClassMetadata(AccountUserReminderEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $reminder;
                    $newAT->parseOriginalDetails();*/

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $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

                    $form->handleRequest($request);

                    /*$newAT = new AuditTrailEntity(
                        'reminder',
                        $em->getClassMetadata(AccountUserReminderEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $reminder;
                    $newAT->parseDetails();
                    $em->persist($newAT);*/

                    if($form->isValid()) {

                        //$agency = $em->getRepository('RxConnexionBundle:AgencyEntity')->find($reminder_form['id']);
                        //$em->remove($reminder);
                        $accountUserReminder->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 {

            $result = array();
            foreach($errors as $error) {
                $result['errors'][] = $error;
            }

            $result['success'] = false;
        }

        return $result;
    }



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

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Account User Reminder New', 'Admin Account User Reminder Update'))) return $authService->redirectToHome();
        $get = $request->query->all();

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

        $defaultPatient = null;
        if(isset($get['pt'])){
            $defaultPatient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($get['pt']));
        }

        $accountUserReminder = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->find($id);
        if(!$accountUserReminder) {
            $accountUserReminder = new AccountUserReminderEntity();
        }

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

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

            $accountUserReminder_form = $request->get($form->getName());
            $result = $this->processForm($accountUserReminder_form, $accountUserReminder, $form, $request);
            if($result['success']){
                return new JsonResponse(array(
                    'success' => true,
                ));
            } else {
                return new JsonResponse(array(
                    'success' => false,
                    'errors' => $result['errors']
                ));
            }
            
        }

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

        $result = array();
        if($authService->isLoggedIn()) {
            $result['html'] = $this->renderView('@RxConnexion/Reminder/global_reminder_form.html.twig', array(
                'title'          => $title,
                'page_title'     => $title,
                'form'           => $form->createView(),
                'action'         => $action,
                'id'             => $id,
                'defaultPatient' => $defaultPatient
            ));
            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/list/global", name="account_user_reminder_list_global")
     */
    public function reminder_list_globalAction(Request $request) {

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

        $result = array();
        $userData = $this->get('session')->get('userData');

        $em = $this->getDoctrine()->getManager();
        $reminders = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->findForUser($userData);

        $result['html'] = $this->renderView('@RxConnexion/Reminder/global_reminder_list.html.twig', array(
            'reminders' => $reminders
        ));
        $result['success'] = true;

        return new JsonResponse($result);
    }

    /**
     * @Route("/count/global", name="account_user_reminder_count_global")
     */
    public function reminder_count_globalAction(Request $request) {

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

        $result = array(
            'success' => false,
        );
        $userData = $this->get('session')->get('userData');
        $em = $this->getDoctrine()->getManager();
        $reminders = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->findForUser($userData);

        $result['count'] = count($reminders);
        $result['success'] = true;

        return new JsonResponse($result);
    }

}