<?php

/**
 * @file
 * Primary module hooks for patnis module.
 *
 * @DCG
 * This file is no longer required in Drupal 8.
 * @see https://www.drupal.org/node/2217931
 */
use Drupal\Core\Form\FormStateInterface;

function patnis_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if ($form['#webform_id'] == 'pieteiksanas_skolai') {
    // Logs a notice
    \Drupal::logger('patnis')->notice('Form sub detected 2');
    // add an AJAX callback to the form submission
    $form['actions']['submit']['#ajax'] = array(
      'callback' => 'processFormSubmission',
      'event' => 'click',
      'progress' => [
        'type' => 'none',
      ],
    );
  }

}

function processFormSubmission(array &$form, FormStateInterface $form_state){
  //Get the values from webform to store it in google sheet
  $first_name = $form_state->getValue('vards_uzvards');
  $last_name = $form_state->getValue('talrunis');
  $email = $form_state->getValue('e_pasts');
  // Load the account
  $google_api_client = \Drupal::entityTypeManager()->getStorage('google_api_service_client')->load('111315275493886458232');
  // Get the service.
  $googleService = \Drupal::service('google_api_service_client.client');
  // Apply the account to the service
  $googleService->setGoogleApiClient($google_api_client);
  // Fetch Sheets object.
  $object = $googleService->getServiceObjects();
  // $object['sheets'] is a object of Google_Service_Sheets
  $sheets = $object['sheets'];
  $single_sheet = $sheets->spreadsheets_values;
  $spreadsheetID = "1LoOdPoXM5iuOK6ouAPFVH4HJUoYXX1xwsrnO5PHgQCI";
  $range = 'Sheet1';//Correct here for your sheet name
  $values = [
    [$first_name,$last_name,$email],
  ];
  $body = new Google_Service_Sheets_ValueRange([
    'values' => $values
  ]);
  $params = [
    'valueInputOption' => 'RAW',
  ];
  $insert = [
    "insertDataOption"=> "INSERT_ROWS",
  ];
  $single_sheet_update = $sheets->spreadsheets_values->append($spreadsheetID, $range, $body, $params, $insert);
}
