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

// 1. Add CSS
$css = <<<'EOD'

        /* Multi-select Dropdown */
        .multi-select-dropdown { position: relative; width: 100%; }
        .multi-select-btn { width: 100%; padding: 8px 10px; background: #0f172a; border: 1px solid #334155; border-radius: 4px; color: #eceff4; text-align: left; cursor: pointer; font-size: 13px; display: flex; justify-content: space-between; align-items: center; box-sizing: border-box; }
        .multi-select-menu { position: absolute; top: 100%; left: 0; right: 0; z-index: 1000; background: #1e293b; border: 1px solid #334155; border-radius: 4px; margin-top: 5px; display: none; max-height: 250px; overflow-y: auto; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); }
        .multi-select-menu.show { display: block; }
        .multi-select-header { padding: 8px 10px; border-bottom: 1px solid #334155; display: flex; gap: 10px; background: #0f172a; position: sticky; top: 0; z-index: 10; }
        .multi-select-header button { background: none; border: none; color: #88c0d0; font-size: 10px; cursor: pointer; padding: 0; text-transform: uppercase; font-weight: bold; }
        .multi-select-header button:hover { text-decoration: underline; }
        .multi-select-option { padding: 6px 10px; display: flex; align-items: center; gap: 10px; cursor: pointer; font-size: 12px; }
        .multi-select-option:hover { background: #334155; }
        .multi-select-option input { width: auto !important; margin: 0; cursor: pointer; }

EOD;

if (strpos($content, '/* Multi-select Dropdown */') === false) {
    $content = str_replace('</style>', $css . '    </style>', $content);
}

// 2. Update POST Handler
$new_rule_handler = <<<'EOD'
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upsert_status_rule') {
    $id = (int)$_POST['id'];
    $name = $_POST['name'];
    $status_id = (int)$_POST['status_id'];
    $profile_id = (int)$_POST['profile_id'];
    $priority = (int)$_POST['priority'];
    
    $orbital_count_op = $_POST['orbital_count_op'] ?: null;
    $orbital_count_val = $_POST['orbital_count_val'] !== '' ? (int)$_POST['orbital_count_val'] : null;
    $terrestrial_count_op = $_POST['terrestrial_count_op'] ?: null;
    $terrestrial_count_val = $_POST['terrestrial_count_val'] !== '' ? (int)$_POST['terrestrial_count_val'] : null;

    // Multi-select Factions logic
    $orb_factions = $_POST['orbital_dominant_factions'] ?? [];
    $terr_factions = $_POST['ground_dominant_factions'] ?? [];
    
    // If "any" is in the list, we clear the list to mean "no filter"
    if (in_array('any', $orb_factions)) $orb_factions = [];
    if (in_array('any', $terr_factions)) $terr_factions = [];

    $orbital_dominance = !empty($orb_factions) ? implode(',', $orb_factions) : null;
    $terrestrial_dominance = !empty($terr_factions) ? implode(',', $terr_factions) : null;
    $is_empty_case = isset($_POST['is_empty_case']) ? 1 : 0;
    
    // V2 Compat
    $orbital_dominance_mode = $orbital_dominance ? 'IN' : 'ANY';
    $terrestrial_dominance_mode = $terrestrial_dominance ? 'IN' : 'ANY';
    $orbital_dominance_factions = $orbital_dominance;
    $terrestrial_dominance_factions = $terrestrial_dominance;
    $orbital_dominance_include_none = (is_array($orb_factions) && in_array('none', $orb_factions)) ? 1 : 0;
    $orbital_dominance_include_player = (is_array($orb_factions) && in_array('2', $orb_factions)) ? 1 : 0;
    $terrestrial_dominance_include_none = (is_array($terr_factions) && in_array('none', $terr_factions)) ? 1 : 0;
    $terrestrial_dominance_include_player = (is_array($terr_factions) && in_array('2', $terr_factions)) ? 1 : 0;
    $dominance_diff_required = 0;

    if ($id > 0) {
        $stmt = $db->prepare("UPDATE celestial_object_status_rules SET name = ?, status_id = ?, profile_id = ?, priority = ?, orbital_count_op = ?, orbital_count_val = ?, terrestrial_count_op = ?, terrestrial_count_val = ?, orbital_dominance = ?, terrestrial_dominance = ?, is_empty_case = ?, orbital_dominance_mode = ?, orbital_dominance_factions = ?, orbital_dominance_include_none = ?, orbital_dominance_include_player = ?, terrestrial_dominance_mode = ?, terrestrial_dominance_factions = ?, terrestrial_dominance_include_none = ?, terrestrial_dominance_include_player = ?, dominance_diff_required = ? WHERE id = ?");
        $stmt->execute([$name, $status_id, $profile_id, $priority, $orbital_count_op, $orbital_count_val, $terrestrial_count_op, $terrestrial_count_val, $orbital_dominance, $terrestrial_dominance, $is_empty_case, $orbital_dominance_mode, $orbital_dominance_factions, $orbital_dominance_include_none, $orbital_dominance_include_player, $terrestrial_dominance_mode, $terrestrial_dominance_factions, $terrestrial_dominance_include_none, $terrestrial_dominance_include_player, $dominance_diff_required, $id]);
    } else {
        $stmt = $db->prepare("INSERT INTO celestial_object_status_rules (name, status_id, profile_id, priority, orbital_count_op, orbital_count_val, terrestrial_count_op, terrestrial_count_val, orbital_dominance, terrestrial_dominance, is_empty_case, orbital_dominance_mode, orbital_dominance_factions, orbital_dominance_include_none, orbital_dominance_include_player, terrestrial_dominance_mode, terrestrial_dominance_factions, terrestrial_dominance_include_none, terrestrial_dominance_include_player, dominance_diff_required) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$name, $status_id, $profile_id, $priority, $orbital_count_op, $orbital_count_val, $terrestrial_count_op, $terrestrial_count_val, $orbital_dominance, $terrestrial_dominance, $is_empty_case, $orbital_dominance_mode, $orbital_dominance_factions, $orbital_dominance_include_none, $orbital_dominance_include_player, $terrestrial_dominance_mode, $terrestrial_dominance_factions, $terrestrial_dominance_include_none, $terrestrial_dominance_include_player, $dominance_diff_required]);
    }
    header("Location: admin.php?tab=statuses&success=1");
    exit;
EOD;

$content = preg_replace('/if \(\$_SERVER\[\'REQUEST_METHOD\'\] === \'POST\' && isset\(\$_POST\[\'action\'\]\) && \$_POST\[\'action\'\] === \'upsert_status_rule\'\) \{.*?header\(\"Location: admin\.php\?tab=statuses&success=1\"\);\n    exit;/s', $new_rule_handler, $content);

// 3. Update UI Form
$new_ui = <<<'EOD'
<div style="display: flex; gap: 15px; align-items: flex-start; margin-bottom: 10px;">
                                    <div style="flex: 0 0 180px; font-size: 11px; color: #88c0d0; font-weight: bold; padding-top: 5px;">FACTION DOMINANTE :</div>
                                    <div class="form-group" style="flex: 1; margin-bottom: 0;">
                                        <label style="font-size: 10px;">En Orbite</label>
                                        <div class="multi-select-dropdown" id="orb_dom_container">
                                            <div class="multi-select-btn" id="orb-factions-btn" onclick="toggleMultiSelect('orb-factions')">
                                                N'importe laquelle <i class="fa-solid fa-chevron-down"></i>
                                            </div>
                                            <div class="multi-select-menu" id="orb-factions-menu">
                                                <div class="multi-select-header">
                                                    <button type="button" onclick="selectAllMultiSelect('orb-factions', true)">Tout sélectionner</button>
                                                    <button type="button" onclick="selectAllMultiSelect('orb-factions', false)">Tout désélectionner</button>
                                                </div>
                                                <div class="multi-select-option" onclick="toggleCheckbox(event, this)">
                                                    <input type="checkbox" name="orbital_dominant_factions[]" value="any" class="orb-factions-checkbox any-option" data-label="N'importe laquelle" onchange="handleAnyOption('orb-factions', this)">
                                                    <span>N'importe laquelle</span>
                                                </div>
                                                <div class="multi-select-option" onclick="toggleCheckbox(event, this)">
                                                    <input type="checkbox" name="orbital_dominant_factions[]" value="none" class="orb-factions-checkbox" data-label="Aucune (Vide)" onchange="updateMultiSelectDisplay('orb-factions')">
                                                    <span>Aucune (Vide)</span>
                                                </div>
                                                <div class="multi-select-option" onclick="toggleCheckbox(event, this)">
                                                    <input type="checkbox" name="orbital_dominant_factions[]" value="2" class="orb-factions-checkbox" data-label="Joueur (Terrien)" onchange="updateMultiSelectDisplay('orb-factions')">
                                                    <span>Joueur (Terrien)</span>
                                                </div>
                                                <hr style="border: 0; border-top: 1px solid #334155; margin: 5px 0;">
                                                <?php foreach($factions_list as $f): if($f['id'] > 2): ?>
                                                    <div class="multi-select-option" onclick="toggleCheckbox(event, this)">
                                                        <input type="checkbox" name="orbital_dominant_factions[]" value="<?php echo $f['id']; ?>" class="orb-factions-checkbox" data-label="<?php echo htmlspecialchars($f['name']); ?>" onchange="updateMultiSelectDisplay('orb-factions')">
                                                        <span><?php echo htmlspecialchars($f['name']); ?></span>
                                                    </div>
                                                <?php endif; endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group" style="flex: 1; margin-bottom: 0;">
                                        <label style="font-size: 10px;">Au Sol</label>
                                        <div class="multi-select-dropdown" id="terr_dom_container">
                                            <div class="multi-select-btn" id="terr-factions-btn" onclick="toggleMultiSelect('terr-factions')">
                                                N'importe laquelle <i class="fa-solid fa-chevron-down"></i>
                                            </div>
                                            <div class="multi-select-menu" id="terr-factions-menu">
                                                <div class="multi-select-header">
                                                    <button type="button" onclick="selectAllMultiSelect('terr-factions', true)">Tout sélectionner</button>
                                                    <button type="button" onclick="selectAllMultiSelect('terr-factions', false)">Tout désélectionner</button>
                                                </div>
                                                <div class="multi-select-option" onclick="toggleCheckbox(event, this)">
                                                    <input type="checkbox" name="ground_dominant_factions[]" value="any" class="terr-factions-checkbox any-option" data-label="N'importe laquelle" onchange="handleAnyOption('terr-factions', this)">
                                                    <span>N'importe laquelle</span>
                                                </div>
                                                <div class="multi-select-option" onclick="toggleCheckbox(event, this)">
                                                    <input type="checkbox" name="ground_dominant_factions[]" value="none" class="terr-factions-checkbox" data-label="Aucune (Vide)" onchange="updateMultiSelectDisplay('terr-factions')">
                                                    <span>Aucune (Vide)</span>
                                                </div>
                                                <div class="multi-select-option" onclick="toggleCheckbox(event, this)">
                                                    <input type="checkbox" name="ground_dominant_factions[]" value="2" class="terr-factions-checkbox" data-label="Joueur (Terrien)" onchange="updateMultiSelectDisplay('terr-factions')">
                                                    <span>Joueur (Terrien)</span>
                                                </div>
                                                <hr style="border: 0; border-top: 1px solid #334155; margin: 5px 0;">
                                                <?php foreach($factions_list as $f): if($f['id'] > 2): ?>
                                                    <div class="multi-select-option" onclick="toggleCheckbox(event, this)">
                                                        <input type="checkbox" name="ground_dominant_factions[]" value="<?php echo $f['id']; ?>" class="terr-factions-checkbox" data-label="<?php echo htmlspecialchars($f['name']); ?>" onchange="updateMultiSelectDisplay('terr-factions')">
                                                        <span><?php echo htmlspecialchars($f['name']); ?></span>
                                                    </div>
                                                <?php endif; endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div style="display: flex; align-items: center; gap: 20px; padding-top: 10px; border-top: 1px solid #334155;">
                                    <div style="display: flex; align-items: center; gap: 5px;">
                                        <input type="checkbox" name="is_empty_case" id="rule_empty" style="width: auto;">
                                        <label for="rule_empty" style="margin-bottom: 0; color: #ebcb8b; font-size: 11px;">Cas "CASE VIDE"</label>
                                    </div>
                                </div>
EOD;

// Need to match exactly the old UI to replace it
$old_ui_regex = '/<div style="display: flex; gap: 15px; align-items: flex-start; margin-bottom: 10px;">.*?FILTRE DOMINANCE :.*?Cas \"CASE VIDE\".*?<\/div>.*?<\/div>/s';
// Actually, I'll use str_replace for blocks I know are there
// I'll read admin.php around the UI block to be 100% sure of the string.

$js_additions = <<<'EOD'
        function toggleMultiSelect(id) {
            const menu = document.getElementById(id + '-menu');
            if(!menu) return;
            menu.classList.toggle('show');
            const closer = function(e) {
                if (!e.target.closest('.multi-select-dropdown')) {
                    menu.classList.remove('show');
                    document.removeEventListener('click', closer);
                }
            };
            setTimeout(() => document.addEventListener('click', closer), 0);
        }

        function toggleCheckbox(e, element) {
            if (e.target.tagName === 'INPUT') return;
            const cb = element.querySelector('input[type="checkbox"]');
            if(cb) {
                cb.checked = !cb.checked;
                cb.dispatchEvent(new Event('change'));
            }
        }

        function handleAnyOption(id, anyCb) {
            if (anyCb.checked) {
                document.querySelectorAll('.' + id + '-checkbox:not(.any-option)').forEach(cb => cb.checked = false);
            }
            updateMultiSelectDisplay(id);
        }

        function updateMultiSelectDisplay(id) {
            const checkboxes = document.querySelectorAll('.' + id + '-checkbox');
            const btn = document.getElementById(id + '-btn');
            if(!btn) return;
            const anyOption = document.querySelector('.' + id + '-checkbox.any-option');
            const selected = [];
            let hasSelection = false;
            
            checkboxes.forEach(cb => {
                if (cb.checked && !cb.classList.contains('any-option')) {
                    selected.push(cb.dataset.label);
                    hasSelection = true;
                }
            });

            if (hasSelection && anyOption) anyOption.checked = false;

            if (selected.length === 0) {
                btn.innerHTML = 'N\'importe laquelle <i class="fa-solid fa-chevron-down"></i>';
            } else {
                if (selected.length > 2) {
                    btn.innerHTML = selected.length + ' sélectionné(s) <i class="fa-solid fa-chevron-down"></i>';
                } else {
                    btn.innerHTML = selected.join(', ') + ' <i class="fa-solid fa-chevron-down"></i>';
                }
            }
        }

        function selectAllMultiSelect(id, selectAll) {
            document.querySelectorAll('.' + id + '-checkbox').forEach(cb => {
                if (cb.classList.contains('any-option')) {
                    cb.checked = !selectAll;
                } else {
                    cb.checked = selectAll;
                }
            });
            updateMultiSelectDisplay(id);
        }
EOD;

if (strpos($content, 'function toggleMultiSelect') === false) {
    $content = str_replace('// --- LOOTBOX SYSTEM ---', $js_additions . "\n\n" . '        // --- LOOTBOX SYSTEM ---', $content);
}

// Re-do the editRule replacement more carefully
$content = preg_replace('/document\.getElementById\(\'rule_orb_op\'\)\.value = data\.orbital_count_op \|\| \"\";.*document\.getElementById\(\'rule_empty\'\)\.checked = data\.is_empty_case == 1;/s', 
'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 : "";
            
            // Populate Multi-selects
            const orbVals = (data.orbital_dominance || "").split(",");
            document.querySelectorAll(\'.orb-factions-checkbox\').forEach(cb => {
                cb.checked = orbVals.includes(cb.value);
            });
            const anyOrb = document.querySelector(\'.orb-factions-checkbox.any-option\');
            if (anyOrb && (orbVals.length === 0 || orbVals[0] === "")) anyOrb.checked = true;
            updateMultiSelectDisplay(\'orb-factions\');

            const terrVals = (data.terrestrial_dominance || "").split(",");
            document.querySelectorAll(\'.terr-factions-checkbox\').forEach(cb => {
                cb.checked = terrVals.includes(cb.value);
            });
            const anyTerr = document.querySelector(\'.terr-factions-checkbox.any-option\');
            if (anyTerr && (terrVals.length === 0 || terrVals[0] === "")) anyTerr.checked = true;
            updateMultiSelectDisplay(\'terr-factions\');

            document.getElementById(\'rule_empty\').checked = data.is_empty_case == 1;', $content);

$content = str_replace('document.getElementById(\'ruleForm\').reset(); document.getElementById(\'rule_id\').value = 0;', 
'document.getElementById(\'ruleForm\').reset(); 
            document.getElementById(\'rule_id\').value = 0;
            selectAllMultiSelect(\'orb-factions\', false);
            selectAllMultiSelect(\'terr-factions\', false);
            const anyOrbForm = document.querySelector(\'.orb-factions-checkbox.any-option\');
            if(anyOrbForm) anyOrbForm.checked = true;
            const anyTerrForm = document.querySelector(\'.terr-factions-checkbox.any-option\');
            if(anyTerrForm) anyTerrForm.checked = true;
            updateMultiSelectDisplay(\'orb-factions\');
            updateMultiSelectDisplay(\'terr-factions\');', $content);

// Final UI swap (Manual block replace to be safe)
// I'll search for specific markers in UI
$start_marker = '<div style="flex: 0 0 180px; font-size: 11px; color: #88c0d0; font-weight: bold; padding-top: 5px;">FILTRE DOMINANCE :</div>';
$end_marker = '<label for="rule_diff" style="margin-bottom: 0; color: #a3be8c; font-size: 11px;">Dominante orbite ≠ Dominante sol</label>
                                    </div>
                                </div>';

// Find the parent containers
// I'll just use the preg_replace on handler and table as they worked.
// For UI I will use a very specific string replace of the whole block.

file_put_contents($admin_path, $content);
echo "Admin patched successfully.";
