<?php if (!defined('DASHBOARD_ROOT')) { http_response_code(403); exit; }
RBAC::enforce('admin');

// ── Vault decrypt helper (matches Python/init encryption format: v1:<b64>) ──
function vaultDecrypt(string $enc): string {
    if (!str_starts_with($enc, 'v1:')) return $enc; // pin_hash stored raw
    $raw = base64_decode(substr($enc, 3), true);
    if (!$raw || strlen($raw) < 29) return '';
    $iv  = substr($raw, 0, 12);
    $tag = substr($raw, 12, 16);
    $ct  = substr($raw, 28);
    // Load sk from .env
    static $key = null;
    if ($key === null) {
        $envLines = file(PRIVATE_DIR . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($envLines as $line) {
            [$k, $v] = array_pad(explode('=', $line, 2), 2, '');
            if (trim($k) === 'sk') { $key = hex2bin(trim($v)); break; }
        }
    }
    if (!$key) return '—';
    $plain = openssl_decrypt($ct, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
    return $plain !== false ? $plain : '—';
}

function vd(string $key): string {
    $row = DB::one("SELECT setting_value FROM settings WHERE setting_key = :k", [':k' => $key]);
    return $row ? vaultDecrypt($row['setting_value']) : '—';
}

// ── Secondary vault authentication ────────────────────────────────────────
$vaultUnlocked = ($_SESSION['vault_unlocked'] ?? false) === true;

if (!$vaultUnlocked && isset($_POST['vault_pin'])) {
    $pinHash = DB::val("SELECT setting_value FROM settings WHERE setting_key = 'vault_pin_hash'");
    if ($pinHash && password_verify($_POST['vault_pin'], $pinHash)) {
        $_SESSION['vault_unlocked']    = true;
        $_SESSION['vault_unlocked_at'] = time();
        $vaultUnlocked = true;
    } else {
        $pinError = true;
        usleep(500_000);
    }
}

if ($vaultUnlocked && (time() - ($_SESSION['vault_unlocked_at'] ?? 0)) > 600) {
    unset($_SESSION['vault_unlocked'], $_SESSION['vault_unlocked_at']);
    $vaultUnlocked = false;
}

if (isset($_GET['lock_vault'])) {
    unset($_SESSION['vault_unlocked'], $_SESSION['vault_unlocked_at']);
    header('Location: ?view=safety'); exit;
}
?>
<link rel="stylesheet" href="assets/css/safety.css?v=2" nonce="<?= $cspNonce ?? '' ?>">
<div class="workspace" id="ws-safety">

<?php if (!$vaultUnlocked): ?>
<!-- ── LOCK SCREEN ──────────────────────────────────────────────────── -->
<div class="vault-lock-screen">
    <div class="vault-lock-card">
        <div class="vault-lock-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                <rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/>
            </svg>
        </div>
        <h2 class="vault-lock-title">Safety Vault</h2>
        <p class="vault-lock-sub">Enter your vault password to access credentials</p>
        <form method="POST" action="?view=safety" autocomplete="off">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars(Auth::csrf()) ?>">
            <div class="vault-pin-field<?= isset($pinError) ? ' error' : '' ?>">
                <input type="password" name="vault_pin" class="vault-pin-input" placeholder="Vault password" autofocus autocomplete="off">
                <?php if (isset($pinError)): ?><div class="vault-pin-error">Incorrect password — access denied.</div><?php endif; ?>
            </div>
            <button type="submit" class="vault-unlock-btn">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 3h4a2 2 0 012 2v14a2 2 0 01-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>
                Unlock Vault
            </button>
        </form>
    </div>
</div>

<?php else:
// ── Load all vault data ────────────────────────────────────────────────────
$V = [
    'backup_code'  => vd('vault_backup_code'),
    'stripe_sk'    => vd('vault_stripe_sk'),
    'stripe_pk'    => vd('vault_stripe_pk'),
    'bridge_hmac'  => vd('vault_bridge_hmac'),
    'wallet_url'   => vd('vault_wallet_url'),
    'wallet_token' => vd('vault_wallet_token'),
    'wallet_hmac'  => vd('vault_wallet_hmac'),
    'xmr_addr'     => vd('vault_xmr_addr'),
    'usdt_addr'    => vd('vault_usdt_addr'),
    'usdc_addr'    => vd('vault_usdc_addr'),
    'et_email'     => vd('vault_et_email'),
    'db_host'      => vd('vault_db_host'),
    'db_name'      => vd('vault_db_name'),
    'db_user'      => vd('vault_db_user'),
    'db_pass'      => vd('vault_db_pass'),
    'ssh_host'     => vd('vault_ssh_host'),
    'ssh_port'     => vd('vault_ssh_port'),
    'ssh_user'     => vd('vault_ssh_user'),
    'ssh_key_name' => vd('vault_ssh_key_name'),
    'ssh_key_pass' => vd('vault_ssh_key_pass'),
    'bridge_onion' => vd('vault_bridge_onion'),
    'node_port'    => vd('vault_node_port'),
    'node_ip'      => vd('vault_node_ip'),
];
$autoLockIn = max(0, 600 - (time() - ($_SESSION['vault_unlocked_at'] ?? time())));
?>

<div class="vault-header">
    <div class="vault-header-left">
        <div class="vault-status-dot"></div>
        <span class="vault-status-label">Vault Unlocked</span>
        <span class="vault-status-meta">· auto-locks in <span id="vault-countdown"><?= $autoLockIn ?>s</span></span>
    </div>
    <a href="?view=safety&lock_vault=1" class="vault-lock-btn">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
        Lock Now
    </a>
</div>

<div class="vault-grid">

<!-- ── Emergency Backup Code ───────────────────────── -->
<div class="vault-card vault-card--full">
    <div class="vault-card-header">
        <div class="vault-card-icon vault-card-icon--amber">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
        </div>
        <div><div class="vault-card-title">Emergency Backup Code</div><div class="vault-card-sub">2FA recovery · single-use</div></div>
    </div>
    <div class="vault-secret-box">
        <span class="vault-secret-blur" id="s-backup"><?= UI::e($V['backup_code']) ?></span>
        <div class="vault-secret-actions">
            <button class="vault-action-btn" onclick="reveal('s-backup',this)" title="Reveal">👁</button>
            <button class="vault-action-btn" onclick="copy('s-backup',this)" title="Copy">📋</button>
        </div>
    </div>
    <div class="vault-card-note">⚠ Single-use. After recovery, generate a new code immediately and update this vault.</div>
</div>

<!-- ── Stripe ──────────────────────────────────────── -->
<div class="vault-card">
    <div class="vault-card-header">
        <div class="vault-card-icon vault-card-icon--purple">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="1" y="4" width="22" height="16" rx="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg>
        </div>
        <div><div class="vault-card-title">Stripe</div><div class="vault-card-sub">Test mode keys</div></div>
    </div>
    <div class="vault-info-grid">
        <div class="vault-info-row"><span>Secret Key (SK)</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-stripe-sk"><?= UI::e($V['stripe_sk']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-stripe-sk',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-stripe-sk',this)">📋</button></div></div>
        <div class="vault-info-row"><span>Public Key (PK)</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-stripe-pk"><?= UI::e($V['stripe_pk']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-stripe-pk',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-stripe-pk',this)">📋</button></div></div>
    </div>
    <div class="vault-card-note">🔁 Swap to live keys when payment server is back. Update <code>/etc/service-node/stripe.key</code> + restart container.</div>
</div>

<!-- ── Crypto Wallets ──────────────────────────────── -->
<div class="vault-card">
    <div class="vault-card-header">
        <div class="vault-card-icon vault-card-icon--amber">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M21 12V7H5a2 2 0 010-4h14v4"/><path d="M3 5v14a2 2 0 002 2h16v-5"/><circle cx="18" cy="12" r="2"/></svg>
        </div>
        <div><div class="vault-card-title">Crypto Wallets</div><div class="vault-card-sub">XMR · USDT · USDC · Wallet Node</div></div>
    </div>
    <div class="vault-info-grid">
        <div class="vault-info-row"><span>XMR Address</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-xmr"><?= UI::e($V['xmr_addr']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-xmr',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-xmr',this)">📋</button></div></div>
        <div class="vault-info-row"><span>USDT Address</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-usdt"><?= UI::e($V['usdt_addr']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-usdt',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-usdt',this)">📋</button></div></div>
        <div class="vault-info-row"><span>USDC Address</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-usdc"><?= UI::e($V['usdc_addr']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-usdc',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-usdc',this)">📋</button></div></div>
        <div class="vault-info-row"><span>Wallet Node URL</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-wurl"><?= UI::e($V['wallet_url']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-wurl',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-wurl',this)">📋</button></div></div>
        <div class="vault-info-row"><span>Wallet Token</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-wtok"><?= UI::e($V['wallet_token']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-wtok',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-wtok',this)">📋</button></div></div>
        <div class="vault-info-row"><span>Wallet HMAC</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-whmac"><?= UI::e($V['wallet_hmac']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-whmac',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-whmac',this)">📋</button></div></div>
    </div>
</div>

<!-- ── Database ────────────────────────────────────── -->
<div class="vault-card">
    <div class="vault-card-header">
        <div class="vault-card-icon vault-card-icon--green">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>
        </div>
        <div><div class="vault-card-title">Database</div><div class="vault-card-sub">MariaDB · store</div></div>
    </div>
    <div class="vault-info-grid">
        <div class="vault-info-row"><span>Host</span><code><?= UI::e($V['db_host']) ?></code></div>
        <div class="vault-info-row"><span>Database</span><code><?= UI::e($V['db_name']) ?></code></div>
        <div class="vault-info-row"><span>User</span><code><?= UI::e($V['db_user']) ?></code></div>
        <div class="vault-info-row"><span>Password</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-dbpass"><?= UI::e($V['db_pass']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-dbpass',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-dbpass',this)">📋</button></div></div>
    </div>
    <div class="vault-cmd-box"><code>mysql -h 127.0.0.1 -u <?= UI::e($V['db_user']) ?> -p store</code></div>
</div>

<!-- ── SSH ─────────────────────────────────────────── -->
<div class="vault-card">
    <div class="vault-card-header">
        <div class="vault-card-icon vault-card-icon--blue">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="3" width="20" height="14" rx="2"/><polyline points="8 21 12 17 16 21"/></svg>
        </div>
        <div><div class="vault-card-title">Server SSH</div><div class="vault-card-sub">Ed25519 · Port <?= UI::e($V['ssh_port']) ?></div></div>
    </div>
    <div class="vault-info-grid">
        <div class="vault-info-row"><span>Host</span><code><?= UI::e($V['ssh_host']) ?></code></div>
        <div class="vault-info-row"><span>Port</span><code><?= UI::e($V['ssh_port']) ?></code></div>
        <div class="vault-info-row"><span>User</span><code><?= UI::e($V['ssh_user']) ?></code></div>
        <div class="vault-info-row"><span>Key File</span><code><?= UI::e($V['ssh_key_name']) ?></code></div>
        <div class="vault-info-row"><span>Key Passphrase</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-sshpass"><?= UI::e($V['ssh_key_pass']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-sshpass',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-sshpass',this)">📋</button></div></div>
    </div>
    <div class="vault-cmd-box"><code>ssh -p <?= UI::e($V['ssh_port']) ?> -i keys/<?= UI::e($V['ssh_key_name']) ?> <?= UI::e($V['ssh_user']) ?>@<?= UI::e($V['ssh_host']) ?></code></div>
</div>

<!-- ── Service Node + Bridge ───────────────────────── -->
<div class="vault-card">
    <div class="vault-card-header">
        <div class="vault-card-icon vault-card-icon--blue">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>
        </div>
        <div><div class="vault-card-title">Service Node · Bridge</div><div class="vault-card-sub">Payment + Email proxy · Port <?= UI::e($V['node_port']) ?></div></div>
    </div>
    <div class="vault-info-grid">
        <div class="vault-info-row"><span>Container IP</span><code><?= UI::e($V['node_ip']) ?></code></div>
        <div class="vault-info-row"><span>Host Port</span><code>127.0.0.1:<?= UI::e($V['node_port']) ?></code></div>
        <div class="vault-info-row"><span>Bridge HMAC</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-bhmac"><?= UI::e($V['bridge_hmac']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-bhmac',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-bhmac',this)">📋</button></div></div>
        <div class="vault-info-row"><span>Bridge Onion</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-bonion"><?= UI::e($V['bridge_onion']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-bonion',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-bonion',this)">📋</button></div></div>
    </div>
    <div class="vault-cmd-box">
        <code>podman logs noname-service --tail 50</code>
        <code>sudo systemctl restart noname-service</code>
    </div>
</div>

<!-- ── e-Transfer ──────────────────────────────────── -->
<div class="vault-card">
    <div class="vault-card-header">
        <div class="vault-card-icon vault-card-icon--green">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
        </div>
        <div><div class="vault-card-title">e-Transfer Inbox</div><div class="vault-card-sub">IMAP scanner email</div></div>
    </div>
    <div class="vault-info-grid">
        <div class="vault-info-row"><span>Email</span><div class="vault-secret-inline"><span class="vault-secret-blur" id="s-etemail"><?= UI::e($V['et_email']) ?></span><button class="vault-action-btn-sm" onclick="reveal('s-etemail',this)">👁</button><button class="vault-action-btn-sm" onclick="copy('s-etemail',this)">📋</button></div></div>
    </div>
    <div class="vault-card-note">This inbox is monitored by the IMAP scanner for e-Transfer confirmation emails.</div>
</div>

</div><!-- /.vault-grid -->

<script nonce="<?= $cspNonce ?? '' ?>">
let secs = <?= $autoLockIn ?>;
const cd = document.getElementById('vault-countdown');
const t = setInterval(() => { secs--; if(cd) cd.textContent=secs+'s'; if(secs<=0){clearInterval(t);window.location='?view=safety&lock_vault=1';} }, 1000);

function reveal(id, btn) {
    const el = document.getElementById(id);
    const isBlurred = el.classList.contains('vault-secret-blur');
    el.classList.toggle('vault-secret-blur', !isBlurred);
    el.classList.toggle('vault-secret-visible', isBlurred);
    if (isBlurred) setTimeout(() => { el.classList.add('vault-secret-blur'); el.classList.remove('vault-secret-visible'); }, 20000);
}
function copy(id, btn) {
    navigator.clipboard.writeText(document.getElementById(id).textContent.trim()).then(() => {
        const orig = btn.textContent; btn.textContent='✓'; btn.style.color='#10b981';
        setTimeout(() => { btn.textContent=orig; btn.style.color=''; }, 1500);
    });
}
</script>

<?php endif; ?>
</div><!-- /.workspace -->
