<?php
/*
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC. All rights reserved.                        |
 |                                                                    |
 | This work is published under the GNU AGPLv3 license with some      |
 | permitted exceptions and without any warranty. For full license    |
 | and copyright information, see https://civicrm.org/licensing       |
 +--------------------------------------------------------------------+
 */

/**
 *
 * @package CRM
 * @copyright CiviCRM LLC https://civicrm.org/licensing
 */
class CRM_Case_XMLProcessor_Report extends CRM_Case_XMLProcessor {

  /**
   * The default variable defined.
   *
   * @var bool
   */
  protected $_isRedact;

  /**
   * Redaction Rules.
   *
   * @var array
   */
  protected $_redactionStringRules = [];

  /**
   * @var array
   */
  public $_redactionRegexRules;

  /**
   */
  public function __construct() {
  }

  public function getRedactionRules() {
    foreach (['redactionStringRules', 'redactionRegexRules'] as $key => $rule) {
      $$rule = CRM_Case_PseudoConstant::redactionRule($key);

      if (!empty($$rule)) {
        foreach ($$rule as & $val) {
          //suffixed with a randomly generated 4-digit number
          if ($key == 'redactionStringRules') {
            $val .= rand(10000, 100000);
          }
        }

        if (!empty($this->{'_' . $rule})) {
          $this->{'_' . $rule} = CRM_Utils_Array::crmArrayMerge($this->{'_' . $rule}, $$rule);
        }
        else {
          $this->{'_' . $rule} = $$rule;
        }
      }
    }
  }

  /**
   * @param int $clientID
   * @param int $caseID
   *
   * @return array
   */
  public function &caseInfo(
    $clientID,
    $caseID
  ) {
    $case = $this->_redactionRegexRules = [];

    if (empty($this->_redactionStringRules)) {
      $this->_redactionStringRules = [];
    }

    if ($this->_isRedact == 1) {
      $this->getRedactionRules();
    }

    $client = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $clientID, 'display_name');

    // add Client to the strings to be redacted across the case session
    if (!array_key_exists($client, $this->_redactionStringRules)) {
      $this->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($this->_redactionStringRules,
        [$client => 'name_' . rand(10000, 100000)]
      );
      $clientSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $clientID, 'sort_name');
      if (!array_key_exists($clientSortName, $this->_redactionStringRules)) {
        $this->_redactionStringRules[$clientSortName] = $this->_redactionStringRules[$client];
      }
    }

    $case['clientName'] = $this->redact($client);

    $dao = new CRM_Case_DAO_Case();
    $dao->id = $caseID;
    if ($dao->find(TRUE)) {
      $case['subject'] = $dao->subject;
      $case['start_date'] = $dao->start_date;
      $case['end_date'] = $dao->end_date;
      $case['caseType'] = CRM_Case_BAO_Case::getCaseType($caseID);
      $case['caseTypeName'] = CRM_Case_BAO_Case::getCaseType($caseID, 'name');
      $case['status'] = CRM_Core_PseudoConstant::getLabel('CRM_Case_BAO_Case', 'status_id', $dao->status_id);
    }
    return $case;
  }

  /**
   * @param $xml
   * @param string $activitySetName
   *
   * @return array|bool
   */
  public function getActivityTypes($xml, $activitySetName) {
    foreach ($xml->ActivitySets as $activitySetsXML) {
      foreach ($activitySetsXML->ActivitySet as $activitySetXML) {
        if ((string ) $activitySetXML->name == $activitySetName) {
          $activityTypes = [];
          $allActivityTypes = CRM_Case_PseudoConstant::caseActivityType(TRUE, TRUE);
          foreach ($activitySetXML->ActivityTypes as $activityTypesXML) {
            foreach ($activityTypesXML as $activityTypeXML) {
              $activityTypeName = (string ) $activityTypeXML->name;
              $activityTypeInfo = $allActivityTypes[$activityTypeName] ?? NULL;
              if ($activityTypeInfo) {
                $activityTypes[$activityTypeInfo['id']] = $activityTypeInfo;
              }
            }
          }
          return empty($activityTypes) ? FALSE : $activityTypes;
        }
      }
    }
    return FALSE;
  }

  /**
   * @param $xml
   * @param string $activitySetName
   *
   * @return null|string
   */
  public function getActivitySetLabel($xml, $activitySetName) {
    foreach ($xml->ActivitySets as $activitySetsXML) {
      foreach ($activitySetsXML->ActivitySet as $activitySetXML) {
        if ((string ) $activitySetXML->name == $activitySetName) {
          return (string ) $activitySetXML->label;
        }
      }
    }
    return NULL;
  }

  /**
   * @param int $clientID
   * @param int $caseID
   * @param $activityTypes
   * @param $activities
   */
  public function getActivities($clientID, $caseID, $activityTypes, &$activities) {
    // get all activities for this case that in this activityTypes set
    foreach ($activityTypes as $aType) {
      $map[$aType['id']] = $aType;
    }

    $activityTypeIDs = implode(',', array_keys($map));
    $query = "
SELECT a.*, c.id as caseID
FROM   civicrm_activity a,
       civicrm_case     c,
       civicrm_case_activity ac
WHERE  a.is_deleted = 0
AND    a.activity_type_id IN ( $activityTypeIDs )
AND    c.id = ac.case_id
AND    a.id = ac.activity_id
AND    ac.case_id = %1
";

    $params = [1 => [$caseID, 'Integer']];
    $dao = CRM_Core_DAO::executeQuery($query, $params);
    while ($dao->fetch()) {
      $activityTypeInfo = $map[$dao->activity_type_id];
      $activities[] = $this->getActivity($clientID,
        $dao,
        $activityTypeInfo
      );
    }
  }

  /**
   * @param int $clientID
   * @param int $activityID
   * @param bool $anyActivity
   * @param int $redact
   *
   * @return mixed
   */
  public function &getActivityInfo($clientID, $activityID, $anyActivity = FALSE, $redact = 0) {
    if ($redact) {
      $this->_isRedact = 1;
      $this->getRedactionRules();
    }

    $index = $activityID . '_' . (int) $anyActivity;

    if ($clientID) {
      $index .= '_' . $clientID;
    }

    if (!array_key_exists($index, \Civi::$statics[__CLASS__][__FUNCTION__]['activityInfos'] ?? [])) {
      \Civi::$statics[__CLASS__][__FUNCTION__]['activityInfos'][$index] = [];
      $selectCaseActivity = "";
      $joinCaseActivity = "";

      if ($clientID) {
        $selectCaseActivity = ", ca.case_id as caseID ";
        $joinCaseActivity = " INNER JOIN civicrm_case_activity ca ON a.id = ca.activity_id ";
      }

      $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
      $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
      $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);

      $query = "
SELECT     a.*, aa.contact_id as assigneeID, at.contact_id as targetID
{$selectCaseActivity}
FROM       civicrm_activity a
{$joinCaseActivity}
LEFT JOIN civicrm_activity_contact at ON a.id = at.activity_id AND at.record_type_id = $targetID
LEFT JOIN civicrm_activity_contact aa ON a.id = aa.activity_id AND aa.record_type_id = $assigneeID
WHERE      a.id = %1
    ";
      $params = [1 => [$activityID, 'Integer']];
      $dao = CRM_Core_DAO::executeQuery($query, $params);

      if ($dao->fetch()) {
        //if activity type is email get info of all activities.
        if ($dao->activity_type_id == CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', 'Email')) {
          $anyActivity = TRUE;
        }
        $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, $anyActivity);
        $activityTypeInfo = NULL;

        if (isset($activityTypes[$dao->activity_type_id])) {
          $activityTypeInfo = $activityTypes[$dao->activity_type_id];
        }
        if ($activityTypeInfo) {
          \Civi::$statics[__CLASS__][__FUNCTION__]['activityInfos'][$index] = $this->getActivity($clientID, $dao, $activityTypeInfo);
        }
      }
    }

    return \Civi::$statics[__CLASS__][__FUNCTION__]['activityInfos'][$index];
  }

  /**
   * @param int $clientID
   * @param $activityDAO
   * @param $activityTypeInfo
   *
   * @return array
   */
  public function &getActivity($clientID, $activityDAO, &$activityTypeInfo) {
    if (empty($this->_redactionStringRules)) {
      $this->_redactionStringRules = [];
    }

    $activity = [];
    $activity['fields'] = [];
    if ($clientID) {
      $clientID = CRM_Utils_Type::escape($clientID, 'Integer');
      if (!in_array($activityTypeInfo['name'], ['Email', 'Inbound Email'])) {
        $activity['editURL'] = CRM_Utils_System::url('civicrm/case/activity',
          "reset=1&cid={$clientID}&caseid={$activityDAO->caseID}&action=update&atype={$activityDAO->activity_type_id}&id={$activityDAO->id}"
        );
      }
      else {
        $activity['editURL'] = '';
      }

      $client = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $clientID, 'display_name');
      // add Client SortName as well as Display to the strings to be redacted across the case session
      // suffixed with a randomly generated 4-digit number
      if (!array_key_exists($client, $this->_redactionStringRules)) {
        $this->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($this->_redactionStringRules,
          [$client => 'name_' . rand(10000, 100000)]
        );

        $clientSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $clientID, 'sort_name');
        if (!array_key_exists($clientSortName, $this->_redactionStringRules)) {
          $this->_redactionStringRules[$clientSortName] = $this->_redactionStringRules[$client];
        }
      }

      $activity['fields'][] = [
        'name' => 'Client',
        'label' => ts('Client'),
        'value' => $this->redact($client),
        'type' => 'String',
      ];
    }

    $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
    $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
    $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
    if (!empty($activityDAO->targetID)) {
      // Re-lookup the target ID since the DAO only has the first recipient if there are multiple.
      // Maybe not the best solution.
      $targetNames = CRM_Activity_BAO_ActivityContact::getNames($activityDAO->id, $targetID);
      $processTarget = FALSE;
      $name = 'With Contact(s)';
      $label = ts('With Contact(s)');
      if (in_array($activityTypeInfo['name'], ['Email', 'Inbound Email'])) {
        $processTarget = TRUE;
        $name = 'Recipient';
        $label = ts('Recipient');
      }
      if (!$processTarget) {
        foreach ($targetNames as $targetID => $targetName) {
          if ($targetID != $clientID) {
            $processTarget = TRUE;
            break;
          }
        }
      }

      if ($processTarget) {
        $targetRedacted = [];
        foreach ($targetNames as $targetID => $target) {
          // add Recipient SortName as well as Display to the strings to be redacted across the case session
          // suffixed with a randomly generated 4-digit number
          if (!array_key_exists($target, $this->_redactionStringRules)) {
            $this->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($this->_redactionStringRules,
              [$target => 'name_' . rand(10000, 100000)]
            );
            $targetSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $targetID, 'sort_name');
            if (!array_key_exists($targetSortName, $this->_redactionStringRules)) {
              $this->_redactionStringRules[$targetSortName] = $this->_redactionStringRules[$target];
            }
          }
          $targetRedacted[] = $this->redact($target);
        }

        $activity['fields'][] = [
          'name' => $name,
          'label' => $label,
          'value' => implode('; ', $targetRedacted),
          'type' => 'String',
        ];
      }
    }

    // Activity Type info is a special field
    $activity['fields'][] = [
      'name' => 'Activity Type',
      'label' => ts('Activity Type'),
      'value' => $activityTypeInfo['label'],
      'type' => 'String',
    ];

    $activity['fields'][] = [
      'name' => 'Subject',
      'label' => ts('Subject'),
      // TODO: Why is this being escaped at this point in the flow? Should
      // this just be done in the tpl where all the other fields get escaped?
      // Is anything depending on this currently or is it just a result of
      // the see-sawing and some double-escaping that went back and forth
      // for a few years?
      'value' => htmlspecialchars($this->redact($activityDAO->subject) ?? ''),
      'type' => 'Memo',
    ];

    $creator = $this->getCreatedBy($activityDAO->id);
    // add Creator to the strings to be redacted across the case session
    if (!array_key_exists($creator, $this->_redactionStringRules)) {
      $this->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($this->_redactionStringRules,
        [$creator => 'name_' . rand(10000, 100000)]
      );
    }
    $activity['fields'][] = [
      'name' => 'Created By',
      'label' => ts('Created By'),
      'value' => $this->redact($creator),
      'type' => 'String',
    ];
    $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
    $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
    $source_contact_id = CRM_Activity_BAO_Activity::getActivityContact($activityDAO->id, $sourceID);
    $reporter = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
      $source_contact_id,
      'display_name'
    );

    // add Reporter SortName as well as Display to the strings to be redacted across the case session
    // suffixed with a randomly generated 4-digit number
    if (!array_key_exists($reporter, $this->_redactionStringRules)) {
      $this->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($this->_redactionStringRules,
        [$reporter => 'name_' . rand(10000, 100000)]
      );

      $reporterSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
        $source_contact_id,
        'sort_name'
      );
      if (!array_key_exists($reporterSortName, $this->_redactionStringRules)) {
        $this->_redactionStringRules[$reporterSortName] = $this->_redactionStringRules[$reporter];
      }
    }

    $activity['fields'][] = [
      'name' => 'Reported By',
      'label' => ts('Reported By'),
      'value' => $this->redact($reporter),
      'type' => 'String',
    ];

    if (!empty($activityDAO->assigneeID)) {
      //allow multiple assignee contacts.CRM-4503.
      $assignee_contact_names = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames([$activityDAO->id], TRUE);

      foreach ($assignee_contact_names as & $assignee) {
        // add Assignee to the strings to be redacted across the case session
        $this->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($this->_redactionStringRules,
          [$assignee => 'name_' . rand(10000, 100000)]
        );
        $assignee = $this->redact($assignee);
      }
      $assigneeContacts = implode(', ', $assignee_contact_names);
      $activity['fields'][] = [
        'name' => 'Assigned to',
        'label' => ts('Assigned to'),
        'value' => $assigneeContacts,
        'type' => 'String',
      ];
    }

    if ($activityDAO->medium_id) {
      $activity['fields'][] = [
        'name' => 'Medium',
        'label' => ts('Medium'),
        'value' => CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'medium_id', $activityDAO->medium_id),
        'type' => 'String',
      ];
    }

    $activity['fields'][] = [
      'name' => 'Location',
      'label' => ts('Location'),
      'value' => $activityDAO->location,
      'type' => 'String',
    ];

    $activity['fields'][] = [
      'name' => 'Date and Time',
      'label' => ts('Date and Time'),
      'value' => $activityDAO->activity_date_time,
      'type' => 'Date',
    ];

    $activity['fields'][] = [
      'name' => 'Details',
      'label' => ts('Details'),
      'value' => $this->redact(CRM_Utils_String::purifyHTML(CRM_Utils_String::stripAlternatives($activityDAO->details))),
      'type' => 'Memo',
    ];

    // Skip Duration field if empty (to avoid " minutes" output). Might want to do this for all fields at some point. dgg
    if ($activityDAO->duration) {
      $activity['fields'][] = [
        'name' => 'Duration',
        'label' => ts('Duration'),
        'value' => $activityDAO->duration . ' ' . ts('minutes'),
        'type' => 'Int',
      ];
    }
    $activity['fields'][] = [
      'name' => 'Status',
      'label' => ts('Status'),
      'value' => CRM_Core_PseudoConstant::getLabel('CRM_Activity_DAO_Activity', 'activity_status_id',
        $activityDAO->status_id
      ),
      'type' => 'String',
    ];

    $activity['fields'][] = [
      'name' => 'Priority',
      'label' => ts('Priority'),
      'value' => CRM_Core_PseudoConstant::getLabel('CRM_Activity_DAO_Activity', 'priority_id',
        $activityDAO->priority_id
      ),
      'type' => 'String',
    ];

    //for now empty custom groups
    $activity['customGroups'] = $this->getCustomData($clientID,
      $activityDAO,
      $activityTypeInfo
    );

    return $activity;
  }

  /**
   * @param int $clientID
   * @param $activityDAO
   * @param $activityTypeInfo
   *
   * @return array|null
   */
  public function getCustomData($clientID, $activityDAO, &$activityTypeInfo) {
    list($typeValues, $options, $sql) = $this->getActivityTypeCustomSQL($activityTypeInfo['id'], '%Y-%m-%d');

    $params = [1 => [$activityDAO->id, 'Integer']];

    $customGroups = [];
    foreach ($sql as $tableName => $sqlClause) {
      $dao = CRM_Core_DAO::executeQuery($sqlClause, $params);
      if ($dao->fetch()) {
        $customGroup = [];
        foreach ($typeValues[$tableName] as $columnName => $typeValue) {

          if (($typeValue['type'] ?? NULL) == 'Date') {
            $value = $dao->$columnName;
          }
          else {
            $value = CRM_Core_BAO_CustomField::displayValue($dao->$columnName, $typeValue['fieldID'], $activityDAO->id);
          }

          if ($value) {
            // Note: this is already taken care in getDisplayValue above, but sometimes
            // strings like '^A^A' creates problem. So to fix this special case -
            if (str_contains($value, CRM_Core_DAO::VALUE_SEPARATOR)) {
              $value = trim($value, CRM_Core_DAO::VALUE_SEPARATOR);
            }
            if (($typeValue['type'] ?? NULL) == 'String' ||
              ($typeValue['type'] ?? NULL) == 'Memo'
            ) {
              $value = $this->redact($value);
            }
          }
          //$typeValue
          $customGroup[] = [
            'label' => $typeValue['label'],
            'value' => $value,
            'type' => $typeValue['type'],
            'fieldID' => $typeValue['fieldID'],
          ];
        }
        $customGroups[$dao->groupTitle] = $customGroup;
      }
    }

    return empty($customGroups) ? NULL : $customGroups;
  }

  /**
   * @param int $activityTypeID
   * @param string|null $dateFormat
   * @param bool $onlyActive
   *
   * @return mixed
   */
  public function getActivityTypeCustomSQL($activityTypeID, $dateFormat = NULL, $onlyActive = TRUE) {
    static $cache = [];

    if (is_null($activityTypeID)) {
      $activityTypeID = 0;
    }

    if (!isset($cache[$activityTypeID])) {
      $query = "
SELECT cg.title           as groupTitle,
       cg.table_name      as tableName ,
       cf.column_name     as columnName,
       cf.label           as label     ,
       cg.id              as groupID   ,
       cf.id              as fieldID   ,
       cf.data_type       as dataType  ,
       cf.html_type       as htmlType  ,
       cf.option_group_id as optionGroupID
FROM   civicrm_custom_group cg,
       civicrm_custom_field cf
WHERE  cf.custom_group_id = cg.id
AND    cg.extends = 'Activity'
AND " . CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW, 'cg.');

      if ($onlyActive) {
        $query .= " AND cf.is_active = 1 ";
      }
      if ($activityTypeID) {
        $query .= "AND ( cg.extends_entity_column_value IS NULL OR cg.extends_entity_column_value LIKE '%" . CRM_Core_DAO::VALUE_SEPARATOR . "%1" . CRM_Core_DAO::VALUE_SEPARATOR . "%' )";
      }
      else {
        $query .= "AND cg.extends_entity_column_value IS NULL";
      }
      $query .= "ORDER BY cg.weight, cf.weight";
      $params = [
        1 => [
          $activityTypeID,
          'Integer',
        ],
      ];
      $dao = CRM_Core_DAO::executeQuery($query, $params);

      $result = $options = $sql = $groupTitle = [];
      while ($dao->fetch()) {
        if (!array_key_exists($dao->tableName, $result)) {
          $result[$dao->tableName] = [];
          $sql[$dao->tableName] = [];
        }
        $result[$dao->tableName][$dao->columnName] = [
          'label' => $dao->label,
          'type' => $dao->dataType,
          'fieldID' => $dao->fieldID,
        ];

        $options[$dao->fieldID] = [];
        $options[$dao->fieldID]['attributes'] = [
          'label' => $dao->label,
          'data_type' => $dao->dataType,
          'html_type' => $dao->htmlType,
        ];
        // since we want to add ISO date format.
        if ($dateFormat && $dao->htmlType == 'Select Date') {
          $options[$dao->fieldID]['attributes']['format'] = $dateFormat;
        }
        if ($dao->optionGroupID) {
          $query = "
SELECT label, value
  FROM civicrm_option_value
 WHERE option_group_id = %1
";

          $option = CRM_Core_DAO::executeQuery($query, [1 => [$dao->optionGroupID, 'Positive']]);
          while ($option->fetch()) {
            $dataType = $dao->dataType;
            if ($dataType == 'Int' || $dataType == 'Float') {
              $num = round($option->value, 2);
              $options[$dao->fieldID]["$num"] = $option->label;
            }
            else {
              $options[$dao->fieldID][$option->value] = $option->label;
            }
          }
        }

        $sql[$dao->tableName][] = $dao->columnName;
        $groupTitle[$dao->tableName] = $dao->groupTitle;
      }

      foreach ($sql as $tableName => $values) {
        $columnNames = implode(',', $values);
        $title = CRM_Core_DAO::escapeString($groupTitle[$tableName]);
        $mysqlTableName = CRM_Utils_Type::escape($tableName, 'MysqlColumnNameOrAlias');
        $sql[$tableName] = "
SELECT '" . $title . "' as groupTitle, $columnNames
FROM   $mysqlTableName
WHERE  entity_id = %1
";
      }

      $cache[$activityTypeID] = [$result, $options, $sql];
    }
    return $cache[$activityTypeID];
  }

  /**
   * @param int $activityID
   *
   * @return null|string
   */
  public function getCreatedBy($activityID) {
    $query = "
SELECT c.display_name
FROM   civicrm_contact c,
       civicrm_log     l
WHERE  l.entity_table = 'civicrm_activity'
AND    l.entity_id    = %1
AND    l.modified_id  = c.id
LIMIT  1
";

    $params = [1 => [$activityID, 'Integer']];
    return CRM_Core_DAO::singleValueQuery($query, $params);
  }

  /**
   * @param $string
   * @param bool $printReport
   * @param array $replaceString
   *
   * @return mixed
   */
  private function redact($string, $printReport = FALSE, $replaceString = []) {
    if ($printReport) {
      return CRM_Utils_String::redaction($string, $replaceString);
    }
    elseif ($this->_isRedact) {
      $regexToReplaceString = CRM_Utils_String::regex($string, $this->_redactionRegexRules);
      return CRM_Utils_String::redaction($string, array_merge($this->_redactionStringRules, $regexToReplaceString));
    }
    return $string;
  }

  /**
   * @param int $clientID
   * @param int $caseID
   * @param string $activitySetName
   * @param array $params
   * @param CRM_Core_Form $form
   *
   * @return mixed
   */
  public static function getCaseReport($clientID, $caseID, $activitySetName, $params, $form) {

    $template = self::populateCaseReportTemplate($clientID, $caseID, $activitySetName, $params, $form);

    // now run the template
    $contents = $template->fetch('CRM/Case/XMLProcessor/Report.tpl');
    return $contents;
  }

  /**
   * @param int $clientID
   * @param int $caseID
   * @param string $activitySetName
   * @param array $params
   * @param CRM_Case_XMLProcessor_Report $form
   *
   * @return CRM_Core_Smarty
   */
  public static function populateCaseReportTemplate($clientID, $caseID, $activitySetName, $params, $form) {

    $template = CRM_Core_Smarty::singleton();

    $template->assign('caseId', $caseID);
    $template->assign('clientID', $clientID);
    $template->assign('activitySetName', $activitySetName);

    if (!empty($params['is_redact'])) {
      $form->_isRedact = TRUE;
      $template->assign('_isRedact', 'true');
    }
    else {
      $form->_isRedact = FALSE;
      $template->assign('_isRedact', 'false');
    }

    // first get all case information
    $case = $form->caseInfo($clientID, $caseID);
    $template->assign('case', $case);

    if (($params['include_activities'] ?? NULL) == 1) {
      $template->assign('includeActivities', 'All');
    }
    else {
      $template->assign('includeActivities', 'Missing activities only');
    }

    $xml = $form->retrieve($case['caseTypeName']);

    $activitySetNames = CRM_Case_XMLProcessor_Process::activitySets($xml->ActivitySets);
    $pageTitle = $activitySetNames[$activitySetName] ?? NULL;
    $template->assign('pageTitle', $pageTitle);

    if ($activitySetName) {
      $activityTypes = $form->getActivityTypes($xml, $activitySetName);
    }
    else {
      $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
    }

    if (!$activityTypes) {
      return FALSE;
    }

    // next get activity set Information
    $activitySet = [
      'label' => $form->getActivitySetLabel($xml, $activitySetName),
      'includeActivities' => 'All',
      'redact' => 'false',
    ];
    $template->assign('activitySet', $activitySet);

    //now collect all the information about activities
    $activities = [];
    $form->getActivities($clientID, $caseID, $activityTypes, $activities);
    $template->assign('activities', $activities);

    return $template;
  }

  public static function printCaseReport() {
    $caseID = CRM_Utils_Request::retrieve('caseID', 'Positive');
    $clientID = CRM_Utils_Request::retrieve('cid', 'Positive');
    $activitySetName = CRM_Utils_Request::retrieve('asn', 'String');
    $isRedact = CRM_Utils_Request::retrieve('redact', 'Boolean');
    $includeActivities = CRM_Utils_Request::retrieve('all', 'Positive');
    $params = $otherRelationships = $globalGroupInfo = [];
    $report = new CRM_Case_XMLProcessor_Report($isRedact);
    if ($includeActivities) {
      $params['include_activities'] = 1;
    }

    if ($isRedact) {
      $params['is_redact'] = 1;
      $report->_redactionStringRules = [];
    }
    $template = CRM_Core_Smarty::singleton();

    //get case related relationships (Case Role)
    $caseRelationships = CRM_Case_BAO_Case::getCaseRoles($clientID, $caseID);
    $caseType = CRM_Case_BAO_Case::getCaseType($caseID, 'name');

    $xmlProcessor = new CRM_Case_XMLProcessor_Process();
    $caseRoles = $xmlProcessor->get($caseType, 'CaseRoles');
    foreach ($caseRelationships as $key => & $value) {
      if (!empty($caseRoles[$value['relation_type'] . '_' . $value['relationship_direction']])) {
        unset($caseRoles[$value['relation_type'] . '_' . $value['relationship_direction']]);
      }
      if ($isRedact) {
        if (!array_key_exists($value['name'], $report->_redactionStringRules)) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$value['name'] => 'name_' . rand(10000, 100000)]
          );
        }
        $value['name'] = $report->redact($value['name'], TRUE, $report->_redactionStringRules);
        if (!empty($value['email']) &&
          !array_key_exists($value['email'], $report->_redactionStringRules)
        ) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$value['email'] => 'email_' . rand(10000, 100000)]
          );
        }

        $value['email'] = $report->redact($value['email'], TRUE, $report->_redactionStringRules);

        if (!empty($value['phone']) &&
          !array_key_exists($value['phone'], $report->_redactionStringRules)
        ) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$value['phone'] => 'phone_' . rand(10000, 100000)]
          );
        }
        $value['phone'] = $report->redact($value['phone'], TRUE, $report->_redactionStringRules);
      }
    }

    $caseRoles['client'] = CRM_Case_BAO_Case::getContactNames($caseID);
    if ($isRedact) {
      foreach ($caseRoles['client'] as &$client) {
        if (!array_key_exists($client['sort_name'] ?? NULL, $report->_redactionStringRules)) {

          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [($client['sort_name'] ?? NULL) => 'name_' . rand(10000, 100000)]
          );
        }
        if (!array_key_exists($client['display_name'] ?? NULL, $report->_redactionStringRules)) {
          $report->_redactionStringRules[$client['display_name'] ?? NULL] = $report->_redactionStringRules[$client['sort_name'] ?? NULL];
        }
        $client['sort_name'] = $report->redact($client['sort_name'] ?? NULL, TRUE, $report->_redactionStringRules);
        if (!empty($client['email']) &&
          !array_key_exists($client['email'], $report->_redactionStringRules)
        ) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$client['email'] => 'email_' . rand(10000, 100000)]
          );
        }
        $client['email'] = $report->redact($client['email'] ?? NULL, TRUE, $report->_redactionStringRules);

        if (!empty($client['phone']) &&
          !array_key_exists($client['phone'], $report->_redactionStringRules)
        ) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$client['phone'] => 'phone_' . rand(10000, 100000)]
          );
        }
        $client['phone'] = $report->redact($client['phone'] ?? NULL, TRUE, $report->_redactionStringRules);
      }
    }
    // Retrieve ALL client relationships
    $relClient = CRM_Contact_BAO_Relationship::getRelationship($clientID,
      CRM_Contact_BAO_Relationship::CURRENT,
      0, 0, 0, NULL, NULL, FALSE
    );
    foreach ($relClient as $r) {
      if ($isRedact) {
        if (!array_key_exists($r['name'], $report->_redactionStringRules)) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$r['name'] => 'name_' . rand(10000, 100000)]
          );
        }
        if (!array_key_exists($r['display_name'], $report->_redactionStringRules)) {
          $report->_redactionStringRules[$r['display_name']] = $report->_redactionStringRules[$r['name']];
        }
        $r['name'] = $report->redact($r['name'], TRUE, $report->_redactionStringRules);

        if (!empty($r['phone']) &&
          !array_key_exists($r['phone'], $report->_redactionStringRules)
        ) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$r['phone'] => 'phone_' . rand(10000, 100000)]
          );
        }
        $r['phone'] = $report->redact($r['phone'], TRUE, $report->_redactionStringRules);

        if (!empty($r['email']) &&
          !array_key_exists($r['email'], $report->_redactionStringRules)
        ) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$r['email'] => 'email_' . rand(10000, 100000)]
          );
        }
        $r['email'] = $report->redact($r['email'], TRUE, $report->_redactionStringRules);
      }
      if (!array_key_exists($r['id'], $caseRelationships)) {
        $otherRelationships[] = $r;
      }
    }

    // Now global contact list that appears on all cases.
    $relGlobal = CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo);
    foreach ($relGlobal as & $r) {
      if ($isRedact) {
        if (!array_key_exists($r['sort_name'], $report->_redactionStringRules)) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$r['sort_name'] => 'name_' . rand(10000, 100000)]
          );
        }
        if (!array_key_exists($r['display_name'], $report->_redactionStringRules)) {
          $report->_redactionStringRules[$r['display_name']] = $report->_redactionStringRules[$r['sort_name']];
        }

        $r['sort_name'] = $report->redact($r['sort_name'], TRUE, $report->_redactionStringRules);
        if (!empty($r['phone']) &&
          !array_key_exists($r['phone'], $report->_redactionStringRules)
        ) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$r['phone'] => 'phone_' . rand(10000, 100000)]
          );
        }
        $r['phone'] = $report->redact($r['phone'], TRUE, $report->_redactionStringRules);

        if (!empty($r['email']) &&
          !array_key_exists($r['email'], $report->_redactionStringRules)
        ) {
          $report->_redactionStringRules = CRM_Utils_Array::crmArrayMerge($report->_redactionStringRules,
            [$r['email'] => 'email_' . rand(10000, 100000)]
          );
        }
        $r['email'] = $report->redact($r['email'], TRUE, $report->_redactionStringRules);
      }
    }

    // Retrieve custom values for cases.
    $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($caseID, 'Case');
    $groupTree = CRM_Core_BAO_CustomGroup::getAll(['extends' => ['Case'], 'is_active' => TRUE]);
    $caseCustomFields = [];
    foreach ($groupTree as $gid => $group_values) {
      foreach ($group_values['fields'] as $id => $field_values) {
        if (array_key_exists($id, $customValues)) {
          $caseCustomFields[$gid]['title'] = $group_values['title'];
          $caseCustomFields[$gid]['values'][$id] = [
            'label' => $field_values['label'],
            'value' => $customValues[$id],
          ];
        }
      }
    }
    $template->assign('caseRelationships', $caseRelationships);
    $template->assign('caseRoles', $caseRoles);
    $template->assign('otherRelationships', $otherRelationships);
    $template->assign('globalRelationships', $relGlobal);
    $template->assign('globalGroupInfo', $globalGroupInfo);
    $template->assign('caseCustomFields', $caseCustomFields);
    $contents = self::getCaseReport($clientID,
      $caseID,
      $activitySetName,
      $params,
      $report
    );
    $printReport = CRM_Case_Audit_Audit::run($contents, $clientID, $caseID);
    echo $printReport;
    CRM_Utils_System::civiExit();
  }

}
