<?php

use Drupal\node\Entity\Node;
use Drupal\node\Entity;
use Drupal\taxonomy\Entity\Term;

function zone_data_run() {
    $boutiquesUpdated = array();
    $storeList = normalizeChars(file_get_contents('public://geojson/halte.dat'));
    $storesArr = explode(PHP_EOL, $storeList);
    $file = normalizeChars(file_get_contents('public://geojson/quartier6.json'));
    $matchedStores = 0;
    $matchedNodes = 0;
    $storesNotFound = array();
    $nodesNotFound = array();
    $createdZones = array();
    if (!empty($geojson = json_decode($file))) {
        $numFeatures = count($geojson->features);

//        usort($geojson->features, "featureCompare");
        $x = 0;
        foreach ($storesArr as $store) {
            $match = false;
            foreach ($geojson->features as $feature) {
                if (isset($feature->properties->name)) {
                    $name = $feature->properties->name;
                    if (trim(strtolower($store)) === trim(strtolower($feature->properties->name))) {
                        $match = true;
                        $matchedStores++;

                        $nQuery = db_query('SELECT nid FROM node_field_data WHERE title LIKE :title AND type = :type AND langcode = :langcode', array(
                            ':title' => $store,
                            ':type' => 'boutique',
                            ':langcode' => 'en',
                        ))->fetchField();

                        if ($nQuery > 0) {
                            $featureData = json_encode($feature->geometry);
                            $matchedNodes++;

                            $term = \Drupal\taxonomy\Entity\Term::create([
                                'name' => 'AD' . $x,
                                'vid' => 'zone',
                            ])->save();
                            if ($term) {
                                $tidQ = array_values(\Drupal::entityQuery('taxonomy_term')
                                    ->condition('vid', 'zone')
                                    ->condition('name', 'AD' . $x)
                                    ->execute());
                            }
                            if ($tidQ != null && is_array($tidQ) && count($tidQ) > 0) {
                                $zoneNodeSaveAttempt = null;
                                if (isset($feature->properties->level)) {
                                    $zoneNode = Node::create([
                                        'type' => 'zone',
                                        'body' => $name,
                                        'title' => 'AD' . $x,
                                        'field_sector_code' => 55,
                                        'field_feature_data' => $featureData,
                                        'field_zone_code' => $tidQ[0],
                                        'field_levels' => $feature->properties->level,
                                    ]);
                                }
                                $zoneNodeSaveAttempt = $zoneNode->save();

                                if ($zoneNodeSaveAttempt === 1 || $zoneNodeSaveAttempt === 2) {
                                    $createdZones[] = $name;
                                    $boutiqueNode = Drupal\node\Entity\Node::load($nQuery);
                                    $boutiqueNode->field_zone_code = $tidQ[0];
                                    $boutiqueNodeSaveAttempt = $boutiqueNode->save();

                                    if ($boutiqueNodeSaveAttempt === 1 || $boutiqueNodeSaveAttempt === 2) {
                                        $boutiquesUpdated[] = $name;
                                    }
                                }


                            } else {
                                $errMsg = 'zone term was not created for: ' . $store;
                                \Drupal::logger('zone_data')->error($errMsg);
                            }


                        } else {
                            $nodesNotFound[] = $store;
                        }
                    }
                }
            }
            if ($match == false) {
              $storesNotFound[] = $store;
              $logStr = '';
              foreach ($storesNotFound as $storeName) {
                $logStr .= $storeName . ', ';
              }
              $logStr = substr($logStr, -2);
              $errMsgAll = 'The following stores did not have zones created for them: ' . $logStr;
                \Drupal::logger('zone_data')->error($errMsgAll);


            }
            $x++;
        }


    }

    $name = 'test';

    return $createdZones;


//    return $term;

}


function normalizeChars($s) {
    $replace = array(
        'Ă'=>'A', 'Ą'=>'A', 'À'=>'A', 'Ã'=>'A', 'Á'=>'A', 'Æ'=>'A', 'Â'=>'A', 'Å'=>'A', 'Ä'=>'Ae',
        'È'=>'E', 'Ę'=>'E', 'É'=>'E', 'Ë'=>'E', 'Ê'=>'E',
        'İ'=>'I', 'Ï'=>'I', 'Î'=>'I', 'Í'=>'I', 'Ì'=>'I',
        'Ù'=>'U', 'Û'=>'U', 'Ú'=>'U', 'Ü'=>'Ue',
        'â'=>'a', 'ǎ'=>'a', 'ą'=>'a', 'á'=>'a', 'ă'=>'a', 'ã'=>'a', 'Ǎ'=>'a', 'а'=>'a', 'А'=>'a', 'å'=>'a', 'à'=>'a', 'א'=>'a', 'Ǻ'=>'a', 'Ā'=>'a', 'ǻ'=>'a', 'ā'=>'a', 'ä'=>'ae', 'æ'=>'ae', 'Ǽ'=>'ae', 'ǽ'=>'ae',
        'ĉ'=>'c', 'Ĉ'=>'c', 'Ċ'=>'c', 'ć'=>'c', 'ç'=>'c', 'ц'=>'c', 'צ'=>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