<?php

/**
 * @file
 * Contains \Drupal\mapui\Form\MapUiForm.
 */

namespace Drupal\mapui\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\mapui\Plugin\BoutiqueSelection;

/**
 * Directory Search form.
 */

class MapUiForm extends FormBase {

  /**
   * {@inheritdoc}
   */

  public function getFormId() {
      return 'map_ui_form';
  }

    /**
     * @param array $form
     * @param FormStateInterface $form_state
     * @return array
     */
    public function buildForm(array $form, FormStateInterface $form_state) {

        $data = array();

        $langCode= \Drupal::languageManager()->getCurrentLanguage()->getId();

        //Get tid for "Stores", the parent term of the store hierarchy
        //Since these terms do not have a parent, we must name them explicitly at the outset and then run the differentiate by langcode
        $taxonomyTermArray = [
            'en' => array(
                ':name1' => 'Stores',
                ':name2' => 'Entertainment',
                ':name3' => 'Restaurant',
                ':name4' => 'Other',
                ':name5' => 'Features',
                ':name6' => 'Brands'),
            'fr' => array(
                ':name1' => 'Boutiques',
                ':name2' => 'Divertissement',
                ':name3' => 'Restaurant',
                ':name4' => 'Autre',
                ':name5' => 'Particularités',
                ':name6' => 'Marques')
        ];
        $tidMaster = db_query("SELECT fd.tid, fd.name FROM taxonomy_term_hierarchy th JOIN taxonomy_term_field_data fd
                       ON fd.tid = th.tid WHERE fd.name = :name1 OR fd.name = :name2 OR fd.name = :name3 OR fd.name = :name4 OR fd.name = :name5 OR fd.name = :name6 ORDER BY fd.weight",

        $taxonomyTermArray[$langCode])->fetchAll();


        if (count($tidMaster) > 0) {
            foreach ($tidMaster as $parent) {
                //Get the tids representing the main types of stores (Ex: Fashion, Restaurants, Entertainment)
                $sTypes = db_query("SELECT fd.tid, fd.name FROM taxonomy_term_field_data fd JOIN taxonomy_term_hierarchy th 
                            ON fd.tid = th.tid WHERE fd.langcode = :langcode AND th.parent = :tid",
                    array(
                        ':langcode' => $langCode,
                        ':tid' => $parent->tid,
                    ))->fetchAll();
                if (count($sTypes) > 0) {
                    $count = count($sTypes);
                    $data['storeTypes'] = isset($data['storeTypes']) ? $data['storeTypes'] : array();
                    foreach ($sTypes as $sType) {
                      //Get the tids representing the subtypes for each type of store (Ex: Fashion - Men's, Women's, Children's, Sport)
                      $subTypes = db_query("SELECT fd.tid, fd.name FROM taxonomy_term_field_data fd JOIN taxonomy_term_hierarchy th 
                            ON fd.tid = th.tid WHERE fd.langcode = :langcode AND th.parent = :tid",
                        array(
                          ':langcode' => $langCode,
                          ':tid' => $sType->tid,
                        ))->fetchAll();
                      if (count($subTypes) > 0) {
                        $data['storeTypes'][$parent->name] = isset($data['storeTypes'][$parent->name]) ? $data['storeTypes'][$parent->name] : array();
                        foreach ($subTypes as $type) {
                          //Get the nids for stores within each subtype
                          $stores = db_query("SELECT entity_id FROM node__field_store_type WHERE field_store_type_target_id = :tid AND langcode = :langcode",
                            array(
                              ':tid' => $type->tid,
                              ':langcode' => $langCode,
                            ))->fetchAll();
                          if (count($stores) > 0) {
                            $data['storeTypes'][$parent->name][$sType->name] = isset($data['storeTypes'][$parent->name][$sType->name]) ? $data['storeTypes'][$parent->name][$sType->name] : array();
                            foreach (($stores) as $store) {
                              //Add the nids to our Data Array
                              $node = db_query("SELECT title FROM node_field_data WHERE nid = :nid AND langcode = :langcode",
                                array(
                                  ':nid' => $store->entity_id,
                                  ':langcode' => $langCode,
                                ))->fetchField();
                              $data['storeTypes'][$parent->name][$sType->name][$type->name][$node] = new \stdClass();
                              $data['storeTypes'][$parent->name][$sType->name][$type->name][$node]->title = $node;
                              $data['storeTypes'][$parent->name][$sType->name][$type->name][$node]->nid = $store->entity_id;


                            }
                          }
//                                if (  is_object($type) &&
//                                      is_array($data['storeTypes'][$parent->name][$sType->name][$type->name]) &&
//                                      $data['storeTypes'][$parent->name][$sType->name][$type->name] != null) {
//                                  if (!is_object($data['storeTypes'][$parent->name][$sType->name][$type->name])) {
////                                    $data['storeTypes'][$parent->name][$sType->name][$type->name] = array_values(array_unique($data['storeTypes'][$parent->name][$sType->name][$type->name]));
//                                    $wehere = ' now';
//                                  } else {
//                                    $wehere = ' now';
//                                  }
//                                }
                        }
                      } else {
                        //Get the nids for stores within this parent
                        $stores = db_query("SELECT entity_id FROM node__field_store_type WHERE field_store_type_target_id = :tid AND langcode = :langcode",
                          array(
                            ':tid' => $sType->tid,
                            ':langcode' => $langCode,
                          ))->fetchAll();
                        if (count($stores) > 0) {
                          $data['storeTypes'][$parent->name] = isset($data['storeTypes'][$parent->name]) ? $data['storeTypes'][$parent->name] : array();
                          $nCount = 0;
                          foreach (($stores) as $store) {
                            //Add the nids to our Data Array
                            $node = db_query("SELECT title FROM node_field_data WHERE nid = :nid AND langcode = :langcode",
                              array(
                                ':nid' => $store->entity_id,
                                ':langcode' => $langCode,
                              ))->fetchField();
                            $data['storeTypes'][$parent->name][$sType->name][$node . $nCount] = new \stdClass();
                            $data['storeTypes'][$parent->name][$sType->name][$node . $nCount]->title = $node;
                            $data['storeTypes'][$parent->name][$sType->name][$node . $nCount]->nid = $store->entity_id;
                          $nCount++;
                          }
                        }

                      }
                    }
                } else {
                    //Get the nids for stores within this parent
                    $stores = db_query("SELECT entity_id FROM node__field_store_type WHERE field_store_type_target_id = :tid AND langcode = :langcode",
                        array(
                            ':tid' => $parent->tid,
                            ':langcode' => $langCode,
                        ))->fetchAll();
                    if (count($stores) > 0) {
                        $data['storeTypes'][$parent->name] = isset($data['storeTypes'][$parent->name]) ? $data['storeTypes'][$parent->name] : array();
                        foreach (($stores) as $store) {
                            //Add the nids to our Data Array
                            $node = db_query("SELECT title FROM node_field_data WHERE nid = :nid and langcode = :langcode",
                                array(
                                    ':nid' => $store->entity_id,
                                    ':langcode' => $langCode,
                                ))->fetchField();
                          $data['storeTypes'][$parent->name][$node] = new \stdClass();
                          $data['storeTypes'][$parent->name][$node]->title = $node;
                          $data['storeTypes'][$parent->name][$node]->nid = $store->entity_id;
                        }
                    }
                }
            }
//            $data = array_map("unserialize", array_unique(array_map("serialize", $data)));
          $plugins = \Drupal::service('plugin.manager.entity_reference_selection')->getDefinitions();
            $test = 'test';
            if ($data != null) {

                $form['Search'] = array(
                    '#type' => 'entity_autocomplete',
                    '#placeholder' => 'Search',
                    '#entity_type' => 'node',
                    '#target_type' => 'node',
                    '#bundles' => array('boutique'),
                    '#autocomplete_route_name' => 'entity-autocomplete/node/boutique/',
                    '#selection_settings' => ['target_bundles' => ['boutique']],
                    '#selection_handler' => 'default:boutique',
                );

                $form['mapSubmit'] = array(
                    '#type' => 'button',
                    '#value' => t('Submit'),
                );

                $z = 0;

                foreach ($data['storeTypes'] as $key => $type) {
                    if (is_array($type)) {
                        if (!is_array(current($type))) {

                            $form[$key] = array(
                                '#type' => 'details',
                                '#title' => t(strtoupper($key)),
                                '#collapsible' => TRUE,
                                '#collapsed' => TRUE,
                                '#states' => array(
                                    'expanded' => array(
                                        ':input[name="'.$key.'"]' => array('value' => 'expand'),
                                    ),
                                ),
                            );
                            $s = 0;
                            foreach ($type as $store) {
                                if (!is_array($store)) {

                                $form[$key][$store->title] = array(
                                    '#type' => 'item',
//                                    '#title' => t('Store'),
                                    '#markup' => t($store->title) . '<span class="hidden-nid">' . $store->nid . '</span>',
                                    '#attributes' => array('tabindex' => 20+$z)
                                    );
                                } else {
                                    foreach ($store as $key => $subStore) {

                                        $form[$key][is_array($subStore) ? key($subStore) : $subStore] = array(
                                            '#type' => 'details',
                                            '#title' => t('Store'),
                                            '#collapsible' => TRUE,
                                            '#collapsed' => TRUE,
                                            '#states' => array(
                                                ':input[name="'.is_array($subStore) ? key($subStore) : $subStore.'"]' => array('value' => 'expand2'),
                                            ));
                                    }
                                }
                                $s++;
                            }
                            ksort($form[$key]);
                        } else {
                            $form[$key] = array(
                                '#type' => 'details',
                                '#title' => t(strtoupper($key)),
                                '#collapsible' => TRUE,
                                '#collapsed' => TRUE,
                                '#states' => array(
                                    'expanded' => array(
                                        ':input[name="'.$key.'"]' => array('value' => 'expand'),
                                    ),
                                ),
                            );
                            foreach ($type as $skey => $subType) {
                                if (is_array($subType)) {
                                    $form[$key][$skey] = array(
                                        '#type' => 'details',
                                        '#title' => t($skey),
                                        '#collapsible' => TRUE,
                                        '#collapsed' => TRUE,
                                        '#states' => array(
                                            'expanded' => array(
                                                ':input[name="'.$skey.'"]' => array('value' => 'expand'),
                                            ),
                                        ),
                                    );
                                    foreach ($subType as $vskey => $store) {
                                        if (!is_array($store)) {
                                            $form[$key][$skey][$vskey] = array(
                                                '#type' => 'item',
//                                            '#title' => t(is_array($store) ? $vskey : $store),
                                                '#markup' => t($store->title) . '<span class="hidden-nid">' . $store->nid . '</span>',
                                                '#attributes' => array('tabindex' => 20+$z)
                                            );
                                        } else {
                                            $form[$key][$skey][$vskey] = array(
                                                '#type' => 'details',
                                                '#title' => $vskey,
                                                '#collapsible' => TRUE,
                                                '#collapsed' => TRUE,
                                                '#states' => array(
                                                    'expanded' => array(
                                                        ':input[name="'.$vskey.'"]' => array('value' => 'expand'),
                                                    ),
                                                ),
                                            );
                                            foreach ($store as $subKey => $subStore) {
                                                $form[$key][$skey][$vskey][is_array($subStore->title) ? $subKey : $subStore->title] = array(
                                                    '#type' => 'item',
                                                    '#markup' => t(is_array($subStore) ? $subKey : $subStore->title) . '<span class="hidden-nid">' . $subStore->nid . '</span>',
                                                );
                                            }
                                        }
                                    }
                                  ksort($form[$key][$skey]);
                                }
                            }
                        }
                    } else {
                        $form[$key][$store == null ? 'null' : $store] = array(
                            '#type' => 'details',
                            '#title' => t($store == null ? 'null' : $store),
                            '#markup' => t($store == null ? 'null' : $store),
                           );
                    }
                    $z++;
                }
            }
        }

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
      /**
       * This function is ignored. Form submissions are handled in qd30-cesium.js
       */
  }
}
