<?php
/*
Plugin Name: Edit Button Order
Description: Restores the previous button order on record edit pages (Cancel, Erase, Preview, Save)
Version: 1.00
CMS Version Required: 3.83
*/

namespace EditButtonOrder;

use Itools\Cmsb\Plugin;

// Don't run from command-line (cron scripts can error when certain CGI env vars aren't set)
if (inCLI()) {
    return;
}

// Buttons appear left to right in the order below - rearrange as desired
// '*' is where buttons added by other plugins appear, e.g. "Save & Copy".
$buttonOrder = ['cancel', 'Erase', 'preview', '*', '_action=save'];

// Reorder edit-page buttons after other plugins have added theirs (priority 100, default is 10)
Plugin::on('adminUI_args', function ($adminUI_args, $tableName, $action) use ($buttonOrder) {
    if (!in_array($action, ['edit', 'add'], true) || empty($adminUI_args['BUTTONS'])) {
        return $adminUI_args;
    }

    $namePos     = array_flip($buttonOrder);  // button name => position
    $unlistedPos = $namePos['*'] ?? -1;       // '*' slot, or far left if '*' was removed
    $position    = fn($button) => $namePos[$button['name'] ?? ''] ?? $unlistedPos;

    usort($adminUI_args['BUTTONS'], fn($a, $b) => $position($a) <=> $position($b)); // stable sort: unlisted buttons keep their relative order

    return $adminUI_args;
}, 100);
