<?php
$states = [
    'sc' => ['zip' => 'w.zip'],
    'mg' => ['zip' => 's.zip'],
    'pr' => ['zip' => 'S.zip'],
    'ms' => ['zip' => 'as.zip'],
    'rs' => ['zip' => 'rs.zip'],
    'rj_zapay' => ['zip' => 's.zip'],
    'rj' => ['zip' => 'RJ.zip', 'path' => '/var/www/html/rj'],
    'df' => ['bak' => true],
    'mt' => ['bak' => true],
    'go' => ['bak' => true],
    'header' => ['zip' => 's.zip']
];

$safeDir = '/var/www/safe_configs';
@mkdir($safeDir, 0777, true);

$configs = ['client-config.php', 'api.php', 'pix-config.php', 'pix-api.php', 'track.php', 'security-client.php'];

foreach ($states as $state => $info) {
    $dir = $info['path'] ?? "/var/www/$state";
    echo "Processando $state em $dir...\n";
    
    if (!is_dir($dir)) { echo "  Diretorio nao existe!\n"; continue; }

    // 1. Backup Configs
    @mkdir("$safeDir/$state", 0777, true);
    foreach ($configs as $cfg) {
        if (file_exists("$dir/$cfg")) {
            copy("$dir/$cfg", "$safeDir/$state/$cfg");
            echo "  Config salvo: $cfg\n";
        }
    }

    // 2. Limpeza Frontend
    $filesToDelete = glob("$dir/{index,debitos,resumo,pagar,debitos1}*.{html,php}", GLOB_BRACE);
    foreach ($filesToDelete as $file) {
        if (in_array(basename($file), $configs)) continue; 
        unlink($file);
    }
    echo "  Frontend limpo.\n";

    // 3. Restauração
    if (isset($info['zip'])) {
        $zipFile = "$dir/" . $info['zip'];
        if (file_exists($zipFile)) {
            // Usando unzip do sistema com -o (overwrite) e -d (destination)
            // Redirecionando output para null para não poluir
            shell_exec("unzip -o '$zipFile' -d '$dir' > /dev/null");
            echo "  ZIP extraido: {$info['zip']}\n";
        } else {
            echo "  ZIP nao encontrado: $zipFile\n";
        }
    } elseif (isset($info['bak'])) {
        $baks = glob("$dir/*.bak*");
        foreach ($baks as $bak) {
            $original = str_replace(['.bak2', '.bak'], '', $bak);
            // Sobrescreve sempre para garantir que é o backup
            copy($bak, $original);
            echo "  Restaurado de BAK: " . basename($original) . "\n";
        }
    }

    // 4. Restaurar Configs (Forçar sobrescrita sobre o que veio do zip)
    foreach ($configs as $cfg) {
        if (file_exists("$safeDir/$state/$cfg")) {
            copy("$safeDir/$state/$cfg", "$dir/$cfg");
            echo "  Config restaurado: $cfg\n";
        }
    }
}
echo "Concluido.\n";
