<?php

namespace Drupal\basket\Query;
use Drupal\views\Views;

class BasketGetUserSumQuery{

    protected static $getQuery;

    public static function getQuery(){
        if(!self::$getQuery){
            self::$getQuery = \Drupal::database()->select('node_field_data', 'n');
            self::$getQuery->fields('n', ['uid']);
            // basket_orders
            self::$getQuery->innerJoin('basket_orders', 'b', 'b.nid = n.nid');
            // basket_currency
            self::$getQuery->innerJoin('basket_currency', 'bc', 'bc.id = b.currency');
            self::$getQuery->innerJoin('basket_currency', 'bc_def', 'bc_def.id = '.\Drupal::service('Basket')->Currency()->getCurrent());
            // ---
            self::$getQuery->addExpression('SUM(b.price*(bc.rate/bc_def.rate))', 'total_sum');
            self::$getQuery->groupBy('n.uid');
        }
        return self::$getQuery;
    }
    public static function viewsJoin(&$view){
        if(empty($view->query->relationships[$view->field.'_getUserSumQuery'])){
            $subQuery = self::getQuery();
            if(!empty($subQuery)){
                $join = Views::pluginManager('join')->createInstance('standard', [
                    'type'          => 'LEFT',
                    'table'         => $subQuery,
                    'field'         => 'uid',
                    'left_table'    => 'users_field_data',
                    'left_field'    => 'uid',
                    'operator'      => '=',
                ]);
                $rel = $view->query->addRelationship($view->field.'_getUserSumQuery', $join, 'users_field_data');
                $view->query->addField($view->field.'_getUserSumQuery', 'total_sum', $view->field.'_total_sum');
            }
        }
    }
    public static function clickSort(&$view, $order){
        self::viewsJoin($view);
        if(!empty($view->query->relationships[$view->field.'_getUserSumQuery'])){
            $view->query->addOrderBy($view->field.'_getUserSumQuery', 'total_sum', $order);
        }
    }
}