<?php
/**
 * Modern Proxy Manager with Admin Routing
 * Access Add page via: yourdomain.com/index.php?admin
 */
$proxy_file = 'proxies.txt';
$header_line = "# superproxy:proxylist:v1";
$max_take = 1000;

// Determine if we are in admin mode
$is_admin = isset($_GET['admin']);

if (!file_exists($proxy_file)) { touch($proxy_file); chmod($proxy_file, 0666); }

$message = "";
$status_type = "info";

function countProxies($file) {
    if (!file_exists($file)) return 0;
    $lines = file($file, FILE_SKIP_EMPTY_LINES);
    return count(array_filter($lines, fn($l) => trim($l) !== '' && strpos(trim($l), '#') !== 0));
}

// --- LOGIC: ADD PROXIES (Admin Only) ---
if ($is_admin && isset($_POST['action']) && $_POST['action'] === 'add') {
    $raw_input = $_POST['new_proxies'] ?? '';
    $lines = explode("\n", str_replace("\r", "", $raw_input));
    $added_count = 0;
    $f = fopen($proxy_file, 'a');
    if (flock($f, LOCK_EX)) {
        foreach ($lines as $line) {
            $line = trim($line);
            if (!empty($line)) {
                fwrite($f, $line . PHP_EOL);
                $added_count++;
            }
        }
        flock($f, LOCK_UN);
        $message = "Successfully added $added_count proxies.";
        $status_type = "success";
    }
    fclose($f);
}

// --- LOGIC: DOWNLOAD & REMOVE (Public) ---
if (isset($_POST['action']) && $_POST['action'] === 'download') {
    $count = filter_var($_POST['count'], FILTER_VALIDATE_INT);
    if ($count && $count > 0) {
        if ($count > $max_take) $count = $max_take;
        $f = fopen($proxy_file, 'c+');
        if (flock($f, LOCK_EX)) {
            $all_lines = [];
            while (($line = fgets($f)) !== false) { $all_lines[] = rtrim($line); }
            $taken = []; $remaining = []; $taken_count = 0;

            foreach ($all_lines as $line) {
                $trimmed = trim($line);
                if (empty($trimmed) || strpos($trimmed, '#') === 0 || $taken_count >= $count) {
                    $remaining[] = $line;
                    continue;
                }
                $parts = explode(':', $trimmed);
                if (count($parts) >= 4) {
                    $taken[] = ['host'=>$parts[0], 'port'=>$parts[1], 'user'=>$parts[2], 'pass'=>implode(':', array_slice($parts, 3))];
                    $taken_count++;
                } else { $remaining[] = $line; }
            }
            ftruncate($f, 0); rewind($f);
            foreach ($remaining as $rem) { fwrite($f, $rem . PHP_EOL); }
            fflush($f); flock($f, LOCK_UN); fclose($f);

            if (!empty($taken)) {
                header('Content-Type: text/plain');
                header('Content-Disposition: attachment; filename="proxies_' . count($taken) . '.txt"');
                echo $header_line . "\r\n";
                foreach ($taken as $idx => $p) {
                    echo "socks5://{$p['user']}:{$p['pass']}@{$p['host']}:{$p['port']}  \"<PROFILE___".($idx+1).">\"\r\n";
                }
                exit;
            }
        }
    }
}

$current_count = countProxies($proxy_file);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $is_admin ? 'Admin Panel' : 'Proxy Extract'; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
        body { font-family: 'Inter', sans-serif; background-color: #0f172a; color: #f1f5f9; }
        .glass { background: rgba(30, 41, 59, 0.7); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.1); }
    </style>
</head>
<body class="min-h-screen flex flex-col items-center justify-center p-6">

    <div class="w-full max-w-4xl">
        <div class="flex flex-col md:flex-row justify-between items-end mb-8 gap-4">
            <div>
                <h1 class="text-4xl font-extrabold text-white tracking-tight">
                    Proxy<span class="text-blue-500 underline decoration-blue-500/30">Dash</span>
                </h1>
                <p class="text-slate-400 mt-1"><?php echo $is_admin ? 'Management Console' : 'Inventory Extraction'; ?></p>
            </div>
            <div class="glass px-6 py-3 rounded-2xl flex items-center gap-4 border-blue-500/20">
                <span class="relative flex h-3 w-3">
                    <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"></span>
                    <span class="relative inline-flex rounded-full h-3 w-3 bg-blue-500"></span>
                </span>
                <p class="text-sm font-medium text-slate-300">Live Pool: <span class="text-white font-bold text-lg ml-1"><?php echo $current_count; ?></span></p>
            </div>
        </div>

        <?php if ($message): ?>
            <div class="mb-6 p-4 rounded-xl glass border-emerald-500/30 text-emerald-400 flex items-center gap-3">
                <i class="fas fa-check-circle"></i> <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 <?php echo $is_admin ? 'md:grid-cols-5' : ''; ?> gap-6">
            
            <?php if ($is_admin): ?>
            <div class="md:col-span-3 glass rounded-3xl p-8 shadow-2xl">
                <h2 class="text-xl font-bold text-white mb-6 flex items-center gap-2">
                    <i class="fas fa-upload text-blue-500"></i> Import New Batch
                </h2>
                <form method="POST" action="?admin">
                    <input type="hidden" name="action" value="add">
                    <textarea 
                        name="new_proxies" 
                        class="w-full h-64 bg-slate-900/80 border border-slate-700 rounded-2xl p-4 text-mono text-sm text-blue-300 focus:ring-2 focus:ring-blue-500 outline-none transition-all placeholder-slate-600 mb-4"
                        placeholder="host:port:user:pass"></textarea>
                    <button type="submit" class="w-full bg-blue-600 hover:bg-blue-500 text-white font-bold py-4 rounded-2xl transition-all shadow-lg shadow-blue-600/20">
                        Add Proxies to File
                    </button>
                </form>
            </div>
            <?php endif; ?>

            <div class="<?php echo $is_admin ? 'md:col-span-2' : 'max-w-md mx-auto w-full'; ?> glass rounded-3xl p-8 border-t-4 border-t-emerald-500 shadow-2xl">
                <h2 class="text-xl font-bold text-white mb-6 flex items-center gap-2">
                    <i class="fas fa-download text-emerald-500"></i> Extract Proxies
                </h2>
                <form method="POST">
                    <input type="hidden" name="action" value="download">
                    <div class="mb-6">
                        <label class="block text-xs uppercase tracking-widest font-bold text-slate-500 mb-3">Quantity</label>
                        <input 
                            type="number" 
                            name="count" 
                            value="8" 
                            class="w-full bg-slate-900 border border-slate-700 rounded-xl py-4 px-4 text-white text-xl font-bold focus:border-emerald-500 outline-none transition-all"
                        >
                    </div>
                    <button type="submit" <?php echo $current_count === 0 ? 'disabled' : ''; ?> 
                        class="w-full <?php echo $current_count === 0 ? 'bg-slate-800 text-slate-600 cursor-not-allowed' : 'bg-emerald-600 hover:bg-emerald-500 shadow-emerald-600/20'; ?> text-white font-bold py-4 rounded-2xl transition-all shadow-lg flex items-center justify-center gap-2 text-lg">
                        Get Converted TXT
                    </button>
                </form>
                
                <div class="mt-8 pt-6 border-t border-slate-700/50">
                    <p class="text-[10px] text-slate-500 uppercase tracking-widest font-bold mb-2 text-center underline decoration-slate-700">Output Format</p>
                    <div class="text-[10px] font-mono text-slate-400 bg-black/30 p-2 rounded text-center truncate">
                        socks5://user:pass@host:port
                    </div>
                </div>
            </div>

        </div>

        <footer class="mt-12 text-center">
            <p class="text-slate-600 text-xs tracking-widest uppercase">
                &copy; <?php echo date("Y"); ?> ProxyDash Dashboard
            </p>
        </footer>
    </div>

</body>
</html>