<?php
namespace App\Controllers\Seller;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

use \App\Controllers\Container;
use \App\Models\Entity\Promotions;

class SellerPromotions extends Container
{
  public function get(Request $request, Response $response, $args){

    $dock = $request->getAttribute('route')->getArgument('dock');

    $entityManager = $this->container->get('em');
    $promotionRepository = $entityManager->getRepository('App\Models\Entity\Promotions');
    $promocao = $promotionRepository->findAll();

    if(empty($promocao)){
      throw new \Exception("Nao existe lista de promocao", 404);
    }

    foreach ($promocao as $p) {
      if ($p->getDockPromotion() == $dock) {
        $promo[] = $p->getId();
      }
    }

    if(empty(promo)){
      throw new \Exception("Nao existe lista de promocao para o seller", 404);
    }

    foreach ($promo as $key => $i) {
      $promoDb[] = $promotionRepository->find($i);
    }

    return $response->withJson($promoDb, 200)->withHeader('Content-type', 'application/json');
  }

  public function create(Request $request, Response $response, $args){

    $entityManager = $this->container->get('em');
    $promotionRepository = $entityManager->getRepository('App\Models\Entity\Promotions')->findAll();

    if (count($promotionRepository) > 3) {
      throw new \Exception("Nao eh possivel criar nova campanha", 404);
    }

    // env.php define variaveis
    $token = getenv('token');
    $keyApp = getenv('appkey');

    $dock = $request->getAttribute('route')->getArgument('dock');

    $name = $request->getParam('name');
    $beginDate = $request->getParam('beginday');
    $endDate = $request->getParam('endday');
    $description = $request->getParam('text');
    $couponString = $request->getParam('coupon');
    $type = $request->getParam('type');

    //limpa cupom
    $acento = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $couponString));
    $cp = preg_replace('/[^0-9A-Za-z]*/', "", $acento);
    $coupon = strtolower($cp);

    $value = 100;

    //valor de porcentagem ou em reais
    if (!empty($request->getParam('percent'))) {
      $percent = $request->getParam('percent');
      $value = str_replace(",", ".", $percent);
    }

    if (!empty($request->getParam('money'))) {
      $percent = $request->getParam('money');
      $value = str_replace(",", ".", $percent);
    }

    //verificar se existe cupom cadastrado no banco

    $bodyJsonCoupon = '{
      "utmSource": "'.$coupon.'",
      "utmCampaign": "'.$coupon.'",
      "couponCode": "'.$coupon.'",
      "isArchived": false,
      "maxItemsPerClient": 0,
      "expirationIntervalPerUse": null
    }';

    //var_dump($bodyJsonCoupon);

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://arsdesign.myvtex.com/api/rnb/pvt/coupon/",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => false,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => $bodyJsonCoupon ,
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
        "X-VTEX-API-AppToken: {$token}",
        "X-VTEX-API-AppKey: {$keyApp}"
      ),
    ));

    $resCurl = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      throw new \Exception("Nao foi possivel cadastrar cupom", 404);
    } else {

      $respJsonCupom = json_decode($resCurl);
      //var_dump($respJsonCupom);

      if (!empty($respJsonCupom->couponCode)) {

        switch ($dock) {
          case 'outletCvto':
            $parceiro = 'Seja Convicto';
            break;

          default:
            throw new \Exception("Doca invalida", 404);
            break;
        }

        switch ($type) {
          case 'nominalFrete':
            $typePromo = 'nominalShippingDiscountValue';
            $typeDb = 'Valor de Frete';
            break;

          case 'percentualCompra':
            $typePromo = 'percentualDiscountValue';
            $typeDb = 'Percentual Valor Total da Compra';
            break;

          case 'nominalCompra':
            $typePromo = 'nominalDiscountValue';
            $typeDb = 'Valor Total da Compra';
            break;

          default:
            //freteGratis e percentual de frete
            $typePromo = 'percentualShippingDiscountValue';
            $typeDb = 'Percentual de Frete';
            break;
        }

        $bodyJsonPromotion = '{
          "name":"'.$name.'",
          "description":"'.$description.'",
          "beginDateUtc":"'.$beginDate.'",
          "endDateUtc":"'.$endDate.'",
          "daysAgoOfPurchases":0,
          "isActive":true,
          "'.$typePromo.'": '.$value.',
          "orderStatusRewardValue":"invoiced",
          "applyToAllShippings":false,
          "origin":"Marketplace",
          "idSellerIsInclusive":true,
          "idsSalesChannel":[],
          "areSalesChannelIdsExclusive":false,
          "marketingTags":[],
          "marketingTagsAreNotInclusive":false,
          "paymentsMethods":[],
          "stores":[],
          "campaigns":[],
          "storesAreInclusive":true,
           "categories":[
              {
                 "id":"228",
                 "name":"Outlet (228)"
              }
           ],
           "categoriesAreInclusive":false,
           "brands":[],
           "brandsAreInclusive":true,
           "products":[],
           "productsAreInclusive":true,
           "skusAreInclusive":true,
           "utmSource":"'.$coupon.'",
           "utmCampaign":"'.$coupon.'",
           "collections1BuyTogether":[],
           "collections2BuyTogether":[],
           "minimumQuantityBuyTogether":0,
           "quantityToAffectBuyTogether":0,
           "enableBuyTogetherPerSku":false,
           "listSku1BuyTogether":[],
           "listSku2BuyTogether":[],
           "coupon":[],
           "totalValueFloor":0.0,
           "totalValueCeling":0.0,
           "totalValueIncludeAllItems":false,
           "totalValueMode":"IncludeMatchedItems",
           "collections":[],
           "collectionsIsInclusive":true,
           "restrictionsBins":[],
           "cardIssuers":[],
           "totalValuePurchase":0.0,
           "slasIds":[
              "'.$parceiro.'"
           ],
           "isSlaSelected":true,
           "isFirstBuy":false,
           "firstBuyIsProfileOptimistic":false,
           "compareListPriceAndPrice":false,
           "isDifferentListPriceAndPrice":false,
           "zipCodeRanges":[],
           "itemMaxPrice":0.0,
           "itemMinPrice":0.0,
           "installment":0,
           "isMinMaxInstallments":false,
           "minInstallment":0,
           "maxInstallment":0,
           "merchants":[],
           "clusterExpressions":[],
           "clusterOperator":"all",
           "paymentsRules":[],
           "giftListTypes":[],
           "productsSpecifications":[],
           "affiliates":[],
           "maxUsage":0,
           "maxUsagePerClient":1,
           "multipleUsePerClient":false,
           "accumulateWithManualPrice":false,
           "type":"regular"
        }';

        //var_dump($bodyJsonPromotion);
        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://arsdesign.myvtex.com/api/rnb/pvt/calculatorconfiguration",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => false,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "POST",
          CURLOPT_POSTFIELDS =>$bodyJsonPromotion,
          CURLOPT_HTTPHEADER => array(
            "Accept: application/json",
            "Content-Type: application/json",
            "X-VTEX-API-AppToken: {$token}",
            "X-VTEX-API-AppKey: {$keyApp}"
          ),
        ));

        $respCurl = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
          throw new \Exception("Nao foi possivel criar promocao", 404);
        }else{
          $respostaJson =  json_decode($respCurl);

          //var_dump($respostaJson);
         

          if (!empty($respostaJson->idCalculatorConfiguration)) {

            if ($respostaJson->isActive = true) {
              $status = "Ativo";
            }else {
              $status = "Inativo";
            }

            $promocao = (new Promotions())->setIdVtex($respostaJson->idCalculatorConfiguration)
                                        ->setNamePromotion($respostaJson->name)
                                        ->setBeginDate(date('Y-m-d', strtotime($beginDate)))
                                        ->setEndDate(date('Y-m-d', strtotime($endDate . "-1day")))
                                        ->setIdCoupon($respJsonCupom->couponCode)
                                        ->setCoupon($respJsonCupom->utmSource)
                                        ->setStatus($status)
                                        ->setTypePromotion($typeDb)
                                        ->setValuePromotion($value)
                                        ->setDockPromotion($dock);

            $entityManager->persist($promocao);
            $entityManager->flush();

            return $response->withJson($promocao, 200)->withHeader('Content-type', 'application/json');
          }else {
            throw new \Exception("Sem retorno", 404);
          }

        }

      }

      
    }

  }

  public function delete(Request $request, Response $response, $args){
    // env.php define variaveis
    $token = getenv('token');
    $keyApp = getenv('appkey');

    $id = $request->getAttribute('route')->getArgument('id');

    if (!is_numeric($id)) {
      throw new \Exception("Numero invalido", 404);
    }

    $entityManager = $this->container->get('em');
    $promotionRepository = $entityManager->getRepository('App\Models\Entity\Promotions');
    $promotion = $promotionRepository->find($id);

    if (!$promotion) {
      throw new \Exception("Nao existe promocao", 404);
    }

    //data exclusão da promoção
    $hoje = date('Y-m-d');
    $hora = 'T00:00:00Z';

    //verifica o tipo da promoção
    $type = $promotion->getTypePromotion();

    switch ($type) {
      case 'Valor de Frete':
        $typePromo = 'nominalShippingDiscountValue';
        break;

      case 'Percentual Valor Total da Compra':
        $typePromo = 'percentualDiscountValue';
        break;

      case 'Valor Total da Compra':
        $typePromo = 'nominalDiscountValue';
        break;

      default:
        //freteGratis e percentual de frete
        $typePromo = 'percentualShippingDiscountValue';
        break;
    }


    $bodyJsonAlt = '{
      "idCalculatorConfiguration":"'.$promotion->getIdVtex().'",
      "name":"'.$promotion->getNamePromotion().'",
      "beginDateUtc":"'.$promotion->getBeginDate().$hora.'",
      "endDateUtc":"'.$promotion->getEndDate().$hora.'",
      "lastModified":"'.$hoje.$hora.'",
      "daysAgoOfPurchases":0,
      "isActive":false,
      "isArchived": true,
      "'.$typePromo.'": '.$promotion->getValuePromotion().',
      "orderStatusRewardValue":"invoiced",
      "applyToAllShippings":false,
      "origin":"Marketplace",
      "idSellerIsInclusive":true,
      "idsSalesChannel":[],
      "areSalesChannelIdsExclusive":false,
      "marketingTags":[],
      "marketingTagsAreNotInclusive":false,
      "paymentsMethods":[],
      "stores":[],
      "campaigns":[],
      "storesAreInclusive":true,
       "categories":[
          {
             "id":"228",
             "name":"Outlet (228)"
          }
       ],
       "categoriesAreInclusive":false,
       "brands":[],
       "brandsAreInclusive":true,
       "products":[],
       "productsAreInclusive":true,
       "skusAreInclusive":true,
       "utmSource":"'.$promotion->getCoupon().'",
       "utmCampaign":"'.$promotion->getCoupon().'",
       "collections1BuyTogether":[],
       "collections2BuyTogether":[],
       "minimumQuantityBuyTogether":0,
       "quantityToAffectBuyTogether":0,
       "enableBuyTogetherPerSku":false,
       "listSku1BuyTogether":[],
       "listSku2BuyTogether":[],
       "coupon":[],
       "totalValueFloor":0.0,
       "totalValueCeling":0.0,
       "totalValueIncludeAllItems":false,
       "totalValueMode":"IncludeMatchedItems",
       "collections":[],
       "collectionsIsInclusive":true,
       "restrictionsBins":[],
       "cardIssuers":[],
       "totalValuePurchase":0.0,
       "slasIds":[],
       "isSlaSelected":true,
       "isFirstBuy":false,
       "firstBuyIsProfileOptimistic":false,
       "compareListPriceAndPrice":false,
       "isDifferentListPriceAndPrice":false,
       "zipCodeRanges":[],
       "itemMaxPrice":0.0,
       "itemMinPrice":0.0,
       "installment":0,
       "isMinMaxInstallments":false,
       "minInstallment":0,
       "maxInstallment":0,
       "merchants":[],
       "clusterExpressions":[],
       "clusterOperator":"all",
       "paymentsRules":[],
       "giftListTypes":[],
       "productsSpecifications":[],
       "affiliates":[],
       "maxUsage":0,
       "maxUsagePerClient":1,
       "multipleUsePerClient":false,
       "accumulateWithManualPrice":false,
       "type":"regular"
    }';

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://arsdesign.myvtex.com/api/rnb/pvt/calculatorconfiguration",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => false,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS =>$bodyJsonAlt,
      CURLOPT_HTTPHEADER => array(
        "Accept: application/json",
        "Content-Type: application/json",
        "X-VTEX-API-AppToken: {$token}",
        "X-VTEX-API-AppKey: {$keyApp}"
      ),
    ));

    $respCurl = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      throw new \Exception("Erro ao cancelar promocao", 404);
    }else{

      $curlResp = json_decode($respCurl);

      if($curlResp->idCalculatorConfiguration){
        
        $entityManager->remove($promotion);
        $entityManager->flush();

        return $response->withStatus(204);
        
      }else{
        
        return $response->withStatus(404);

      }

    }




  }
}
