<?php
/*
Plugin Name: Edit Button Order
Description: Restores the previous button order on record edit pages (Cancel, Erase, Preview, Save)
Version: 1.01
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, listed by the label shown on the button.
// '*' is where any buttons not listed appear, e.g. ones added by other plugins.
$buttonOrder = ['Cancel', 'Erase', 'Preview', '*', '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;
    }

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

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

    return $adminUI_args;
}, 100);
