<?php

namespace OfficeBrain\Bundle\OrderBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
 * @author Employee Id: 410175
 * OB eCommerce Product - Order
 * - OrderProcess for user
 * @Route("/api/v1", defaults={"rule_service"="rule_charges"})
 */
class ApiOrderController extends OrderController
{
    /**
     * @author Employee Id: 410175
     * To set member variables default value
     */
    public function __construct()
    {
        parent::__construct();
        $this->paymentManager = null;
    }

    /**
     * @author Employee Id: 410175
     * To unset member variables
     */
    public function __destruct()
    {
        parent::__destruct();
        unset($this->paymentManager);
    }

    /**
     * @author Employee Id: 4203
     * Create various objects required action in this class
     */
    public function initAction()
    {
        parent::initAction();
    }

    /*
     * @author Employee Id: 410175
     * Description : Use to save order data
     *
     * @param 1 : No paramater
     *
     * @return type : json
     *
     * @throws Exception: Null
     *
     * @Route("/{_locale}/set-product-to-cart", name="office_brain_orderbundle_order_setproducttocart_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Order",
     *      description="Add Item to cart",
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      },
     *      input = {
     *      	"class" = "\OfficeBrain\Bundle\OrderBundle\Form\ApiOrderType"
     *      },
     *      requirements={
     *             {"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *             {"name"="_locale", "dataType"="string",  "default"="en_us"},
     *             {"name"="order_type", "dataType"="string", "description"="set sample,blank or decoration"},
     *      },  
     * )
     * 
     * @Method({"POST"})
     * /
    public function setProductToCartAction()
    {
        $this->initAction();

        if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw new AccessDeniedException();
        }

        $convertJsonToAry = array(
                'color',
                'shipping_method',
                'imprint',
                'fax_proof',
                'paper_proof',
                'product_proof',
        );
        foreach ($convertJsonToAry as $fieldName) {
            if ($this->request->request->has($fieldName) && $this->request->request->get($fieldName) != null && $this->request->request->get($fieldName) != 'null') {
                $fieldVal = $this->request->request->get($fieldName);
                $fieldVal = json_decode($fieldVal, true);
                $this->request->request->set($fieldName, $fieldVal);
            }
        }

        // $maxSelectableColor = $this->request->get('max_selectable_color');
        $this->validationManager->setMaxNoOfColor($this->request->get('max_selectable_color'));
        $this->validationManager->setProjectConfiguration($this->productDetailconfigurationRule);
        $this->validationManager->setRules('color', 'color', 'color');
        $this->validationManager->setRules('imprint', 'printPosition', 'printPosition');
        $this->validationManager->setRules('fax_proof', 'faxProof', 'printPositionProof');
        $this->validationManager->setRules('paper_proof', 'paperProof', 'printPositionProof');
        $this->validationManager->setRules('shipping_method', 'shippingMethod', 'shippingMethod');
        //$this->validationManager->setRules('special_instruction', 'required', 'specialInstruction');
        $errorMessage = null;
        if ($this->validationManager->isValid()) {
            if ($this->request->request->has('imprint') && $this->request->request->get('imprint') != null && $this->request->request->get('imprint') != 'null') { // Code to upload media image to artwork
                $imprintData = $this->request->request->get('imprint');
                foreach ($imprintData as $imprintKey => $imprints) {
                    if (isset($imprints ['art_work_text']) && isset($imprints ['art_work_text'] ['logo'])) {
                        foreach ($imprints ['art_work_text'] ['logo'] as $logoKey => $logo) {
                            $logoAry = explode('/', $logo);
                            $logoName = '';
                            if (($logoCount = count($logoAry)) > 1) {
                                $logoName = $logoAry [$logoCount - 1];
                            } else {
                                $logoName = $logoAry [0];
                            }

                            $isArtWorkUploaded = $this->copyMediaImageToArtwork($logo, $logoName);
                            $imprintData [$imprintKey] ['art_work_text'] ['logo'] [$logoKey] = ($isArtWorkUploaded != null ? $isArtWorkUploaded : $logo);
                        }
                    }
                }
                $this->request->request->set('imprint', $imprintData);
            }

            $status = $this->orderManager->setAddToCart();

            switch ($status) {
                case 'ERROR_MAX_LIMIT_REACHED' :
                    $errorMessage = $this->get('translator')->trans('order.max_product_order', array(
                            '%count%' => $this->inlineViewProductMaxLimit,
                    ));
                    break;
                case 'ERROR_PRODUCT_ALREADY_EXISTS' :
                    $errorMessage = $this->get('translator')->trans('order.product_already_exists');
                    break;
                case 'SUCCESS' :
                    break;
                default :
            }
            $totalProduct = $this->orderManager->getTotalCount();
        } else {
            $errorMessage = $this->validationManager->isError();
        }

        if ($errorMessage == null) {
            return array(
                    'status' => 'success',
                    'status_code' => 1,
                    'data' => array(
                            'total_product' => $totalProduct,
                    ),
            );
        } else {
            return array(
                    'status' => 'error',
                    'status_code' => 0,
                    'message' => $errorMessage,
            );
        }
    }

    /**
     * To get cart product list.
     * 
     * @author Employee Id: 410175
     * Description : Use to Checkout the order
     *
     * @param 1 : No paramater
     *
     * @return type : json
     *
     * @throws Exception: Null
     * 
     * @Route("/{_locale}/checkout-detail",	name="office_brain_orderbundle_order_checkoutdetail_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Order",
     *      description="To Checkout Order data.",
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      },
     *      requirements={
     *             {"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *             {"name"="_locale", "dataType"="string",  "default"="en_us"},
     *      },  
     * )
     * 
     * @Template()
     * 
     * @Method("GET") 
     * /
    public function checkoutDetailAction()
    {
        if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw new AccessDeniedException();
        }

        $this->initAction();
        $this->reponse = array();
        $this->reponse ['total_record'] = $this->orderManager->getTotalCount();
        if ($this->reponse ['total_record'] > 0) {
            $this->reponse ['checkout_product_list'] = $this->orderManager->getCartList();

            return array(
                    'status' => 'success',
                    'status_code' => 1,
                    'data' => $this->reponse,
            );
        } else {
            return array(
                    'status' => 'error',
                    'status_code' => 0,
                    'message' => 'No item found.',
            );
        }
    }

    /**
     * @author Employee Id: 410175
     * @Route("/{_locale}/payment", name="office_brain_paymentbundle_payment_preparepayment_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Order",
     *      description="To Submit Order with payment detail.",
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      },
     *      input = {
     *      	"class" = "\OfficeBrain\Bundle\PaymentBundle\Form\InvoiceType"
     *      },
     *      requirements={
     *             {"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *             {"name"="_locale", "dataType"="string",  "default"="en_us"},
     *             {"name"="payment_type", "dataType"="string", "description"="set invoice,paypalExpress or authorizeDotNetAim"},
     *      },  
     * )
     * 
     * @Template()
     * @Method("POST")
     * /
    public function preparePaymentAction()
    {
        if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw new AccessDeniedException();
        }

        $this->initAction();

        $this->reponse ['total_record'] = $this->orderManager->getTotalCount();
        if ($this->reponse ['total_record'] <= 0) {
            return array(
                    'status' => 'error',
                    'status_code' => 0,
                    'message' => 'No item found.',
            );
        }

        $this->paymentManager = $this->get('office_brain_payment_manager');

        $this->response = $this->paymentManager->preparePayment($this, $jsonFormat = true);
        $errorMsg = $successMsg = null;
        switch ($this->response ['status']) {
            case 'CAPTURE' :
                $successMsg = 'Successfully submitted.';
                break;
            case 'CAPTURE_AIM' :
                // TODO:what we need to do for this
                // return $this->forward('PayumBundle:Capture:do', array('payum_token' => $this->response['payum_token']));
                $successMsg = 'Successfully submitted.';
                break;
            case 'INVOICE' :
                $this->paymentSuccessAction();
                $successMsg = 'Successfully submitted.';
                break;
            case 'NOTVALIDATE' :
                $errorMsg = 'Not valid data.';
                break;
            default :
                $errorMsg = 'Not valid data.';
        }
        if ($errorMsg != null) {
            return array(
                    'status' => 'error',
                    'status_code' => 0,
                    'message' => $errorMsg,
            );
        } else {
            return array(
                    'status' => 'success',
                    'status_code' => 1,
                    'message' => $successMsg,
            );
        }
    }

    /**
     * @author Employee Id: 410175
     * @Route("/{_locale}/get-payment-list",name="office_brain_orderbundle_order_paymentlist_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Order",
     *      description="To Get all the Payment Methods.",
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      },
     *      requirements={
     *             {"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *             {"name"="_locale", "dataType"="string",  "default"="en_us"},
     *      },  
     * )
     * 
     * @Template()
     *  @Method ("POST")
     * /
    public function paymentListAction()
    {
        if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw new AccessDeniedException();
        }

        $this->initAction();
        $countryCode = explode('_', $this->locale);
        $paymentMethods = $this->thirdPartyManager->getPaymentCountryWise($countryCode [1]);
        $returnAry = array();

        foreach ($paymentMethods as $methodKey => $methodName) {
            $returnAry [] = array(
                    'key' => $methodKey,
                    'value' => $methodName,
            );
        }
        $returnAry [] = array(
                'key' => 'invoice',
                'value' => 'Pay through invoice',
        );

        return array(
                'status' => 'success',
                'status_code' => 1,
                'data' => $returnAry,
        );
    }

    /**
     * @author Employee Id: 410175
     * Description : Use to render view to add imprint location box.
     *
     * @param 1 : No paramater
     *
     * @return type : Ajax response in view.
     *
     * @throws Exception: Null
     *
     * @Route("/{_locale}/order-add-imprint-location", name="office_brain_orderbundle_order_addimprintlocation_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Order",
     *      description="To get Imprint Method from position.",
     *      requirements={     
     *      	{"name"="_locale", "dataType"="string", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=false, "description"="valid access token"},
     *      	{"name"="imprint_location_id", "dataType"="integer", "description"="valid imprint position id"},
     *      	{"name"="product_id", "dataType"="integer", "description"="valid product id"},
     *      },
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      }
     * )
     * 
     * @Template("")
     * @Method({"POST"})
     * /
    public function addImprintLocationAction()
    {
        $this->initAction();

        $imprintData = $this->orderManager->addImprintLocationMobileApi();

        if ($imprintData === false) {
            return array(
                    'status' => 'error',
                    'status_code' => 0,
                    'message' => 'Please enter productId & imprint location id.',
            );
        }

        return array(
                'status' => 'success',
                'status_code' => 1,
                'data' => $imprintData,
        );
    }

    /**
     * @author Employee Id: 410175
     *
     * Description : Use to submit guest user quote form.
     *
     * @param 1 : No paramater
     *
     * @return type : Form view and data.
     *
     * @throws Exception: Null
     *
     * @Route("/{_locale}/order-select-method", name="office_brain_orderbundle_order_selectMethod_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Order",
     *      description="To get No of color from selected Imprint Method id.",
     *      requirements={     
     *      	{"name"="_locale", "dataType"="string", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=false, "description"="valid access token"},
     *      	{"name"="imprint_id", "dataType"="integer", "description"="valid imprint position id"},
     *      	{"name"="method_id", "dataType"="integer", "description"="valid imprint method id"},
     *      	{"name"="product_id", "dataType"="integer", "description"="valid product id"},
     *      },
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      }
     * )
     * 
     * @Template("")
     * @Method({"POST"})
     * /
    public function selectMethodAction()
    {
        $this->initAction();
        $data = $this->orderManager->selectImprintMethodMobileApi();

        if ($data === false) {
            return array(
                    'status' => 'error',
                    'status_code' => 0,
                    'message' => 'Please select productId, ImprintId, MethodId.',
            );
        }

        return array(
                'status' => 'success',
                'status_code' => 1,
                'data' => $data,
        );
    }

    /**
     * @author Employee Id: 410175
     * Description : Use to show the list of product in this request quote.
     *
     * @param 1 : No paramater
     *
     * @return type : json
     *
     * @throws Exception: Null
     *
     * @Route("/{_locale}/order-select-color-request-quote", name="office_brain_orderbundle_order_selectColor_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Order",
     *      description="To get standard & PMS colors.",
     *      requirements={     
     *      	{"name"="_locale", "dataType"="string", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=false, "description"="valid access token"},
     *      	{"name"="imprint_id", "dataType"="integer", "description"="valid imprint position id"},
     *      	{"name"="product_id", "dataType"="integer", "description"="valid product id"},
     *      },
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      }
     * )
     * 
     * @Template("")
     * @Method({"POST"})
     * /
    public function selectColorAction()
    {
        $this->initAction();
        $standardImprintColor = $this->orderManager->getStandardImprintColorInformationMobileApi();
        $pmsColor = $this->container->getParameter('pms_color');

        return array(
                'imprint_id' => $this->request->get('imprint_id'),
                'product_id' => $this->request->get('product_id'),
                'standard_imprint_color' => $standardImprintColor,
                'pms_color' => $pmsColor,
        );
    }

    /**
     * @author Employee Id: 410175
     * Description : Use to get shopping cart configuration
     *
     * @param 1 : No paramater
     *
     * @return type : json
     *
     * @throws Exception: Null
     *
     * @Route("/{_locale}/get-shopping-cart-configuration", name="office_brain_orderbundle_order_getshoppingcartconfig_api")
     *
     * @ApiDoc(
     *      resource=true,
     *      section="Order",
     *      description="To get shopping cart configuration.",
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      },
     *      requirements={
     *             {"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *             {"name"="_locale", "dataType"="string",  "default"="en_us"},
     *      },
     * )
     *
     * @Method({"POST"})
     * /
    public function getShoppingCartConfiguationAction()
    {
        $this->initAction();

        if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw new AccessDeniedException();
        }

        return array(
                'status' => 'success',
                'status_code' => 1,
                'data' => $this->configurationRule,
        );
    }

    private function copyMediaImageToArtwork($imageWithUrl, $imageName)
    {
        if (($this->artworkFileURL.'/'.$imageName) == $imageWithUrl) {
            return $imageWithUrl;
        }

        $imageUpload = $this->imageLibraryManager->copyMedia($this->mediaFilePath, $this->artworkFilePath, $imageName, $imageName);

        if ($imageUpload != '') {
            return $this->artworkFileURL.'/'.$imageName;
        }

        return;
    }*/
}
