<?php
use CRM_Dataprocessor_ExtensionUtil as E;

/**
 * Collection of upgrade steps.
 */
class CRM_Dataprocessor_Upgrader extends CRM_Dataprocessor_Upgrader_Base {

  public function install() {

  }

  public function uninstall() {
    // Remove output from menu
    $dao = CRM_Core_DAO::executeQuery("SELECT configuration FROM civicrm_data_processor_output");
    while ($dao->fetch()) {
      $configuration = json_decode($dao->configuration, TRUE);
      if (isset($configuration['navigation_id']) && $configuration['navigation_id']) {
        $navId = $configuration['navigation_id'];
        \CRM_Core_BAO_Navigation::processDelete($navId);
      }
    }
    \CRM_Core_BAO_Navigation::resetNavigation();
  }

  /**
   * Upgrade after refactor of Aggregation functionality.
   *
   * @return bool
   */
  public function upgrade_1001() {
    CRM_Dataprocessor_Upgrader_Version_1_1_0::upgradeAggregationFields();
    CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_data_processor` DROP `aggregation`;");
    return TRUE;
  }

  /**
   * Rename field type calculations_percentage to calculations_percentage_change
   *
   * @return bool
   */
  public function upgrade_1002() {
    CRM_Core_DAO::executeQuery("UPDATE `civicrm_data_processor_field` SET `type`='calculations_percentage_change' WHERE `type` = 'calculations_percentage';");
    return TRUE;
  }

  public function upgrade_1003() {
    CRM_Core_DAO::executeQuery("
      CREATE TABLE `civicrm_data_processor_filter_collection` (
        `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'Unique DataProcessorFilterCollection ID',
        `data_processor_id` int unsigned NOT NULL COMMENT 'FK to Data Processor',
        `weight` int NULL,
        `name` varchar(255) NULL,
        `title` varchar(255) NOT NULL,
        `description` text NULL,
        `condition` varchar(255) NULL DEFAULT 'AND',
        `link_condition` varchar(255) NULL DEFAULT 'AND',
        `show_collapsed` tinyint NOT NULL,
        PRIMARY KEY (`id`),
        CONSTRAINT FK_civicrm_data_processor_filter_collection_data_processor_id FOREIGN KEY (`data_processor_id`) REFERENCES `civicrm_data_processor`(`id`) ON DELETE CASCADE
      )
      ENGINE=InnoDB;
    ");
    CRM_Core_DAO::executeQuery("
        ALTER TABLE `civicrm_data_processor_filter`
        ADD COLUMN `collection_id` int unsigned;
    ");
    CRM_Core_DAO::executeQuery("
        ALTER TABLE `civicrm_data_processor_filter`
        ADD CONSTRAINT FK_civicrm_data_processor_filter_collection_id FOREIGN KEY (`collection_id`) REFERENCES `civicrm_data_processor_filter_collection`(`id`) ON DELETE SET NULL;
    ");
    return TRUE;
  }

  /**
   * Look up extension dependency error messages and display as Core Session Status
   *
   * @param array $unmet
   */
  public static function displayDependencyErrors(array $unmet){
    foreach ($unmet as $ext) {
      $message = self::getUnmetDependencyErrorMessage($ext);
      CRM_Core_Session::setStatus($message, E::ts('Prerequisite check failed.'), 'error');
    }
  }

  /**
   * Mapping of extensions names to localized dependency error messages
   *
   * @param string $unmet an extension name
   */
  public static function getUnmetDependencyErrorMessage($unmet) {
    switch ($unmet) {
      case 'legacycustomsearches':
        return ts('Dataprocessor was installed successfully, but you must also install and enable the <strong>legacycustomsearches</strong> extension.');
    }

    CRM_Core_Error::fatal(ts('Unknown error key: %1', array(1 => $unmet)));
  }

  /**
   * Extension Dependency Check
   *
   * @return Array of names of unmet extension dependencies; NOTE: returns an
   *         empty array when all dependencies are met.
   */
  public static function checkExtensionDependencies() {
    $version = \CRM_Core_BAO_Domain::version();
    $unmet = [];
    if (version_compare($version, '5.41', '>=')) {
      $unmet[] = 'legacycustomsearches';
    }
    $extensions = civicrm_api3('Extension', 'get', array('options' => array('limit' => 0)));
    foreach($extensions['values'] as $ext) {
      if ($ext['key'] == 'legacycustomsearches' && $ext['status'] == 'installed') {
        unset($unmet[array_search('action-provider', $unmet)]);
      }
    }
    return $unmet;
  }

}
