<?php

namespace Civi\DataProcessor\FieldOutputHandler;

use \Civi\DataProcessor\DataSpecification\FieldSpecification;
use \Civi\DataProcessor\FieldOutputHandler\AbstractSimpleFieldOutputHandler;
use \Civi\DataProcessor\FieldOutputHandler\FieldOutput;
use CRM_Dataprocessor_ExtensionUtil as E;
use Svg\DefaultStyle;

class ContactCountNumberOfCases extends AbstractSimpleFieldOutputHandler {

  private $settings;

  /**
   * 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()) {
    parent::buildConfigurationForm($form, $field);

    $caseTypesApi = civicrm_api4('CaseType', 'get', [
      'select' => ['title'],
      'where' => [['is_active', '=', TRUE]],
    ]);
    $caseTypes = array();
    foreach ($caseTypesApi as $caseType) {
      $caseTypes[] = $caseType['title'];
    }
    $form->add('select', 'case_type', E::ts('Case type'), $caseTypes, false, array(
      'style' => 'min-width:250px',
      'class' => 'crm-select2 huge',
      'placeholder' => E::ts('- Show all case types -'),
      'multiple' => true,
    ));

    $caseStatusListApi = civicrm_api4('OptionValue', 'get', [
      'select' => ['label'],
      'where' => [['option_group_id:name', '=', 'case_status']],
    ]);
    $caseStatusList = array();
    foreach ($caseStatusListApi as $status) {
      $caseStatusList[] = $status['label'];
    }
    $form->add('select', 'case_status', E::ts('Case status'), $caseStatusList, false, array(
      'style' => 'min-width:250px',
      'class' => 'crm-select2 huge',
      'placeholder' => E::ts('- Show all case statuses -'),
      'multiple' => true,
    ));

    $form->add('text', 'case_subject', E::ts('Case subject'), array(
      'style' => 'min-width:250px',
      'class' => 'huge',
    ), false);

    $form->add('checkbox', 'include_deleted', E::ts('Include deleted cases'), false, false);
    $form->add('checkbox', 'ignore_permission', E::ts('Ignore the permission check for the API calls'), false, false);

    for ($i = 1; $i <= 3; ++$i) {
      $form->add('text', "generic_input_{$i}", E::ts("Input field {$i}"), array(
        'style' => 'min-width:250px',
        'class' => 'huge',
      ), false);
      $form->add('text', "generic_match_{$i}", E::ts("Value to match {$i}"), array(
        'style' => 'min-width:250px',
        'class' => 'huge',
      ), false);
    }

    if (isset($field['configuration'])) {
      $configuration = $field['configuration'];
      $defaults = array();
      if (isset($configuration['case_type'])) {
        $defaults['case_type'] = $configuration['case_type'];
      }
      if (isset($configuration['case_status'])) {
        $defaults['case_status'] = $configuration['case_status'];
      }
      if (isset($configuration['case_subject'])) {
        $defaults['case_subject'] = $configuration['case_subject'];
      }
      if (isset($configuration['include_deleted'])) {
        $defaults['include_deleted'] = $configuration['include_deleted'];
      }
      if (isset($configuration['ignore_permission'])) {
        $defaults['ignore_permission'] = $configuration['ignore_permission'];
      }
      for ($i = 1; $i <= 3; ++$i) {
        if (isset($configuration["generic_input_{$i}"])) {
          $defaults["generic_input_{$i}"] = $configuration["generic_input_{$i}"];
        }
        if (isset($configuration["generic_match_{$i}"])) {
          $defaults["generic_match_{$i}"] = $configuration["generic_match_{$i}"];
        }
      }
      $form->setDefaults($defaults);
    }
  }

  /**
   * Process the submitted values and create a configuration array
   *
   * @param $submittedValues
   * @return array
   */
  public function processConfiguration($submittedValues) {

    $configuration = parent::processConfiguration($submittedValues);


    $configuration['case_type'] = isset($submittedValues['case_type']) ? $submittedValues['case_type'] : null;
    $configuration['case_status'] = isset($submittedValues['case_status']) ? $submittedValues['case_status'] : null;
    $configuration['case_subject'] = isset($submittedValues['case_subject']) ? $submittedValues['case_subject'] : null;
    $configuration['include_deleted'] = isset($submittedValues['include_deleted']) ? $submittedValues['include_deleted'] : 0;
    $configuration['ignore_permission'] = isset($submittedValues['ignore_permission']) ? $submittedValues['ignore_permission'] : 0;
    $configuration['ignore_permission'] = isset($submittedValues['ignore_permission']) ? $submittedValues['ignore_permission'] : 0;

    for ($i = 1; $i <= 3; ++$i) {
      $configuration["generic_input_{$i}"] = isset($submittedValues["generic_input_{$i}"]) ? $submittedValues["generic_input_{$i}"] : null;
      $configuration["generic_match_{$i}"] = isset($submittedValues["generic_match_{$i}"]) ? $submittedValues["generic_match_{$i}"] : null;
    }

    return $configuration;
  }

  public function getConfigurationTemplateFileName() {
    return "CRM/Dataprocessor/Form/Field/Configuration/ContactCountNumberOfCases.tpl";
  }

  /**
   * Initialize the processor
   *
   * @param String $alias
   * @param String $title
   * @param array $configuration
   * @param \Civi\DataProcessor\ProcessorType\AbstractProcessorType $processorType
   */
  public function initialize($alias, $title, $configuration) {
    parent::initialize($alias, $title, $configuration);
    $this->outputFieldSpec = new FieldSpecification($alias, 'Integer', $title, null, $alias);
    $this->initializeConfiguration($configuration);
  }

  /**
   * @param array $configuration
   *
   * @return void
   */
  protected function initializeConfiguration($configuration) {
    foreach ($configuration as $key => $item) {
      if ($key == 'case_type') {
        $caseTypesApi = civicrm_api4('CaseType', 'get', [
          'select' => ['id', 'title'],
          'where' => [['is_active', '=', TRUE]],
          'checkPermissions' => FALSE,
        ]);
        $this->settings['case_type'] = array();
        foreach ($item as $index) {
          $this->settings['case_type'][] = $caseTypesApi[(int) $index]['id'];
        }
      }
      elseif ($key == 'case_status') {
        $caseStatusListApi = civicrm_api4('OptionValue', 'get', [
          'select' => ['value'],
          'where' => [['option_group_id:name', '=', 'case_status']],
          'checkPermissions' => FALSE,
        ]);
        $this->settings['case_status'] = array();
        foreach ($item as $index) {
          $this->settings['case_status'][] = $caseStatusListApi[(int) $index]['value'];
        }
      }
      else {
        $this->settings[$key] = $item;
      }
    }
  }
  /**
   * @return string
   */
  protected function getFieldTitle() {
    return E::ts('CiviCRM ID');
  }

  protected function getType() {
    return 'Integer';
  }


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

    $apiParams = array();
    $apiParams['select'] = array('id');
    $apiParams['where'] = array(
      ['contact_id', '=', $inputField]
    );

    if (!empty($this->settings['case_type'])) {
      $apiParams['where'][] = ['case_id.case_type_id', 'IN', $this->settings['case_type']];
    }
    if (!empty($this->settings['case_status'])) {
      $apiParams['where'][] = ['case_id.status_id', 'IN', $this->settings['case_status']];
    }
    if (!empty($this->settings['case_subject'])) {
      $apiParams['where'][] = ['case_id.subject', '=', $this->settings['case_subject']];
    }
    if (!isset($this->settings['include_deleted']) || $this->settings['include_deleted'] == 0) {
      $apiParams['where'][] = ['case_id.is_deleted', '=', FALSE];
    }
    if (isset($this->settings['ignore_permission']) && $this->settings['ignore_permission'] == 1) {
      $apiParams['checkPermissions'] = FALSE;
      }
    for ($i = 1; $i <= 3; ++$i) {
      if (!empty($this->settings["generic_input_{$i}"]) && !empty($this->settings["generic_match_{$i}"])) {
        $apiParams['where'][] = [$this->settings["generic_input_{$i}"], '=', $this->settings["generic_match_{$i}"]];
      }
    }


    $cases = civicrm_api4('CaseContact', 'get', $apiParams);

    $result = sizeof($cases);

    if($inputField == 89) {
      $test = 'Test';
    }

    return new FieldOutput($result);
  }
}
