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

// 1. Update POST Handler
$old_handler = '$is_empty_case = isset($_POST[\'is_empty_case\']) ? 1 : 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 = ? 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, $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) 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]);
    }
';

$new_handler = '$is_empty_case = isset($_POST[\'is_empty_case\']) ? 1 : 0;
    $combine_mode = $_POST[\'combine_mode\'] ?? \'OR\';

    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 = ?, combine_mode = ? 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, $combine_mode, $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, combine_mode) 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, $combine_mode]);
    }
';

if (strpos($content, $old_handler) !== false) {
    $content = str_replace($old_handler, $new_handler, $content);
    echo "Handler patched.\n";
} else {
    echo "Handler NOT found.\n";
}

// 2. Update UI (Configuration des règles)
$start_marker = '<div style="background: rgba(0,0,0,0.2); padding: 15px; border-radius: 4px; border: 1px solid #334155; margin-bottom: 15px;">';
$end_marker = 'ENREGISTRER LA RÈGLE</button>';

$pos_start = strpos($content, $start_marker);
$pos_end = strpos($content, $end_marker, $pos_start);

if ($pos_start !== false && $pos_end !== false) {
    // We want to replace everything from $start_marker up to just before "ENREGISTRER LA RÈGLE" button
    // Actually the UI I prepared includes the background div.
    
    $new_ui = <<<'HTML'
                            <div style="background: rgba(0,0,0,0.2); padding: 15px; border-radius: 4px; border: 1px solid #334155; margin-bottom: 15px;">
                                <div style="display: flex; gap: 20px; align-items: stretch;">
                                    
                                    <!-- COLONNE ORBITALE -->
                                    <div style="flex: 1; display: flex; flex-direction: column; gap: 15px; padding-right: 15px; border-right: 1px dashed #334155;">
                                        <div style="font-size: 11px; color: #88c0d0; font-weight: bold; text-align: center; border-bottom: 1px solid #334155; padding-bottom: 5px; margin-bottom: 5px;">EN ORBITE</div>
                                        
                                        <div class="form-group" style="margin-bottom: 0;">
                                            <label style="font-size: 10px;">Nombre de factions</label>
                                            <div style="display: flex; gap: 5px;">
                                                <select name="orbital_count_op" id="rule_orb_op" style="width: 70px;">
                                                    <option value="">-
                                                    <option value="=">=
                                                    <option value=">">>
                                                    <option value="<"><
                                                    <option value=">=">=
                                                    <option value="<="><=
                                                </select>
                                                <input type="number" name="orbital_count_val" id="rule_orb_val" placeholder="0">
                                            </div>
                                        </div>

                                        <div class="form-group" style="margin-bottom: 0;">
                                            <label style="font-size: 10px;">Filtre Dominance</label>
                                            <div class="ms-container" id="ms_orb">
                                                <div class="ms-display" onclick="toggleMS('ms_orb_list')">Toutes / Peu importe</div>
                                                <div class="ms-dropdown" id="ms_orb_list">
                                                    <label class="ms-item"><input type="checkbox" value="none" onchange="updateMSLabel('ms_orb')"> Aucune (Vide)</label>
                                                    <?php foreach($factions_list as $f): if($f['name'] !== 'Aucune'): ?>
                                                        <label class="ms-item"><input type="checkbox" value="<?php echo $f['id']; ?>" name="orbital_dominance[]" onchange="updateMSLabel('ms_orb')"> <?php echo htmlspecialchars($f['name']); ?></label>
                                                    <?php endif; endforeach; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- COLONNE COMBINAISON (MILIEU) -->
                                    <div style="flex: 0 0 100px; display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 10px; background: rgba(136, 192, 208, 0.05); border-radius: 8px; border: 1px solid rgba(136, 192, 208, 0.2); padding: 10px;">
                                        <label style="font-size: 10px; color: #88c0d0; font-weight: bold; text-transform: uppercase;">Combinaison</label>
                                        <select name="combine_mode" id="rule_combine" style="width: 100%; text-align: center; font-weight: bold; color: #ebcb8b; background: #2e3440; border-color: #88c0d0;">
                                            <option value="OR">OU</option>
                                            <option value="AND">ET</option>
                                        </select>
                                        <div style="font-size: 9px; color: #d8dee9; text-align: center; opacity: 0.7;">(Orbital) [?] (Sol)</div>
                                    </div>

                                    <!-- COLONNE SOL -->
                                    <div style="flex: 1; display: flex; flex-direction: column; gap: 15px; padding-left: 15px; border-left: 1px dashed #334155;">
                                        <div style="font-size: 11px; color: #88c0d0; font-weight: bold; text-align: center; border-bottom: 1px solid #334155; padding-bottom: 5px; margin-bottom: 5px;">AU SOL</div>

                                        <div class="form-group" style="margin-bottom: 0;">
                                            <label style="font-size: 10px;">Nombre de factions</label>
                                            <div style="display: flex; gap: 5px;">
                                                <select name="terrestrial_count_op" id="rule_terr_op" style="width: 70px;">
                                                    <option value="">-
                                                    <option value="=">=
                                                    <option value=">">>
                                                    <option value="<"><
                                                    <option value=">=">=
                                                    <option value="<="><=
                                                </select>
                                                <input type="number" name="terrestrial_count_val" id="rule_terr_val" placeholder="0">
                                            </div>
                                        </div>

                                        <div class="form-group" style="margin-bottom: 0;">
                                            <label style="font-size: 10px;">Filtre Dominance</label>
                                            <div class="ms-container" id="ms_terr">
                                                <div class="ms-display" onclick="toggleMS('ms_terr_list')">Toutes / Peu importe</div>
                                                <div class="ms-dropdown" id="ms_terr_list">
                                                    <label class="ms-item"><input type="checkbox" value="none" onchange="updateMSLabel('ms_terr')"> Aucune (Vide)</label>
                                                    <?php foreach($factions_list as $f): if($f['name'] !== 'Aucune'): ?>
                                                        <label class="ms-item"><input type="checkbox" value="<?php echo $f['id']; ?>" name="terrestrial_dominance[]" onchange="updateMSLabel('ms_terr')"> <?php echo htmlspecialchars($f['name']); ?></label>
                                                    <?php endif; endforeach; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div style="display: flex; align-items: center; gap: 10px; padding-top: 15px; margin-top: 15px; border-top: 1px solid #334155;">
                                    <input type="checkbox" name="is_empty_case" id="rule_empty" style="width: auto;">
                                    <label for="rule_empty" style="margin-bottom: 0; color: #ebcb8b;">Cas "CASE VIDE" (Aucune faction nulle part)</label>
                                </div>
                            </div>
HTML;
    
    // Find where the background div ends (it should be before the button)
    // We can find the button and look backwards for the last </div> before it.
    $pos_button = strpos($content, '<button type="submit" class="btn btn-add">ENREGISTRER LA RÈGLE');
    $content_before_button = substr($content, 0, $pos_button);
    $last_div_pos = strrpos($content_before_button, '</div>');
    
    // Re-verify that we are replacing the right block
    $content = substr($content, 0, $pos_start) . $new_ui . substr($content, $pos_button);
    echo "UI patched.\n";
} else {
    echo "UI NOT found.\n";
}

// 3. Update JS (resetRuleForm)
if (strpos($content, "document.getElementById('rule_id').value = 0; document.getElementById('rule_combine').value = 'OR';") === false) {
    $content = str_replace(
        "document.getElementById('rule_id').value = 0;",
        "document.getElementById('rule_id').value = 0; document.getElementById('rule_combine').value = 'OR';",
        $content
    );
    echo "JS patched.\n";
} else {
    echo "JS already patched or not found.\n";
}

file_put_contents($file, $content);
echo "Final save done.\n";
?>