<?php

namespace Drupal\abinbev_gmap;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Batch\BatchBuilder;
use Drupal\Core\Config\ConfigFactory;
use \Drupal\Core\Database\Connection;
use Drupal\Core\Database\Database;
use Google\Cloud\BigQuery\BigQueryClient;
use Drupal\Core\Logger\LoggerChannelFactory;
use GuzzleHttp\Client;
use http\Client\Request;

/**
 * Class UserData Service
 *
 * @package Drupal\abinbev_gmap\Services
 */
class UserDataService {

  protected $config;

  protected $logger;

  protected $client;

  protected $database;

  /**
   * CustomService constructor.
   */
  public function __construct(ConfigFactory $config, LoggerChannelFactory $logger, Client $client, Connection $database) {
    $this->config = $config->get('abinbev_gmap.settings');
    $this->logger = $logger;
    $this->client = $client;
    $this->database = $database;
  }

  /**
   * @return mixed
   */
  function getUserData($phone_number) {
    $connection = $this->database;
    $query = $connection->select('bees_user_validated', 'uv')
      ->fields('uv', [])
      ->execute();
    return $query->fetchAllAssoc('id');
  }

  /**
   * @param $place_id
   *
   * @return \Drupal\Core\Database\StatementInterface|int|string|null
   * @throws \Exception
   */
  function setUserData($values) {
    $data = [
      'user_phone' => $values['phone_number'],
      'user_name' => $values['first_name'],
      'access_token' => bin2hex(random_bytes(4)),
      'refresh_token' => '',
      'validation_code' => '',
      'language' => $values['language'],
      'visited' => 0,
      'created' => time(),
      'updated' => time(),
      //'optanon_consent' => $_COOKIE['OptanonConsent'] ?? '',
      //'optanon_alert_box_closed' => $_COOKIE['OptanonAlertBoxClosed'] ?? '',
    ];
    $connection = $this->database;

    $query = $connection->insert('bees_user_validated')
      ->fields($data)->execute();

    return $query;
  }

  /**
   * @return mixed
   */
  function getUserDataByPhone($phone) {
    $connection = $this->database;
    $query = $connection->select('bees_user_validated', 'uv')
      ->fields('uv', [])
      ->condition('user_phone', $phone, '=')
      ->execute();
    $result = $query->fetchAssoc();
    return $result;
  }


  /**
   * @return mixed
   */
  function getUserDataByToken($token) {
    $connection = $this->database;
    $query = $connection->select('bees_user_validated', 'uv')
      ->fields('uv', [])
      ->condition('access_token', $token, '=')
      ->execute();
    $result = $query->fetchAssoc();
    return $result;
  }

  /**
   * @param $token
   */
  function setUserIsVisited($token, $bees_user_id, $refresh_token) {
    $connection = $this->database;
    $connection->update('bees_user_validated')
      ->fields([
        'visited' => 1,
        'updated' => time(),
        'bees_user_id' => $bees_user_id,
        'refresh_token' => $refresh_token,
      ])
      ->condition('access_token', $token, '=')
      ->execute();
  }

  /**
   * @param $token
   * @param $refresh_token
   */
  function setRefreshToken($token, $refresh_token, $code) {
    $connection = $this->database;
    $connection->update('bees_user_validated')
      ->fields([
        'refresh_token' => $refresh_token,
        'updated' => time(),
        'validation_code' => $code,
      ])
      ->condition('access_token', $token, '=')
      ->execute();
  }

  /**
   * Check what is current mechanic.
   */
  public function getCurrentMechanic() {

    $alias = \Drupal::request()->getPathInfo();

    $out = [
      'flow' => 'b',
      'page' => 'form',
    ];

    if (empty($alias)) {
      return $out;
    }

    $args = explode('/', $alias);

    if (count($args) == 3) {
      if (isset($args[1])) {
        $flow = $args[1];
        $page = $args[2];
      }
    }
    if (count($args) == 4) {
      if (isset($args[2])) {
        $flow =  $args[2];
        $page = $args[3];
      }
    }

    $allowed_flows = ['a', 'b', 'c', 'r', 'd'];
    if (isset($flow) && in_array($flow, $allowed_flows)) {
      $out = [
        'flow' => $flow,
        'page' => $page,
      ];
    }
    return $out;
  }

  public function setCookie($name, $value, $sameSite = NULL) {
    $host = \Drupal::request()->getHost();
    $sameSiteValue = FALSE;
    if ($sameSite) {
      $sameSiteValue = $sameSite;
    }
    if (strpos($host, 'mybe')) {
      setcookie($name, $value, time() + 60 * 60 * 24 * 30, '/', 'mybe', TRUE, $sameSiteValue);
    }
    else {
      setcookie($name, $value, time() + 60 * 60 * 24 * 30, '/', '', TRUE, $sameSiteValue);
    }
  }

}