<?php

namespace Drupal\abinbev_gmap\Controller;

use Drupal\abinbev_gmap\BQRequestService;
use Drupal\abinbev_gmap\PlaceInfoService;
use Drupal\abinbev_gmap\UserDataService;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AppendCommand;
use Drupal\Core\Ajax\OpenDialogCommand;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Class Map.
 */
class MapController extends ControllerBase {

  /**
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  protected $bqService;

  protected $placeInfoService;

  protected $userDataService;

  /**
   * Cache.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  private $cache;

  /**
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config factory service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, BQRequestService $bqService, PlaceInfoService $placeInfoService, UserDataService $userDataService, CacheBackendInterface $cacheBackend) {
    $this->config = $config_factory->get('abinbev_gmap.settings');
    $this->bqService = $bqService;
    $this->placeInfoService = $placeInfoService;
    $this->userDataService = $userDataService;
    $this->cache = $cacheBackend;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('bq_request_service'),
      $container->get('place_info_service'),
      $container->get('user_data_service'),
      $container->get('cache.default')
    );
  }

  public function requestPocToCampaign($poc_id) {
    $response = new AjaxResponse();
    $user_token = $_COOKIE['bees_user_validated'] ?? '';

    if (!$user_token) {
      $response->setContent(json_encode($user_token));
      return $response;
    }

    $access_token = $_COOKIE['access_token'] ?? '';
    $info = $this->placeInfoService->getUserInfoByAccessToken($access_token);
    $data = [
      'user_token' => $user_token,
      'poc_id' => $poc_id,
      'user_name' => $info['user_name'],
      'phone_number' => $info['user_phone'],
    ];

    $userHasRequestedPoc = $this->placeInfoService->userHasRequestedPoc();
    if (empty($userHasRequestedPoc)) {
      $this->placeInfoService->saveUserPocRequest($data);
    }

    $response->setContent(json_encode($userHasRequestedPoc));
    return $response;
  }

  /**
   * @return \Drupal\Core\Ajax\AjaxResponse
   */
  public function checkUserHasRequestedPoc() {
    $response = new AjaxResponse();
    $userHasRequestedPoc = $this->placeInfoService->userHasRequestedPoc();
    $out = 'false';
    if (!empty($userHasRequestedPoc)) {
      $out = 'true';
    }
    $response->setContent($out);
    return $response;
  }

  /**
   * Check User Access by personal token.
   *
   * @param $token
   *
   */
  public function checkUserAccess($token, $flow) {
    $user_data = $this->userDataService->getUserDataByToken($token);
    $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $prefix = '';

    if ($lang != 'en') {
      $prefix = '/' . $lang;
    }
    if ($user_data) {
      $this->userDataService->setCookie('access_token', $token);

      if (empty($user_data['refresh_token'])) {
        $auth = $this->smsValidatorService->auth();
        $id_token = $auth['idToken'];
        $refresh_token = $auth['refreshToken'];
        $decoded = json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', $id_token)[1]))));
        $user_id = $decoded->user_id;

        $this->userDataService->setUserIsVisited($token, $user_id, $refresh_token);
        $this->smsValidatorService->sendUserVerification($token);

        $this->userDataService->setCookie('bees_user_validated', $refresh_token);
        $response = new RedirectResponse($prefix . '/' . $flow . '/map?token=' . $token);

        return $response;
      }
      else {
        $this->userDataService->setCookie('bees_user_validated', $user_data['refresh_token']);
        return new RedirectResponse($prefix . '/' . $flow . '/map');
      }
    }
    return new RedirectResponse($prefix . '/' . $flow . '/form');
  }

  /**
   * Form Confirmation Page
   */
  public function fwcFormConfirmation() {
    $phone = '';
    $sid = \Drupal::request()->query->get('sid');
    if (!empty($sid)) {
      $data = \Drupal::entityTypeManager()
        ->getStorage('webform_submission')
        ->loadByProperties(['uuid' => $sid]);
      if (!empty($data)) {
        $data = reset($data);
        $values = $data->getData();
        $phone = trim($values['phone_number']);
        $phone = '+' . preg_replace('/\++|\-+|\s+/', '', $phone);
      }
    }
    return [
      '#theme' => 'bees_form_confirmation',
      '#phone' => $phone,

    ];
  }

  /**
   * Form Confirmation Page
   */
  public function fwcDFormConfirmation() {
    $phone = '';
    $sid = \Drupal::request()->query->get('sid');
    if (!empty($sid)) {
      $data = \Drupal::entityTypeManager()
        ->getStorage('webform_submission')
        ->loadByProperties(['uuid' => $sid]);
      if (!empty($data)) {
        $data = reset($data);
        $values = $data->getData();
        $phone = trim($values['phone_number']);
        $phone = '+' . preg_replace('/\++|\-+|\s+/', '', $phone);
      }
    }
    return [
      '#theme' => 'bees_d_form_confirmation',
      '#phone' => $phone,

    ];
  }

  public function showMap($id) {
    setcookie('show_map', 1, time() + 3600, '/');
    $paragraph = \Drupal::entityTypeManager()
      ->getStorage('paragraph')
      ->load($id);
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('paragraph');
    $pre_render = $view_builder->view($paragraph, 'teaser');

    $render_output = \Drupal::service('renderer')->render($pre_render);

    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#paragraph-map', $render_output));
    return $response;

  }

}
