<?php  // Plugin Menu Functions



// plugin menu - add code generator link
function permalink_pluginMenu_codeGeneratorLink() { redirectBrowserToURL('?menu=_codeGenerator&_generator=permalink_codeGenerator'); }

// plugin menu - add Permalinks DB link
function permalink_pluginMenu_permalinksMenuLink() { redirectBrowserToURL('?menu=_permalinks'); }

// plugin menu - add Update Tables
function permalink_pluginMenu_updateTable() {
  
  // prepare adminUI() placeholders
  $adminUI = [];
  // page title
  $adminUI['PAGE_TITLE'] = [
    t("Plugins")                    => '?menu=admin&action=plugins',
    t("Permalinks - Update Tables") => '?_pluginAction=permalink_pluginMenu_updateTable',
  ];
  
  // button
  $adminUI['BUTTONS'] = [
    [ 'name' => 'back_to_plugins', 'label' => 'Back to Plugins &gt;&gt;',  'onclick' => 'window.location="?menu=admin&action=plugins";', 'type' => 'button' ],
  ];
  
  // content
  $adminUI['CONTENT'] = ob_capture(function() {
  ?>
    <p>
      This section allows add permalinks to existing tables.  Select a table below:<br/>
      Note: Tables must have a <b><i>permalink</i></b> field to be processed (unsupported tables will be grayed out).
    </p>

    <p>
      <div class="form-group">
        <select name="table" id="table"  class="form-control">
          <option value="">&lt;select table&gt;</option>
          <?php foreach(getSchemaTables() as $tablename): ?>
            <?php if ($tablename == '_permalinks') { continue; } ?>
            <?php $schema = loadSchema($tablename); ?>
            <option <?php echo (!@$schema['permalink']) ? 'disabled="disabled"' : '' ?>><?php echo htmlencode($tablename) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php echo adminUI_button(['id' => 'button', 'type' => 'button', 'btn-type' => 'default', 'label' => t('Update')]); ?>
    </p>

    <p id="backupMessage"></p>      
    <p id="progress">&nbsp;</p>
    <p id="errors"></p>

    <script type="text/javascript"><!--
      function setProgressMessage(message) { $('#progress').html(message); }
      function disableForm() { $('#button').attr('disabled', 'disabled'); $('#table').attr('disabled', 'disabled'); }
      function enableForm()  { $('#button').removeAttr('disabled'); $('#table').removeAttr('disabled'); }
      $(document).ready(function(){
        $('#button').click(function() {
  
          var tablename = $('#table option:selected').val();
          if (tablename == '') { return alert("No table selected!"); }
  
          setProgressMessage("Processing of '" + tablename + "' starting...");
          disableForm();
          $('#errors').html('');
  
          var url = '?_pluginAction=_permalink_pluginMenu_updateTable_ajax&tablename=' + tablename + '&skip=';
          function permalinkTable(skip) {
            $.ajax({
              url: url + skip,
              error:  function(msg){ setProgressMessage("Error!"); alert("There was an error sending the request!"); enableForm(); },
              success: function(msg){
                var json;
                try {
                  json = $.parseJSON(msg);
                }
                catch(err) {}
                if (json) {
                  $('#backupMessage').append(json.backupMessage);
                  $('#errors').append(json.errors);
                  if (json.remaining < 1) {
                    setProgressMessage("Processing of '" + tablename + "' complete!");
                    enableForm();
                    return;
                  }
                  setProgressMessage("Processing '" + tablename + "': " + json.remaining + " records remaining...");
                  permalinkTable(json.skip);
                }
                else {
                  setProgressMessage("Error!");
                  alert("Error: " + msg);
                  enableForm();
                }
              }
            });
          }
  
          permalinkTable(0);
          return false;
        });
      });
    //--></script>

  <?php });
  // show content
  adminUI($adminUI);
  exit;
}

//
function _permalink_pluginMenu_updateTable_ajax() {

  //
  $tableName = @$_REQUEST['tablename'];
  $limit     = 100;                     // records to process at a time
  $skip      = @$_REQUEST['skip'];      // records we've already processed
  $schema    = loadSchema($tableName);

  // error checking
  if (!$tableName)            { die("No tablename specified!"); }
  if (!$schema)               { die("Couldn't load schema for '" .htmlencode($tableName). "'!"); }
  if (!@$schema['permalink']) { die("There is no 'permalink' field defined in schema '" .htmlencode($tableName). "'!"); }
  
  // backup table
  $backupMessage = ''; 
  if (!$skip) {
    $backupFilepath = backupDatabase('', $tableName);
    $backupMessage = "Saved backup as: $backupFilepath<br/>\n"; 
  } 
  
  //
  $result = _permalink_updateTable($tableName, $limit, $skip);
  print json_encode(array(
    'remaining' => $result['remaining'],
    'skip'      => $result['skip'],
    'errors'    => $result['errors'],
    'backupMessage' => $backupMessage,
  ));
  exit;
  
}


//
function _permalink_updateTable($tableName, $limit = null, $skip = 0) {
  global $TABLE_PREFIX;
  
  //
  $schema          = loadSchema($tableName);
  $permalinkPrefix = $schema['permalink']['defaultValue'];

  // load next batch of records to process
  $where     = "`permalink` = '' OR ISNULL(`permalink`)";
  $count     = mysql_count($tableName, $where);  // get count of records with no permalink
  $remaining = $count - $skip;
  
  $query     = "SELECT * FROM `{$TABLE_PREFIX}$tableName` WHERE $where";
  if ($limit) {
    $query .= " LIMIT " . intval($skip) . ", $limit";
  }
  $records   = mysql_select_query($query);

  // process records
  $errors    = '';
  foreach ($records as $record) {
    $recordLink = "<a href=\"?menu=$tableName&amp;action=edit&amp;num={$record['num']}\">Record #{$record['num']}</a>";

    // #1 - get permalink
    $permalink = permalink_generate($record, $permalinkPrefix);
    if (!$permalink) { $errors .= "$recordLink - couldn't determine permalink!<br/>\n"; $skip++; $remaining--; continue; }

    // #2 - add to permalinks DB
    $permalinkErrors = permalink_add($permalink, $tableName, $record['num']);  // add/update permalink
    if ($permalinkErrors) { $errors .= "$recordLink - $permalinkErrors<br/>\n"; }
    
    // #3 - update record
    if (!$permalinkErrors) { mysql_update($tableName, $record['num'], null, array('permalink' => $permalink)); }
    
    //
    $remaining--;
  }
  
  return array(
    'remaining'     => $remaining,
    'skip'          => $skip,
    'errors'        => $errors,
    'backupMessage' => ''
  );
}


// eof