<?php
$content = file_get_contents('admin.php');

$newJs = <<<'JS'
        function editRule(data) {
            document.getElementById('rule_id').value = data.id;
            document.getElementById('rule_name').value = data.name;
            document.getElementById('rule_profile_id').value = data.profile_id || "";
            document.getElementById('rule_status_id').value = data.status_id;
            document.getElementById('rule_priority').value = data.priority || 0;
            document.getElementById('rule_orb_op').value = data.orbital_count_op || "";
            document.getElementById('rule_orb_val').value = data.orbital_count_val !== null ? data.orbital_count_val : "";
            document.getElementById('rule_terr_op').value = data.terrestrial_count_op || "";
            document.getElementById('rule_terr_val').value = data.terrestrial_count_val !== null ? data.terrestrial_count_val : "";
            
            // Orbital Multi-select
            const orbFactions = (data.orbital_dominant_factions || "").split(',').filter(x => x);
            msAll('orb', false);
            if (orbFactions.length === 0) {
                document.getElementById('orb_any').checked = true;
            } else {
                document.getElementById('orb_any').checked = false;
                orbFactions.forEach(val => {
                    const cb = document.querySelector(`.orb-cb[value="${val}"]`);
                    if(cb) cb.checked = true;
                });
            }
            updateMSLabel('orb');

            // Ground Multi-select
            const terrFactions = (data.ground_dominant_factions || "").split(',').filter(x => x);
            msAll('terr', false);
            if (terrFactions.length === 0) {
                document.getElementById('terr_any').checked = true;
            } else {
                document.getElementById('terr_any').checked = false;
                terrFactions.forEach(val => {
                    const cb = document.querySelector(`.terr-cb[value="${val}"]`);
                    if(cb) cb.checked = true;
                });
            }
            updateMSLabel('terr');

            document.getElementById('rule_empty').checked = data.is_empty_case == 1;
            if(document.getElementById('rule_diff')) document.getElementById('rule_diff').checked = data.dominance_diff_required == 1;
            window.scrollTo(0,0);
        }

        function resetRuleForm() {
            document.getElementById('ruleForm').reset();
            document.getElementById('rule_id').value = 0;
            msAll('orb', false);
            msAll('terr', false);
        }
JS;

$content = preg_replace('/function editRule\(data\) \{.*?function resetRuleForm\(\)\{.*?\}/s', $newJs, $content);

file_put_contents('admin.php', $content);
echo "editRule and resetRuleForm updated.\n";

