<?php
defined('ABSPATH') or die('Direct access not allowed');

class CodeEditor_MenuSort {
    public function __construct() {
        add_action('admin_menu', [$this, 'save_menu_order'], 999);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
    }

    public function enqueue_scripts($hook) {
        if (strpos($hook, 'code-editor') !== false || strpos($hook, 'code-editor-cloud') !== false || strpos($hook, 'code-editor-git') !== false) {
            wp_enqueue_script('jquery-ui-sortable');
            wp_enqueue_script('menu-sort-js', plugins_url('assets/js/menu-sort.js', dirname(__FILE__)), ['jquery', 'jquery-ui-sortable'], '1.0.0', true);
            wp_enqueue_style('menu-sort-css', plugins_url('assets/css/menu-sort.css', dirname(__FILE__)));
        }
    }

    public function save_menu_order() {
        $menu_order = get_option('code_editor_menu_order', []);
        
        global $menu;
        if (!empty($menu_order)) {
            $ordered_menu = [];
            foreach ($menu_order as $item) {
                foreach ($menu as $key => $value) {
                    if ($value[2] === $item) {
                        $ordered_menu[] = $value;
                        unset($menu[$key]);
                        break;
                    }
                }
            }
            $menu = array_merge($ordered_menu, $menu);
        }
    }
}

new CodeEditor_MenuSort();