<?php

namespace Webkul\WooCommerceBundle\Controller\Rest;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Webkul\WooCommerceBundle\Entity\CredentialConfig;
use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;

/**
 * Configuration rest controller in charge of the WooCommerce connector configuration managements
 */
class CredentialController extends Controller
{
    const READONLY_CREDENTIALS = 'credentailsReadonlyUrls';
    const QUICK_EXPORT_CODE = 'woocommerce_product_quick_export';
    
    const SECTION = 'woocommerce_connector';

    const MAPPING_SECTION = 'woccomerce_store_mapping';
    const DEFAULTS_SECTION = 'woocommerce_connector_defaults';
    const QUICKSETTING_SECTION = "woocommerce_quicksettings";
    const OTHER_MAPPING_SECTION = 'woocommerce_other_mappings';
    const OTHER_MAPPING = 'woocommerce_connector_othermapping';


    /**
     * add credentials
     *
     * @AclAncestor("webkul_akeneo_woocommerce_connector_configuration")
     *
     * @return JsonResponse
     */
   
    public function addAction(Request $request)
    {   
        $id = $request->query->get('identifier'); #$request->get('id');
        $em = $this->getDoctrine()->getManager();
        $content = $request->getContent();
        $data = json_decode($content, true);
        $connectorService = $this->get('woocommerce.connector.service');
        $isExistCredential = '';
       
        if($id) {            
            $credential = $em->getRepository(CredentialConfig::Class)->findOneById($id);           
        } else {          
            $credential = new CredentialConfig();                       
        }

        if (!empty($data['consumerSecret']) && $data['consumerSecret'] === str_repeat('*', 20)) {
            $dataParam = $connectorService->getAllCredentials($id);
            $data['consumerSecret'] = $dataParam['consumerSecret'];
        } 
     //  dump($request->getContent());die;
        if(!empty($credential) && !empty($data['consumerKey']) && !empty($data['consumerSecret']) && !empty($data['shopUrl'])) {
                              
                $isCredentialsValid = $connectorService->checkCredentials($data);
                
                if ($isCredentialsValid == true) {
                    $credential->setShopUrl($data['shopUrl']);
                    $credential->setConsumerKey($data['consumerKey']);
                    $credential->setConsumerSecret($data['consumerSecret']);

                    $host = $request->getHost();
                    if ($request->getPort() && !in_array($request->getPort(), [443, 80])) {
                        $host .= ':' . $request->getPort();
                    }
                    $data['hostname'] = $host;
                    $data['scheme'] = $request->getScheme();

                    if (isset($data['extraResources']) && !empty($data['extraResources'])) {
                        $credential->setextraResources($data['extraResources']);
                    }
                   
                    $em->persist($credential);
                    $em->flush();

                    $data= ['meta' => [
                        'id' => $credential->getId()
                    ]];
                    
                    return new JsonResponse($data);
                }
            
        } else {
            return new JsonResponse([ 'shopUrl' => 'Shop URL is required', 'consumerKey' => 'Consumer Key  is required','consumerSecret' => 'Consumer Secret Key is required'], Response::HTTP_BAD_REQUEST);
        }
        

        return new JsonResponse([ 'shopUrl' => 'Error! invalid credentials' ], Response::HTTP_BAD_REQUEST);
    }
    /**
     * toogle status
     *
     * @AclAncestor("webkul_akeneo_woocommerce_connector_configuration")
     *
     * @return JsonResponse
     */
    public function toggleStatusAction($id, Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $credential = $em->getRepository(CredentialConfig::class)->findOneById($id);

        if ($credential) {
            $credential->setActive($credential->getActive() ? 0 : 1);

            if($credential->getActive() == 0) {
                $credential->setDefaultSet(0);
            }

            $em->persist($credential);
            $em->flush();
        }

        if (!$request->isXmlHttpRequest()) {
            return $this->redirect($this->generateUrl('webkul_woocommerce_connector_configuration'));
        }

        return new JsonResponse(['successful' => true]);
    }

    /**
     * delete credentials
     *
     * @AclAncestor("webkul_akeneo_woocommerce_connector_configuration")
     *
     * @return JsonResponse
     */
    public function deleteAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $credential = $em->getRepository(CredentialConfig::class)->findOneById($id);
        
        if ($credential) {
            //Skip the Readonly Parameter to delete
            $host = $credential->getShopUrl();
            
            if ($this->container->hasParameter(self::READONLY_CREDENTIALS) && in_array($host, $this->container->getParameter(self::READONLY_CREDENTIALS))) {
                return new JsonResponse(['successful' => false], 400);
            }
            
            $em->remove($credential);
            $em->flush();
        }

        return new JsonResponse([]);
    }


    /**
     * get credential
     *
     * @AclAncestor("webkul_akeneo_woocommerce_connector_configuration")
     *
     * @return JsonResponse
     */
    

    public function getAction($identifier)
    {   
        $data = [];
        $em = $this->getDoctrine()->getManager();
        $credential = $em->getRepository(CredentialConfig::class)->findOneById($identifier);

        if ($credential) {
            $data = [
                'id' => $credential->getId(),
                'shopUrl' => $credential->getShopUrl(),
                'consumerKey' => $credential->getConsumerKey(),
                'consumerSecret' => str_repeat("*", 20),
                'extraResources' => $credential->getextraResources()
                
            ];
            
            if ($credential->getConsumerKey()) {
                $result = json_decode($credential->getConsumerKey(), true);
                if ($result) {
                    $data = array_merge($data, $result);
                }
            }
        }

        return new JsonResponse($data);
    }

    public function getAttributeMappingKeyAction($identifier)
    {
        try {
            $result = $this->connectorService->requestApiAction1($identifier, 'getAttributeMapping', []);
            $result = $this->serializeCustomerGroups($result);
        } catch (\Exception $e) {
            $result['error'] = $e->getMessage();
        }
        
        return new JsonResponse($result);
    }

    /**
     * get credentials
     *
     * @AclAncestor("webkul_akeneo_woocommerce_connector_configuration")
     *
     * @return JsonResponse
     */
    public function getAllAction()
    {
        $em = $this->getDoctrine()->getManager();
        $credentials = $em->getRepository(CredentialConfig::class)->findByActive(1);
        $data = [];

        foreach ($credentials as $credential) {
            $data[$credential->getId()] = $credential->getShopUrl();
        }
        return new JsonResponse($data);
    }

    public function changeDefaultAction(Request $request)
    {
        $id = $request->get('id');
        $em = $this->getDoctrine()->getManager();
        $credentialRepoUpdateAll = $em->getRepository(CredentialConfig::class);
        $credentialRepoUpdateSingle = $em->getRepository(CredentialConfig::class);

        $credential = $credentialRepoUpdateSingle->findOneById($id);
        $defaultSetValue = $credential->getDefaultSet();
        
        $credentialRepoUpdateAll->createQueryBuilder('c')
                        ->update()
                        ->set('c.defaultSet', ':setValue')
                        ->where('c.defaultSet =:value')
                        ->setParameter('setValue', false)
                        ->setParameter('value', true)
                        ->getQuery()->execute();

        $credential = $credentialRepoUpdateSingle->findOneById($id);

        if ($credential) {
            $defaultSet = $defaultSetValue ? false : true;
            
            if($credential->getActive() == 0 && $defaultSet == true) {
                return new JsonResponse(['successful' => false]);
            }

            $credential->setDefaultSet($defaultSet);
            $em->persist($credential);
            $em->flush();
            $this->checkAndSaveQuickJob();
        }

        return new JsonResponse(['successful' => true]);
    }

    protected function checkAndSaveQuickJob()
    {
        $jobInstance = $this->get('pim_enrich.repository.job_instance')->findOneBy(['code' => self::QUICK_EXPORT_CODE]);
    
        if (!$jobInstance) {
            $em = $this->getDoctrine()->getManager();
            $jobInstance = new \JobInstance();
            $jobInstance->setCode(self::QUICK_EXPORT_CODE);
            $jobInstance->setJobName('woocommerce_quick_export');
            $jobInstance->setLabel('WooCommerce product quick export');
            $jobInstance->setConnector('WooCommerce Export Connector');
            $jobInstance->setType('quick_export');
            $em->persist($jobInstance);
            $em->flush();
        }
    }
}
