<?php

namespace Drupal\basket\Plugin\views\filter;

use Drupal\views\Plugin\views\filter\FilterPluginBase;
use Drupal\views\Views;

/**
 * Filter by In Stosk.
 *
 * @ViewsFilter("basket_product_in_stock")
 */
class BasketProductInStosk extends FilterPluginBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    if (empty($this->query->relationships['basket_product_in_stock'])) {
      if (!empty($subQueryCount = \Drupal::getContainer()
        ->get('BasketQuery')
        ->getQtyQuery())) {
        $join = Views::pluginManager('join')->createInstance('standard', [
          'type' => 'INNER',
          'table' => $subQueryCount,
          'field' => 'nid',
          'left_table' => 'node_field_data',
          'left_field' => 'nid',
          'operator' => '=',
        ]);
        $this->query->addRelationship('basket_product_in_stock', $join, 'node_field_data');
      }
    }
    if (!empty($this->query->relationships['basket_product_in_stock'])) {
      $this->query->addWhere(NULL, 'basket_product_in_stock.count', 0, '>');
    }
  }
}
