<?php
/**
 * Copyright (C) 2022  Jaap Jansma (jaap.jansma@civicoop.org)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

namespace Civi\DataProcessor\FilterHandler;

use Civi\DataProcessor\DataFlow\SqlDataFlow;
use Civi\DataProcessor\DataSpecification\FieldSpecification;
use Civi\DataProcessor\Exception\InvalidConfigurationException;
use CRM_Dataprocessor_ExtensionUtil as E;

class LastEventDateFilter extends AbstractFieldFilterHandler {

  /**
   * @var array
   */
  protected $event_types = [];

  /**
   * Initialize the filter
   *
   * @throws \Civi\DataProcessor\Exception\DataSourceNotFoundException
   * @throws \Civi\DataProcessor\Exception\InvalidConfigurationException
   * @throws \Civi\DataProcessor\Exception\FieldNotFoundException
   */
  protected function doInitialization() {
    if (!isset($this->configuration['datasource']) || !isset($this->configuration['field'])) {
      throw new InvalidConfigurationException(E::ts("Filter %1 requires a field to filter on. None given.", array(1=>$this->title)));
    }
    $this->initializeField($this->configuration['datasource'], $this->configuration['field']);

    if (isset($this->configuration['event_types']) && $this->configuration['event_types']) {
      $this->event_types = $this->configuration['event_types'];
    }
  }

  /**
   * Returns true when this filter has additional configuration
   *
   * @return bool
   */
  public function hasConfiguration() {
    return true;
  }

  /**
   * When this filter type has additional configuration you can add
   * the fields on the form with this function.
   *
   * @param \CRM_Core_Form $form
   * @param array $filter
   */
  public function buildConfigurationForm(\CRM_Core_Form $form, $filter=array()) {
    $fieldSelect = \CRM_Dataprocessor_Utils_DataSourceFields::getAvailableFilterFieldsInDataSources($filter['data_processor_id']);
    $eventTypes = [];
    $optionValues = \Civi\Api4\OptionValue::get()
      ->addWhere('option_group_id:name', '=', 'event_type')
      ->setLimit(0)
      ->execute();
    foreach($optionValues as $optionValue) {
      $eventTypes[$optionValue['value']] = $optionValue['label'];
    }

    $form->add('select', 'contact_id_field', E::ts('Contact ID Field'), $fieldSelect, true, array(
      'style' => 'min-width:250px',
      'class' => 'crm-select2 huge data-processor-field-for-name',
      'placeholder' => E::ts('- select -'),
    ));

    $form->add('select', 'event_types', E::ts('Event Types'), $eventTypes, false, array(
      'style' => 'min-width:250px',
      'class' => 'crm-select2 huge',
      'placeholder' => E::ts('- All Events -'),
      'multiple' => true,
    ));

    if (isset($filter['configuration'])) {
      $configuration = $filter['configuration'];
      $defaults = array();
      if (isset($configuration['field']) && isset($configuration['datasource'])) {
        $defaults['contact_id_field'] = \CRM_Dataprocessor_Utils_DataSourceFields::getSelectedFieldValue($filter['data_processor_id'], $configuration['datasource'], $configuration['field']);
      }
      if (isset($configuration['event_types'])) {
        $defaults['event_types'] = $configuration['event_types'];
      }
      $form->setDefaults($defaults);
    }
  }

  /**
   * When this filter type has configuration specify the template file name
   * for the configuration form.
   *
   * @return false|string
   */
  public function getConfigurationTemplateFileName() {
    return "CRM/Dataprocessor/Form/Filter/Configuration/LastEventDateFilter.tpl";
  }


  /**
   * Process the submitted values and create a configuration array
   *
   * @param array $submittedValues
   * @return array
   */
  public function processConfiguration($submittedValues): array {
    [$datasource, $field] = explode('::', $submittedValues['contact_id_field'], 2);
    $configuration['field'] = $field;
    $configuration['datasource'] = $datasource;
    $configuration['event_types'] = isset($submittedValues['event_types']) ? $submittedValues['event_types'] : [];
    return $configuration;
  }

  /**
   * File name of the template to add this filter to the criteria form.
   *
   * @return string
   */
  public function getTemplateFileName() {
    return "CRM/Dataprocessor/Form/Filter/LastEventDateFilter.tpl";
  }

  protected function getOperatorOptions(FieldSpecification $fieldSpec) {
    return array(
      '>' => E::ts('Is more than'),
      '<' => E::ts('Is less than'),
      'bw' => E::ts('Is between'),
      'nbw' => E::ts('Is not between'),
    );
  }

  /**
   * Add the elements to the filter form.
   *
   * @param \CRM_Core_Form $form
   * @param array $defaultFilterValue
   * @param string $size
   *   Possible values: full or compact
   * @return array
   *   Return variables belonging to this filter.
   */
  public function addToFilterForm(\CRM_Core_Form $form, $defaultFilterValue, $size='full') {
    $fieldSpec = $this->getFieldSpecification();
    $operations = $this->getOperatorOptions($fieldSpec);
    $defaults = array();

    $title = $fieldSpec->title;
    $alias = $fieldSpec->alias;
    if ($this->isRequired()) {
      $title .= ' <span class="crm-marker">*</span>';
    }

    $sizeClass = 'huge';
    $minWidth = 'min-width: 250px;';
    if ($size =='compact') {
      $sizeClass = 'medium';
      $minWidth = '';
    }

    $form->add('select', "{$alias}_op", E::ts('Operator:'), $operations, true, [
      'onchange' => "return showHideMaxMinVal( '$alias', this.value );",
      'style' => $minWidth,
      'class' => 'crm-select2 '.$sizeClass,
      'multiple' => FALSE,
      'placeholder' => E::ts('- select -'),
    ]);
    // we need text box for value input
    $form->add('text', "{$alias}_value", NULL, ['class' => $sizeClass]);
    if (isset($defaultFilterValue['op']) && $defaultFilterValue['op']) {
      $defaults[$alias . '_op'] = $defaultFilterValue['op'];
    } else {
      $defaults[$alias . '_op'] = key($operations);
    }
    if (isset($defaultFilterValue['value'])) {
      $defaults[$alias.'_value'] = $defaultFilterValue['value'];
    }

    // and a min value input box
    $form->add('text', "{$alias}_min", E::ts('Min'), ['class' => $sizeClass]);
    // and a max value input box
    $form->add('text', "{$alias}_max", E::ts('Max'), ['class' => $sizeClass]);

    if (isset($defaultFilterValue['min'])) {
      $defaults[$alias.'_min'] = $defaultFilterValue['min'];
    }
    if (isset($defaultFilterValue['max'])) {
      $defaults[$alias.'_max'] = $defaultFilterValue['max'];
    }

    $filter['type'] = $fieldSpec->type;
    $filter['alias'] = $fieldSpec->alias;
    $filter['title'] = $title;
    $filter['size'] = $size;

    if (count($defaults)) {
      $form->setDefaults($defaults);
    }

    return $filter;
  }

  /**
   * @param array $filter
   *   The filter settings
   * @return mixed
   */
  public function setFilter($filter) {
    $this->resetFilter();

    $value = null;
    if (isset($filter['value']) && is_array($filter['value'])) {
      $value = array();
      foreach($filter['value'] as $v) {
        $dateTime = new \DateTime($v);
        $value[] = "'" .  \CRM_Utils_Type::escape($dateTime->format('Y-m-d'), 'String') . "'";
      }
    } elseif (isset($filter['value'])) {
      $dateTime = new \DateTime($filter['value']);
      $value = "'". \CRM_Utils_Type::escape($dateTime->format('Y-m-d'), 'String') . "'";
    }

    if ($filter['op'] == 'BETWEEN' || $filter['op'] == 'NOT BETWEEN') {
      $value = implode(" AND ", $value);
    }


    $dataFlow  = $this->dataSource->ensureField($this->inputFieldSpecification);
    if ($dataFlow && $dataFlow instanceof SqlDataFlow && $this->filterCollection->useWhere()) {
      $tableAlias = $this->getTableAlias($dataFlow);
      $fieldName = $this->inputFieldSpecification->getName();
      $fieldAlias = $this->inputFieldSpecification->alias;
      $sqlStatement = "`{$tableAlias}`.`{$fieldName}` NOT IN (
        SELECT `contact_id`
        FROM `civicrm_participant` `p_{$fieldAlias}`
        INNER JOIN `civicrm_event` `e_{$fieldAlias}` ON `e_{$fieldAlias}`.`id` = `p_{$fieldAlias}`.`event_id`
        WHERE `e_{$fieldAlias}`.`start_date` {$filter['op']} {$value}";
      if (count($this->event_types)) {
        $sqlStatement .= " AND `e_{$fieldAlias}`.`event_type_id` IN (" . implode(",", $this->event_types) . ")";
      }
      $sqlStatement .= ")";
      $this->whereClause = new SqlDataFlow\PureSqlStatementClause($sqlStatement, FALSE);
      $this->filterCollection->addWhere($this->whereClause);
    }


  }

}
