<?php
/**
 * @ViewsField("basket_user_sum_field")
 */

namespace Drupal\basket\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Drupal\Core\Form\FormStateInterface;
use Drupal\basket\Query\BasketGetUserSumQuery;

class BasketUserSumField extends FieldPluginBase {

    protected $basket;

    public function __construct(){
        call_user_func_array(array('parent', '__construct'), func_get_args());
        $this->basket = \Drupal::service('Basket');
    }

    protected function defineOptions() {
        $options = parent::defineOptions();
        $options['templateTwig'] = ['default' => '{{ sum|number_format(2, \',\', \'\') }} {{ currency }}'];
        return $options;
    }
    public function buildOptionsForm(&$form, FormStateInterface $form_state) {
        $form['templateTwig'] = array(
            '#type'             => 'textarea',
            '#title'            => 'Render template (Twig)',
            '#rows'             => 1,
            '#default_value'    => $this->options['templateTwig'],
            '#description'      => implode('<br/>', [
                '{{ sum }}',
                '{{ currency }}'
            ])
        );
        parent::buildOptionsForm($form, $form_state);
    }
    public function query(){
        BasketGetUserSumQuery::viewsJoin($this);
    }
    public function clickSort($order){
        BasketGetUserSumQuery::clickSort($this, $order);
    }
    public function render(ResultRow $values){
        return [
            '#type'         => 'inline_template',
            '#template'     => $this->options['templateTwig'],
            '#context'      => [
                'sum'           => !empty($values->{$this->field.'_total_sum'}) ? $values->{$this->field.'_total_sum'} : 0,
                'currency'      => $this->basket->Cart()->getCurrencyName()
            ]
        ];
    }
}