<?php
/**
 * @author Jaap Jansma <jaap.jansma@civicoop.org>
 * @license AGPL-3.0
 */

namespace Civi\DataProcessor\FieldOutputHandler;

use Civi\DataProcessor\ProcessorType\AbstractProcessorType;
use CRM_Dataprocessor_ExtensionUtil as E;
use Civi\DataProcessor\Source\SourceInterface;
use Civi\DataProcessor\DataSpecification\FieldSpecification;
use Civi\DataProcessor\Exception\DataSourceNotFoundException;
use Civi\DataProcessor\Exception\FieldNotFoundException;
use Civi\DataProcessor\FieldOutputHandler\FieldOutput;

class MembershipsFieldOutputHandler extends AbstractFieldOutputHandler {

  /**
   * @var \Civi\DataProcessor\Source\SourceInterface
   */
  protected $dataSource;

  /**
   * @var SourceInterface
   */
  protected $contactIdSource;

  /**
   * @var FieldSpecification
   */
  protected $contactIdField;

  /**
   * @var FieldSpecification
   */
  protected $outputFieldSpecification;

  /**
   * @var array
   */
  protected $membership_type_ids = array();

  protected $separator = ', ';

  /**
   * @return \Civi\DataProcessor\DataSpecification\FieldSpecification
   */
  public function getOutputFieldSpecification() {
    return $this->outputFieldSpecification;
  }

  /**
   * Returns the data type of this field
   *
   * @return String
   */
  protected function getType() {
    return 'String';
  }

  /**
   * Initialize the processor
   *
   * @param String $alias
   * @param String $title
   * @param array $configuration
   * @param \Civi\DataProcessor\ProcessorType\AbstractProcessorType $processorType
   */
  public function initialize($alias, $title, $configuration) {
    list($this->contactIdSource, $this->contactIdField) = $this->initializeField($configuration['field'], $configuration['datasource'], $alias);
    $this->outputFieldSpecification = new FieldSpecification($this->contactIdField->name, 'String', $title, null, $alias);
    if (isset($configuration['membership_types']) && is_array($configuration['membership_types'])) {
      $this->membership_type_ids = array();
      foreach($configuration['membership_types'] as $membership_type) {
        $membership_type_id = civicrm_api3('MembershipType', 'getvalue', ['return' => 'id', 'name' => $membership_type]);
        $this->membership_type_ids[] = $membership_type_id;
      };
    }
    if (isset($configuration['separator'])) {
      $this->separator = $configuration['separator'];
    }
  }

  /**
   * Returns the formatted value
   *
   * @param $rawRecord
   * @param $formattedRecord
   *
   * @return \Civi\DataProcessor\FieldOutputHandler\FieldOutput
   */
  public function formatField($rawRecord, $formattedRecord) {
    $contactId = $rawRecord[$this->contactIdField->alias];

    $sqlStatements = [];

    $order = 1;
    if (count($this->membership_type_ids)) {
      foreach($this->membership_type_ids as $membership_type_id) {
        $sqlStatements[] = "
          SELECT `civicrm_membership_type`.`name` as `name`, " . $order . " AS `order`
          FROM `civicrm_membership`
          INNER JOIN `civicrm_membership_type` ON `civicrm_membership`.`membership_type_id` = `civicrm_membership_type`.`id`
          INNER JOIN `civicrm_membership_status` ON `civicrm_membership`.`status_id` = `civicrm_membership_status`.`id`
          WHERE `civicrm_membership`.`contact_id` = %1
          AND `civicrm_membership_status`.`is_current_member` = '1'
          AND `civicrm_membership_type`.`id` = '" . \CRM_Utils_Type::escape($membership_type_id, 'Integer') . "'
        ";
        $order ++;
      }
    } else {
      $sqlStatements[] = "
        SELECT `civicrm_membership_type`.`name` as `name`, 1 as `order`
        FROM `civicrm_membership`
        INNER JOIN `civicrm_membership_type` ON `civicrm_membership`.`membership_type_id` = `civicrm_membership_type`.`id`
        INNER JOIN `civicrm_membership_status` ON `civicrm_membership`.`status_id` = `civicrm_membership_status`.`id`
        WHERE `civicrm_membership`.`contact_id` = %1 AND `civicrm_membership_status`.`is_current_member` = '1'
      ";
    }
    $formattedValues = [];
    $htmlFormattedValues = [];
    $output = new HTMLFieldOutput($contactId);

    if (count($sqlStatements)) {
      $sql = implode(" UNION ", $sqlStatements) . " ORDER BY `order` ASC, `name` ASC";
      $sqlParams[1] = [$contactId, 'Integer'];
      $dao = \CRM_Core_DAO::executeQuery($sql, $sqlParams);

      while ($dao->fetch()) {
        $formattedValues[] = $dao->name;
      }
    }
    $output->formattedValue = implode($this->separator, $formattedValues);
    $output->setHtmlOutput(implode("\r\n", $htmlFormattedValues));
    return $output;
  }

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

  /**
   * When this handler has additional configuration you can add
   * the fields on the form with this function.
   *
   * @param \CRM_Core_Form $form
   * @param array $field
   */
  public function buildConfigurationForm(\CRM_Core_Form $form, $field=array()) {
    $fieldSelect = \CRM_Dataprocessor_Utils_DataSourceFields::getAvailableFieldsInDataSources($field['data_processor_id']);
    $membershipTypeApi = civicrm_api3('MembershipType', 'get', [
      'options' => ['limit' => 0]
    ]);
    $membershipTypes = [];

    foreach ($membershipTypeApi['values'] as $membership_type) {
      $membershipTypes[$membership_type['name']] = $membership_type['name'];
    }
    if (isset($field['configuration']) && isset($field['configuration']['membership_types'])) {
      foreach (array_reverse($field['configuration']['membership_types']) as $membership_type) {
        $label = $membershipTypes[$membership_type];
        unset($membershipTypes[$membership_type]);
        $membershipTypes = array_merge([$membership_type => $label], $membershipTypes);
      }
    }

    $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 -'),
    ));

    $membershipTypes = array_flip($membershipTypes);
    $form->addCheckBox('membership_type_checkboxes',  E::ts('Restrict to membership types'), $membershipTypes);
    $form->assign('membership_types', $membershipTypes);
    $form->add('hidden', 'sorted_membership_types', null, ['id' => 'sorted_membership_types']);
    // Backwords compatibilty
    $form->assign('useSortIcon', false);
    if (version_compare(\CRM_Utils_System::version(), '5.15', '<')) {
      $form->assign('useSortIcon', true);
    }
    $form->add('text', 'separator', E::ts('Separator'), true);
    $defaults = array();
    if (isset($field['configuration'])) {
      $configuration = $field['configuration'];
      if (isset($configuration['field']) && isset($configuration['datasource'])) {
        $defaults['contact_id_field'] = \CRM_Dataprocessor_Utils_DataSourceFields::getSelectedFieldValue($field['data_processor_id'], $configuration['datasource'], $configuration['field']);
      }
      if (isset($configuration['membership_types'])) {
        $defaults['membership_type_checkboxes'] = array();
        foreach($configuration['membership_types'] as $membership_type) {
          $defaults['membership_type_checkboxes'][$membership_type] = 1;
        }
      }
      if (isset($configuration['separator'])) {
        $defaults['separator'] = $configuration['separator'];
      }
    }
    if (!isset($defaults['separator'])) {
      $defaults['separator'] = ',';
    }
    $form->setDefaults($defaults);
  }

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


  /**
   * Process the submitted values and create a configuration array
   *
   * @param $submittedValues
   * @return array
   */
  public function processConfiguration($submittedValues) {
    list($datasource, $field) = explode('::', $submittedValues['contact_id_field'], 2);
    $configuration['field'] = $field;
    $configuration['datasource'] = $datasource;
    $configuration['separator'] = $submittedValues['separator'];
    if (!empty($submittedValues['sorted_membership_types'])) {
      $sortedMembershipTypes = explode(',', $submittedValues['sorted_membership_types']);
      $configuration['relationship_types'] = [];
      foreach ($sortedMembershipTypes as $key => $val) {
        if ($val && isset($submittedValues['membership_type_checkboxes'][$val])) {
          $configuration['membership_types'][] = $val;
        }
      }
    } elseif (isset($submittedValues['membership_type_checkboxes'])) {
      $configuration['membership_types'] = array_keys($submittedValues['membership_type_checkboxes']);
    }

    return $configuration;
  }




}
