<?php
/*
Plugin Name: List Field Jump
Description: Adds a link to CMS list fields which link to other records
Version: 1.00
Requires at least: 3.65
Required System Plugin: Yes
*/

$GLOBALS['LISTFIELDJUMP_SHOW_ON_LIST_PAGE'] = true;

/* The $GLOBALS['ADVANCED_MYSQL_FIELDS'] variable can be used to allow list fields
 * that use the "Get options from MySQL query (advanced)" to provide links to the
 * related table as well.
 *
 * The format should be edit_table_name => edit_field_name = goto_table. Here are some
 * examples of how you might use it:
 *
 * $GLOBALS['ADVANCED_MYSQL_FIELDS']['edit_table_name']['edit_field_name']  = 'goto_table';

 * I have a cars section with an advanced MySQL drop down list that has the following MySQL: "SELECT num, title  FROM `<?php echo $TABLE_PREFIX ?>brands`"
 * $GLOBALS['ADVANCED_MYSQL_FIELDS']['cars']['brand']  = 'brands';
 *
 */
$GLOBALS['ADVANCED_MYSQL_FIELDS']  = array();

function _listFieldJump_isValidListField($fieldSchema): bool {
  $isListField = @$fieldSchema['type'] === 'list';
  $isPulldown  = @$fieldSchema['listType'] === 'pulldown';
  $isTableLink = @$fieldSchema['optionsType'] === 'table' || @$fieldSchema['optionsType'] === 'query';
  $isNumValued = @$fieldSchema['optionsValueField'] === 'num' || @$GLOBALS['ADVANCED_MYSQL_FIELDS'][@$fieldSchema['_tableName']][@$fieldSchema['name']];
  return $isListField && $isPulldown && $isTableLink && $isNumValued;
}

//
addFilter('edit_show_field', 'listFieldJump_edit_show_field', null, 3);
function listFieldJump_edit_show_field($allowDefaultBehaviour, $fieldSchema, $record) {
  global $SETTINGS;
  if (!$allowDefaultBehaviour) { return $allowDefaultBehaviour; }
  
  if ( _listFieldJump_isValidListField($fieldSchema) ) {
    
    // get the appropriate table link.
    $linkTableName = @$fieldSchema['optionsTablename'] ? $fieldSchema['optionsTablename'] :  @$GLOBALS['ADVANCED_MYSQL_FIELDS'][@$fieldSchema['_tableName']][@$fieldSchema['name']];
    
    // build default list field ui - emulate try block from: edit_functions.php
    $name = $fieldSchema['name'];
    $active_schema = [$name => $fieldSchema];
    $fieldObj = Itools\CMSB\Fields\Factory::create($name, $active_schema, $record ?? []);
    $html = $fieldObj->getEditRow();

    // insert link after the </select>
    $editUrl = $SETTINGS['adminUrl'] . '?menu=' . $linkTableName . '&action=edit&num=';
    
    $onHover = "var selectedOption = $(this).parent().prev().find(':selected');
                if(selectedOption.val()){
                  var optionText = selectedOption.text();
                  $(this).attr('title', 'Go to \'' + optionText + '\' record');
                }";
    $link    = '<span class="input-group-addon" style="border-left: none; background: #fff">
                  <a onmouseover="'.$onHover.'" id="listFieldJump-' . htmlencode(@$fieldSchema['name']) . '" href="?dynamicURL" onclick="var num = $(this).parent().prev().val(); if (num) { window.open(\'' . htmlencode($editUrl) . '\' + num); } return false;">
                    <span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span>
                  </a>
                </span>';
    $html    = preg_replace('#(</select>)#', "\\1 $link", $html);
    
    echo $html;
    return false;
  }
  return $allowDefaultBehaviour;
}

if ($GLOBALS['LISTFIELDJUMP_SHOW_ON_LIST_PAGE']) {
  addFilter('listRow_displayValue', 'listFieldJump_listRow_displayValue', null, 4);
}
function listFieldJump_listRow_displayValue($displayValue, $tableName, $fieldname, $record) {
  global $SETTINGS, $schema;
  
  $fieldSchema = @$schema[$fieldname];
  if (_listFieldJump_isValidListField($fieldSchema) && $record[$fieldname]) {
    
      // get the appropriate table link.
      $linkTableName = @$fieldSchema['optionsTablename'] ? $fieldSchema['optionsTablename'] :  @$GLOBALS['ADVANCED_MYSQL_FIELDS'][@$fieldSchema['_tableName']][@$fieldSchema['name']];
    
      $editUrl = $SETTINGS['adminUrl'] . '?menu=' . $linkTableName . '&action=edit&num=' . $record[$fieldname];
    
      $displayValue .= ' <a href="' . $editUrl . '" target="_blank"><span class="small glyphicon glyphicon-share-alt" aria-hidden="true"></span></a>';
  }

  return $displayValue;
}
