<?php
/**
 * Copyright (C) 2023  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_Core_Form;
use CRM_Dataprocessor_ExtensionUtil as E;
use CRM_Dataprocessor_Utils_DataSourceFields;
use CRM_Utils_Type;

class ContactHasActiveRecurringContributions extends AbstractFieldFilterHandler {

  /** @var array */
  private static $activeContributionRecurStatusIds;

  /**
   * 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']);
    $this->fieldSpecification->type = 'Integer';
  }

  /**
   * Returns true when this filter has additional configuration
   *
   * @return bool
   */
  public function hasConfiguration(): bool {
    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']);

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

    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']);
      }
      $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/ContactHasActiveRecurringContributions.tpl";
  }


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

  protected function getOperatorOptions(FieldSpecification $fieldSpec) {
    return array(
      'IN' => E::ts('Has at least X active recurring contributions'),
      'NOT IN' => E::ts('Does not have more than X active recurring contributions'),
    );
  }

  /**
   * @param array $filter
   *   The filter settings
   */
  public function setFilter($filter) {
    $this->resetFilter();
    $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;
      $value = CRM_Utils_Type::escape($filter['value'], 'Integer');
      $activeContributionStatusIds = $this->getActiveRecurringContributionStatusIds();
      if (empty($activeContributionStatusIds)) {
        return;
      }
      $sqlStatement = "`{$tableAlias}`.`{$fieldName}` {$filter['op']} (
        SELECT `contact_id`
        FROM `civicrm_contribution_recur` `recur_{$fieldAlias}`
        WHERE
				(`recur_{$fieldAlias}`.`cancel_date` IS NULL OR `recur_{$fieldAlias}`.`cancel_date` > CURRENT_DATE)
				AND (`recur_{$fieldAlias}`.`end_date` IS NULL OR `recur_{$fieldAlias}`.`end_date` > CURRENT_DATE)
				AND `contribution_status_id` IN (" . implode(', ', $activeContributionStatusIds) . ")
				AND `is_test` = 0
				GROUP BY `contact_id`
        HAVING COUNT(*) >= {$value}
        ";
      $sqlStatement .= ")";
      $this->whereClause = new SqlDataFlow\PureSqlStatementClause($sqlStatement, FALSE);
      $this->filterCollection->addWhere($this->whereClause);
    }
  }

  protected function getActiveRecurringContributionStatusIds(): array {
    if (empty(static::$activeContributionRecurStatusIds)) {
      static::$activeContributionRecurStatusIds = [];
      $activityContributionStatusNames = [
        'Pending',
        'In Progress',
        'Processing'
      ];

      try {
        $result = civicrm_api3('OptionValue', 'get', [
          'sequential' => 1,
          'option_group_id' => "contribution_recur_status",
          'options' => ['limit' => 0],
        ]);
        foreach($result['values'] as $value) {
          if (in_array($value['name'], $activityContributionStatusNames)) {
            static::$activeContributionRecurStatusIds[] = $value['value'];
          }
        }
      } catch (\CiviCRM_API3_Exception $e) {
      }
    }
    return static::$activeContributionRecurStatusIds;
  }


}
