<?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\SupplierEntity;
use RxConnexionBundle\Entity\SupplierFileEntity;
use RxConnexionBundle\Entity\SupplierStatusEntity;
//use RxConnexionBundle\Entity\UserNotifEntity;
use RxConnexionBundle\Form\SupplierForm;

/**
 * @Route("/admin/supplier")
 */
class SupplierController extends Controller
{
    /**
     * @Route("", name="supplier")
     */
    public function indexAction(Request $request) {

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

        return $this->render('@RxConnexion/Supplier/index.html.twig', array(
            'title' => 'Manage Supplier',
            'page_title' => 'Manage Supplier',
            'javascripts' => array('rxconnexion/admin/js/supplier/supplier.js?v=1.0.1'),
            'status' =>  $request->get('status')
        ));
    }

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

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

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

        if($this->get('rx_connexion.authService')->isLoggedIn()) {
            $result = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:SupplierEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

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

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

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

        if($this->get('rx_connexion.authService')->isLoggedIn()) {
            $result = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:SupplierEntity')->ajax_list_for_canvassing($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/form/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "supplier_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 Supplier New', 'Admin Supplier Update'))) return $authService->redirectToHome();

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

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

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

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

            $supplier_form = $request->get($form->getName());
            $result = $this->processForm($supplier_form, $supplier, $form, $request);

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

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

        return $this->render('@RxConnexion/Supplier/form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/supplier/supplier_form.js'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'supplier' => $supplier

        ));
    }

    private function processForm($supplier_form, $supplier, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:SupplierEntity')->validate($supplier_form);

        if(!count($errors)) {

            switch($supplier_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

//                        $authService = $this->get('rx_connexion.authService');
//                        $user = $authService->getUser();
//                        if(!$authService->isLoggedIn()) {
//                            return new JsonResponse(array('success' => false));
//                        }


//                        $city = $em->getRepository('RxConnexionBundle:CityEntity')->find($supplier_form['city_id']);
//
//                        if($city && $city->getDescriptionAndProvinceDescription() === $supplier_form['city_description']) $supplier->setCity($city);
//
                        $em->persist($supplier);
//
//                        $supplierStatus = new SupplierStatusEntity();
//                        $supplierStatus->setSupplier($supplier);
//                        $supplierStatus->setUser($user);
//                        $supplierStatus->setStatus(SupplierStatusEntity::APPROVAL_DESCRIPTION_PENDING);
//                        $supplierStatus->setApprovalDescription(SupplierStatusEntity::APPROVAL_DESCRIPTION_PENDING);
//                        $supplierStatus->setNote('Supplier Created');
//                        $supplierStatus->setBatchNo(1);
//                        $em->persist($supplierStatus);
                        $em->flush();

//                        $newAT = new AuditTrailEntity();
//                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                        $newAT->entity = $supplier;
//                        $newAT->setRefTable('supplier');
//                        $newAT->parseInformation('New');
//                        $em->persist($newAT);
//                        $em->flush();

//                        $this->get('rx_connexion.glAccountService')->processCmsSlByLink('Supplier', $supplier);

                        $this->process_children($supplier, $request);

                        $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

//                    $supplier_obj = $em->getRepository('RxConnexionBundle:SupplierEntity')->find($supplier_form['id']);
//
//                    $newAT = new AuditTrailEntity();
//                    $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                    $newAT->entity = $supplier_obj;
//                    $newAT->setRefTable('supplier');
//                    $newAT->parseOriginalDetails();
//
//                    $city = $em->getRepository('RxConnexionBundle:CityEntity')->find($supplier_form['city_id']);
//
//                    if($city && $city->getDescriptionAndProvinceDescription() === $supplier_form['city_description']) $supplier_obj->setCity($city);
//                    else $supplier_obj->setCity(null);
//
//                    $supplier_obj->setCode($supplier_form['code']);
//                    $supplier_obj->setDescription($supplier_form['description']);
//                    $supplier_obj->setMobileNo($supplier_form['mobile_no']);
//                    $supplier_obj->setPhoneNo($supplier_form['phone_no']);
//                    $supplier_obj->setEmail($supplier_form['email']);
//                    $supplier_obj->setContactPerson($supplier_form['contact_person']);
//                    $supplier_obj->setStreet($supplier_form['street']);
//                    $supplier_obj->setNote($supplier_form['note']);
//                    $supplier_obj->setPaymentType($supplier_form['payment_type']);
//                    $supplier_obj->setPaymentTerm($supplier_form['payment_term']);
//                    $supplier_obj->setFax($supplier_form['fax']);
//                    $supplier_obj->setTinNo($supplier_form['tin_no']);
//                    $supplier_obj->setStartDate($supplier_form['start_date']);
//                    $supplier_obj->setEndDate($supplier_form['end_date']);
//
//                    $newAT->parseInformation('Update');
//                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {
                        $em->flush();

    //                    $this->get('rx_connexion.glAccountService')->processCmsSlByLink('Supplier', $supplier_obj);

                        $this->process_children($supplier, $request);

                        $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

//                    $supplier = $em->getRepository('RxConnexionBundle:SupplierEntity')->find($supplier_form['id']);
                    $supplier->setIsDeleted(true);

//                    $newAT = new AuditTrailEntity();
//                    $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                    $newAT->entity = $supplier;
//                    $newAT->setRefTable('supplier');
//                    $newAT->parseInformation('Delete');
//                    $em->persist($newAT);

                    $em->flush();

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

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

                    break;
            }

            $result['success'] = true;

        } else {

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

            $result['success'] = false;
        }

        return $result;
    }

    private function process_children(SupplierEntity $supplier, Request $request) {

        $otherForm = $request->get('otherForm');

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

        $supplierFiles = $supplier->getSupplierFiles();
        if(count($supplierFiles)) {
            foreach($supplierFiles as $supplierFile) {
                if(!isset($otherForm['files']) || !in_array($supplierFile->getIdEncoded(), $otherForm['files'])) {
                    $em->remove($supplierFile);
                }
            }
            $em->flush();
            $em->refresh($supplier);
        }

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

                    $newSupplierFile = new SupplierFileEntity();
                    $newSupplierFile->setSupplier($supplier);

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

                    if(move_uploaded_file($tmpName, $uploadFile)) {

                        $newSupplierFile->setFileDesc($_FILES['files']['name'][$key]);
                        $newSupplierFile->setParsedFileDesc($baseName);
                        $em->persist($newSupplierFile);
                        $em->flush();
                    }
                }
            }
        }

        return true;
    }

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

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

        $result = array(
            'query' => 'suppliers',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:SupplierEntity')->autoCompleteSuggestions($q)
        );

        return new JsonResponse($result);
    }

    /**
     * @Route("/autocomplete2", name="supplier_autocomplete2")
     */
    public function autocomplete2Action(Request $request) {

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

        $result = array(
            'query' => 'suppliers',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:SupplierEntity')->autoCompleteSuggestions2($q)
        );

        return new JsonResponse($result);
    }

    /**
     * @Route("/file/download/{id}", name="supplier_file_download")
     */
    public function file_downloadAction($id) {

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

            $supplierFile = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:SupplierFileEntity')->find(base64_decode($id));

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

            $handle = fopen($this->container->getParameter('project_path') . '/web/' . $supplierFile->getUploadDir() . '/' . $supplierFile->getParsedFileDesc(), 'rb');
            $chunkSize = 1024*1024;

            if($handle !== false) {

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

                fclose($handle);
            }
        }

        exit();
    }


    //FOR APPROVAL

    /**
     * @Route("/approval_form", name="supplier_approval_form")
     */
    public function approval_formAction(Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) {
            return new JsonResponse(array('success' => false));
        }

        $id = $request->query->get('id');
        $em = $this->getDoctrine()->getManager();
        $supplier = $em->getRepository('RxConnexionBundle:SupplierEntity')->find(base64_decode($id));

        if(!$supplier) {
            $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong, please try again.');
            return new JsonResponse(array('success' => false));
        }

        $userRequester = $em->getRepository('RxConnexionBundle:UserEntity')->findOneBy(array('username' => $supplier->getCreatedBy()));

        return new JsonResponse(array(
            'success' => true,
            'html' => $this->renderView('RxConnexionBundle:Supplier:approval_form.html.twig', array(
                'id' => $id,
                'supplier' => $supplier,
                'requesterFullName' => $userRequester ? $userRequester->getFullName() : ''
            ))
        ));
    }

//    /**
//     * @Route("/approval_save", name="supplier_approval_save")
//     */
//    public function approval_saveAction(Request $request) {
//
//        $authService = $this->get('rx_connexion.authService');
//        if(!$authService->isLoggedIn()) {
//            return new JsonResponse(array('success' => false));
//        }
//
//        $form = $request->get('form');
//
//        $em = $this->getDoctrine()->getManager();
//        $supplier = $em->getRepository('RxConnexionBundle:SupplierEntity')->find(base64_decode($form['id']));
//
//        if(!$supplier) {
//            $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong, please try again.');
//            return new JsonResponse(array('success' => false));
//        }
//
//        $user = $authService->getUser();
//
//
//        if('a' === $form['axn']) {
//
//            $supplierStatus = new SupplierStatusEntity();
//            $supplierStatus->setSupplier($supplier);
//            $supplierStatus->setUser($user);
//            $supplierStatus->setStatus(SupplierStatusEntity::APPROVAL_DESCRIPTION_APPROVED);
//            $supplierStatus->setApprovalDescription(SupplierStatusEntity::APPROVAL_DESCRIPTION_APPROVED);
//            $supplierStatus->setNote($form['note']);
//            $supplierStatus->setBatchNo(1);
//            $em->persist($supplierStatus);
//
//            $supplier->setStatus(SupplierEntity::SUPPLIER_APPROVED);
//            $supplier->setStartDate(date('Y-m-d'));
//            $notifDetail = $supplier->getDescription() . ' ' . $supplier->getId();
//
//            $newUserNotif = new UserNotifEntity();
//            $newUserNotif->setUser($user);
//            $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
//            $newUserNotif->setRef('supplier');
//            $newUserNotif->setRefId($supplier->getId());
//            $newUserNotif->setDetail($notifDetail);
//            $em->persist($newUserNotif);
//
//            $em->flush();
//
//            return new JsonResponse(array(
//                'success' => true,
//                'msg' => 'Record successfully approved.'
//            ));
//
//        } else { // 'r' === $form['axn']
//
//            $supplierStatus = new SupplierStatusEntity();
//            $supplierStatus->setSupplier($supplier);
//            $supplierStatus->setUser($user);
//            $supplierStatus->setStatus(SupplierStatusEntity::APPROVAL_DESCRIPTION_REJECTED);
//            $supplierStatus->setApprovalDescription(SupplierStatusEntity::APPROVAL_DESCRIPTION_REJECTED);
//            $supplierStatus->setNote($form['note']);
//            $supplierStatus->setBatchNo(1);
//            $em->persist($supplierStatus);
//
//            $supplier->setStatus(SupplierEntity::SUPPLIER_REJECTED);
//            $supplier->setStartDate(\DateTime::createFromFormat('Y-m-d H:i:s', date('Y-m-d')));
//            $notifDetail = $supplier->getDescription() . ' ' . $supplier->getId();
//
//            $newUserNotif = new UserNotifEntity();
//            $newUserNotif->setUser($user);
//            $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
//            $newUserNotif->setRef('supplier');
//            $newUserNotif->setRefId($supplier->getId());
//            $newUserNotif->setDetail($notifDetail);
//            $em->persist($newUserNotif);
//
//            $em->flush();
//
//            return new JsonResponse(array(
//                'success' => true,
//                'msg' => 'Record successfully rejected.'
//            ));
//        }
//    }
}
