<?php

require_once 'civicrm_admin_ui.civix.php';
use CRM_CivicrmAdminUi_ExtensionUtil as E;

/**
 * Implements hook_civicrm_config().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_config/
 */
function civicrm_admin_ui_civicrm_config(&$config) {
  _civicrm_admin_ui_civix_civicrm_config($config);
}

/**
 * Implements hook_civicrm_pageRun().
 */
function civicrm_admin_ui_civicrm_pageRun(&$page) {
  $pageName = get_class($page);
  if ($pageName == 'CRM_Mailing_Page_Report') {
    $smarty = CRM_Core_Smarty::singleton();
    $report = $smarty->getTemplateVars()['report'];
    foreach ($report['click_through'] as $key => &$val) {
      if (preg_match('/mid=(\d+).*uid=(\d+)/', $val['link'], $matches)) {
        $val['link_unique'] = CRM_Utils_System::url('civicrm/mailing/report/urltrack#/?mid=' . $matches[1] . '&uid=' . $matches[2]);
      }
    }
    $smarty->assign('report', $report);
    $smarty->assign('is_adminui_enabled', TRUE);
  }
  // Copied from CRM_Admin_Page_Job
  if ($pageName == 'CRM_Afform_Page_AfformBase' && $page->urlPath === ['civicrm', 'admin', 'job']) {
    // check if non-prod mode is enabled.
    if (CRM_Core_Config::environment() != 'Production') {
      CRM_Core_Session::setStatus(ts('Execution of scheduled jobs has been turned off by default since this is a non-production environment. You can override this for particular jobs by adding runInNonProductionEnvironment=TRUE as a parameter. Note: this will send emails if your <a %1>outbound email</a> is enabled.', [1 => 'href="' . CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1') . '"']), ts('Non-production Environment'), 'warning', ['expires' => 0]);
    }
    else {
      $cronError = Civi\Api4\System::check(FALSE)
        ->addWhere('name', '=', 'checkLastCron')
        ->addWhere('severity_id', '>', 1)
        ->setIncludeDisabled(TRUE)
        ->execute()
        ->first();
      if ($cronError) {
        CRM_Core_Session::setStatus($cronError['message'], $cronError['title'], 'alert', ['expires' => 0]);
      }
    }
  }
}

/**
 * Implements hook_civicrm_postProcess().
 */
function civicrm_admin_ui_civicrm_postProcess($className, $form) {
  // Alter core forms to redirect to the new AdminUI afform pages
  switch ($className) {
    case 'CRM_UF_Form_Group':
      if ($form->getAction() & CRM_Core_Action::ADD) {
        $redirect = "civicrm/admin/uf/group/field#/?uf_group_id=$form->_id";
      }
      else {
        $redirect = 'civicrm/admin/uf/group';
      }
      break;

    case 'CRM_UF_Form_Field':
      $buttonName = $form->controller->getButtonName();
      // Redirect to field list unless "Save and New" was clicked
      if ($buttonName != $form->getButtonName('next', 'new')) {
        $redirect = "civicrm/admin/uf/group/field#/?uf_group_id=$form->_gid";
      }
      break;
  }

  if (isset($redirect)) {
    $url = CRM_Utils_System::url($redirect, '', FALSE, NULL, FALSE);
    CRM_Core_Session::singleton()->replaceUserContext($url);
  }
}

/**
 * Implements hook_civicrm_post().
 */
function civicrm_admin_ui_civicrm_post($op, $entityName, $id, $object, $params) {
  // When editing custom fields, refresh the autogenerated search displays
  if ($entityName === 'CustomGroup' || $entityName === 'CustomField') {
    CRM_Core_ManagedEntities::singleton()->reconcile([E::LONG_NAME]);
  }
}

function civicrm_admin_ui_civicrm_managed(&$entities, $modules) {
  if ($modules && !in_array(E::LONG_NAME, $modules, TRUE)) {
    return;
  }

  $records = \Civi\Api4\Action\CustomGroup\GetSearchKit::getAllManaged();

  foreach ($records as $record) {
    $record['module'] = E::LONG_NAME;
    $entities[] = $record;
  }
}

function civicrm_admin_ui_civicrm_alterMenu(&$menuItems) {
  // For SavedSearch_Mailings_Browse
  unset($menuItems['civicrm/mailing/browse/scheduled'], $menuItems['civicrm/mailing/browse/unscheduled'], $menuItems['civicrm/mailing/browse/archived']);
}

function civicrm_admin_ui_civicrm_navigationMenu(&$navigationItems) {
  // For SavedSearch_Mailings_Browse
  _civicrm_admin_ui_alter_mailing_navigation($navigationItems);
}

function _civicrm_admin_ui_alter_mailing_navigation(&$navigationItems) {
  foreach ($navigationItems as &$navigationItem) {
    if (!empty($navigationItem['attributes']['url'])) {
      if (str_starts_with($navigationItem['attributes']['url'], 'civicrm/mailing/browse/scheduled')) {
        $navigationItem['attributes']['url'] = 'civicrm/mailing#?is_archived=0&status=Scheduled,Running,Complete,Paused,Canceled';
      }
      if (str_starts_with($navigationItem['attributes']['url'], 'civicrm/mailing/browse/unscheduled')) {
        $navigationItem['attributes']['url'] = 'civicrm/mailing/draft';
      }
      if (str_starts_with($navigationItem['attributes']['url'], 'civicrm/mailing/browse/archived')) {
        $navigationItem['attributes']['url'] = 'civicrm/mailing#?is_archived=1';
      }
    }
    if (!empty($navigationItem['child'])) {
      _civicrm_admin_ui_alter_mailing_navigation($navigationItem['child']);
    }
  }
}
