<?php

namespace Drupal\basket\Admin\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class SettingsExportOrdersForm extends FormBase{
	
    protected static $Basket;
    protected static $Settings;

	public function __construct(){
		self::$Basket = \Drupal::service('Basket');
        self::$Settings = self::$Basket->getSettings('export_orders', 'config');
	}
	public function getFormId(){
    	return 'basket_export_orders_form_settings';
  	}
  	public function buildForm(array $form, FormStateInterface $form_state, $type = '', $tid = NULL){
        $form['#prefix'] = '<div id="table_excel">';
        $form['#suffix'] = '</div>';
        $form['#attached']['library'][] = 'basket/codemirror';
        $form['config'] = [
            '#tree'         => TRUE,
            'orders'        => [
                '#type'         => 'details',
                '#title'        => self::$Basket->Translate()->t('Orders'),
                '#open'         => TRUE,
                'header'        => [
                    '#type'         => 'item',
                    '#title'        => self::$Basket->Translate()->t('Column name').':',
                    self::getColumns(['config', 'orders', 'header'], TRUE)
                ],
                'data'          => [
                    '#type'         => 'item',
                    '#title'        => self::$Basket->Translate()->t('Order data').':',
                    self::getColumns(['config', 'orders', 'data'])
                ],
                'token'         => [
                    '#theme'        => 'token_tree_link',
                    '#token_types'  => ['user', 'node'],
                    '#text'         => self::$Basket->Translate()->t('[available tokens]')
                ],
                self::templateTokenTwig()
            ]
        ];
        // ---
        $form['actions'] = [
            '#type'         => 'actions',
            'submit'        => [
                '#type'         => 'submit',
                '#value'        => t('Save configuration')
            ]
        ];
        return $form;
  	}
  	public function submitForm(array &$form, FormStateInterface $form_state){
        self::$Basket->setSettings('export_orders', 'config', $form_state->getValue('config'));
    }
    private static function templateTokenTwig(){
        $tokents = [];
        foreach (\Drupal\basket\BasketExport::getTokenInfo() as $keyToken => $token) {
            if(!is_array($token)){
                $tokents[] = '{{'.$keyToken.'}} - <b>'.self::$Basket->Translate()->t(trim($token)).'</b>';
            } else {
                $tokents[] = '{{'.$keyToken.'}} - <b>'.self::$Basket->Translate()->t(trim($token['title'])).'</b>';
            }
        }
        return [
            '#type'         => 'details',
            '#title'        => self::$Basket->Translate()->t('Twig tokens'),
            '#description'  => implode('<br/>', $tokents)
        ];
    }
    private static function getColumns($parents, $isHeader = FALSE){
        $header = [''];
        $rows[0] = [
            '#markup'       => '1',
            '#wrapper_attributes'=> ['class' => ['td_num', 'not_hover']]
        ];
        foreach (range('A', 'Z') as $letter) {
            $header[] = $letter;
            $rows[$letter]['data'] = [
                '#type'         => 'textfield',
                '#parents'      => $parents+['letter' => $letter],
                '#default_value'=> !empty(self::$Settings[$parents[1]][$parents[2]][$letter]) ? self::$Settings[$parents[1]][$parents[2]][$letter] : ''
            ];
            if(!$isHeader){
                $rows[$letter]['data']['#type'] = 'textarea';
                $rows[$letter]['data']['#attributes']['class'][] = 'inline_twig inline_twig_excel';
                $rows[0]['#wrapper_attributes']['height'] = 100;
            }
        }
        return [
            '#type'         => 'table',
            '#header'       => $header,
            $rows,
            '#prefix'       => '<div class="table_excel_wrap '.implode('_', $parents).'">',
            '#suffix'       => '</div>'
        ];
    }
}