<?php
/*
Plugin Name: Create Record Here
Description: Allow users to choose where new records should be inserted in manually sorted record lists.
Version: 1.02m
Requires at least: 3.10
*/

$GLOBALS['CRH_LINK_NAME'] = 'create record here';  // the link name


// DON'T UPDATE ANYTHING BELOW THIS LINE

addFilter('listRow_actionLinks',  'crh_addLink',           null, 3);
addFilter('record_saved_message', 'crh_updateRecordOrder', null, 3);


// add "create record here" link
function crh_addLink($actionLinks, $tableName, $record) {
  global $schema;

  if (!@$schema['dragSortOrder']) { return $actionLinks; } // skip sections without dragSortOrder field
  if (@$schema['_disableAdd'] === '1') { return $actionLinks; } // skip sections with add disabled

  // get new sort order
  $isDesc        = preg_match("/dragSortOrder\s+DESC/i", @$schema['listPageOrder']);
  $newSortOrder  = abs($record['dragSortOrder'] + ($isDesc ? -1 : 1));

  // create link
  $addLink       = "?menu=$tableName&amp;action=add&amp;dragSortOrder=$newSortOrder";
  $actionLinks  .= "<br/><a href='$addLink'>{$GLOBALS['CRH_LINK_NAME']}</a>";

  //
  return $actionLinks;
}


// update record order so there is space between order values for new records to be inserted
// Note: The only reason we're using a filter for this is because there is no hook available
function crh_updateRecordOrder($message, $tableName, $recordNum) {
  global $schema;
  if (!@$schema['dragSortOrder']) { return $message; } // skip sections without dragSortOrder field

  // re-order records
  $tableNameWithPrefix = getTableNameWithPrefix($tableName);
  $query1 = "SET @count = 0";
  $query2 = "UPDATE `$tableNameWithPrefix` SET `dragSortOrder` = (SELECT @count := @count + 10) ORDER BY dragSortOrder";
  mysqli()->query($query1) or die("MySQL Error: ". htmlencode(mysqli()->error) . "\n");
  mysqli()->query($query2) or die("MySQL Error: ". htmlencode(mysqli()->error) . "\n");

  //
  return $message;
}

// eof
