<?php

namespace Drupal\abinbev_gmap;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\ConfigFactory;
use Google\Cloud\BigQuery\BigQueryClient;
use Drupal\Core\Logger\LoggerChannelFactory;
use Google\Exception;

/**
 * Class SMSValidatorService
 *
 * @package Drupal\abinbev_gmap\Services
 */
class BQRequestService {

  protected $config;

  protected $logger;

  protected $placeInfoService;

  /**
   * CustomService constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactory $config
   */
  public function __construct(ConfigFactory $config, LoggerChannelFactory $logger, PlaceInfoService $placeInfoService) {
    $this->config = $config->get('abinbev_gmap.settings');
    $this->logger = $logger;
    $this->placeInfoService = $placeInfoService;
  }

  /**
   * Auth method.
   *
   * @return void
   */
  private function auth() {
    $cert_file = $this->config->get('google_cert_file');
    $cert_file = base64_decode($cert_file);
    $cert_file = '/var/www/html/' . str_replace('../', '', $cert_file);
    $cert_file = trim($cert_file);
    if (file_exists($cert_file)) {
      putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $cert_file);
    }
    else {
      $cert_file = str_replace('/var/www/html/', '', $cert_file);
      $root = $_SERVER["DOCUMENT_ROOT"];
      $cert_file = $root . '/' . trim($cert_file);
      putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $cert_file);
    }
  }

  /**
   * @return void
   */
  public function BQCDPauth() {
    $cert_file = $this->config->get('google_cdp_cert_file');
    $cert_file = base64_decode($cert_file);
    $cert_file = '/var/www/html/' . str_replace('../', '', $cert_file);
    $cert_file = trim($cert_file);
    if (file_exists($cert_file)) {
      putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $cert_file);
    }
    else {
      $cert_file = str_replace('/var/www/html/', '', $cert_file);
      $root = $_SERVER["DOCUMENT_ROOT"];
      $cert_file = $root . '/' . trim($cert_file);
      putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $cert_file);
    }

  }

  /**
   * Get Data method.
   *
   * @return array
   * @throws \Google\Cloud\Core\Exception\GoogleException
   */
  public function getData($promo_id) {
    $this->auth();
    $projectId = $this->config->get('google_project_id');
    $dataset = $this->config->get('google_dataset_id');

    // If no value, make query to BQ.
    $bigQuery = new BigQueryClient([
      'projectId' => $projectId,
    ]);

    if (!is_array($promo_id)) {
      $promo_id = explode(',', $promo_id);
    }

    $condition = [];
    foreach ($promo_id as $id) {
      $condition[] = "promo_id = " . $id;
    }
    $condition = implode(' OR ', $condition);

    $query = <<<ENDSQL
        SELECT
          DISTINCT(google_place_id), customer_id 
        FROM {$dataset}
        WHERE {$condition}
      ENDSQL;

    $queryJobConfig = $bigQuery->query($query);
    $queryResults = $bigQuery->runQuery($queryJobConfig);

    if ($queryResults->isComplete()) {
      $rows = $queryResults->rows();

      $dataRows = [];
      foreach ($rows as $i => $row) {
        $place_id = $row['google_place_id'];
        $poc_id = $row['customer_id'];
        if (!empty($place_id)) {
          $dataRows[] = $place_id;
          $this->placeInfoService->savePlace($place_id, $poc_id);
        }
      }
    }
    else {
      throw new \Exception('The query failed to complete');
    }

    return $dataRows;
  }

  /**
   * Get List of non active locations.
   *
   * @return mixed
   */
  public function getLocations() {
    $kv_store = \Drupal::service('keyvalue.expirable')
      ->get('abinbev_gmap');
    return $kv_store->get('bq_list_of_na_pocs', NULL);
  }


  /**
   * Set CDP Data method.
   *
   * @return \Google\Cloud\BigQuery\QueryResults|string
   */
  public function setCDPData($data) {
    $this->BQCDPauth();
    $projectId = $this->config->get('google_cdp_project_id');
    $datasetName = $this->config->get('google_cdp_dataset_id');

    // If no value, make query to BQ.
    $bigQuery = new BigQueryClient([
      'projectId' => $projectId,
    ]);
    $dataset = $bigQuery->dataset($datasetName);

    $table = $dataset->table('web_form');
    $row = [
      '__source_table' => $data['__source_table'],
      'td_client_id' => $data['td_client_id'],
      'abi_name' => $data['abi_name'],
      'abi_phone' => $data['abi_phonenumber'],
      'abi_preferred_language' => $data['abi_preferred_language'],
      'abi_campaign' => $data['abi_campaign_name'],
      'abi_brand' => $data['abi_brand'],
      'abi_country' => $data['abi_country'],
      'purpose_name' => $data['purpose_name'],
      'abi_form' => $data['abi_form'],
      'td_url' => $data['td_url'],
      'td_host' => $data['td_host'],
      'abi_interests' => $data['abi_interests'],
      'time' => time(),
      'ABI_PROMO_ID' => $data['ABI_PROMO_ID']
    ];
    $insertResponse = $table->insertRows([
      ['data' => $row],
    ]);
    if ($insertResponse->isSuccessful()) {
      return TRUE;
    } else {
      foreach ($insertResponse->failedRows() as $row) {
        foreach ($row['errors'] as $error) {
          $dataRows =  printf('%s: %s' . PHP_EOL, $error['reason'], $error['message']);
          \Drupal::logger('BQ_INSERT Error')->error(print_r($dataRows, 1));
        }
      }
    }
  }

}