<?php

if (!$coin) return;

$this->pageTitle = $coin->name.' address explorer';
$logo = '/vexon/ui/images/vexon-logo.png';
$address = trim((string)$address);
$remote = new WalletRPC($coin);
$validation = vexon_explorer_validate_address($remote, $address);
$isValidAddress = !!arraySafeVal($validation, 'isvalid', false);

$account = null;
try {
	$account = getdbosql('db_accounts', "username=:address", array(':address'=>$address));
} catch (Exception $e) {
	$account = null;
}

$userid = $account ? intval($account->id) : 0;
$poolAlgo = $coin->algo;
$balance = $account ? (double) objSafeVal($account, 'balance', 0) : 0;
$minPayout = $coin && $coin->payout_min ? (double)$coin->payout_min : (defined('VEXON_PAYMENTS_MINI') ? (double)VEXON_PAYMENTS_MINI : 0.001);
$activeWorkers = $userid ? intval(vexon_explorer_query_scalar(
	"SELECT COUNT(DISTINCT worker) FROM workers WHERE userid=:uid AND time>UNIX_TIMESTAMP()-900",
	array(':uid'=>$userid),
	0
)) : 0;
$lastShareTime = $userid ? intval(vexon_explorer_query_scalar(
	"SELECT MAX(time) FROM shares WHERE userid=:uid AND algo=:algo",
	array(':uid'=>$userid, ':algo'=>$poolAlgo),
	0
)) : 0;

$workers = $userid ? vexon_explorer_query_list(
	"SELECT worker, version, difficulty, time, FROM_UNIXTIME(time) AS last_seen FROM workers WHERE userid=:uid ORDER BY time DESC LIMIT 8",
	array(':uid'=>$userid)
) : array();

$shares = $userid ? vexon_explorer_query_list(
	"SELECT valid, error, COUNT(*) AS rows_count, SUM(difficulty) AS sumdiff, MIN(time) AS first_time, MAX(time) AS last_time FROM shares WHERE userid=:uid AND algo=:algo AND time>UNIX_TIMESTAMP()-86400 GROUP BY valid,error ORDER BY rows_count DESC",
	array(':uid'=>$userid, ':algo'=>$poolAlgo)
) : array();

$earnings = $userid ? vexon_explorer_query_list(
	"SELECT status, COUNT(*) AS rows_count, SUM(amount) AS amount FROM earnings WHERE userid=:uid AND coinid=:coin GROUP BY status ORDER BY status",
	array(':uid'=>$userid, ':coin'=>$coin->id)
) : array();

$payouts = $userid ? vexon_explorer_query_list(
	"SELECT amount, tx, completed, errmsg, time FROM payouts WHERE account_id=:uid ORDER BY id DESC LIMIT 10",
	array(':uid'=>$userid)
) : array();

$chainLookup = $isValidAddress ? vexon_explorer_chain_transactions($remote, $address, 20) : array('available'=>false, 'transactions'=>array());
$chainTxs = arraySafeVal($chainLookup, 'transactions', array());
$chainLookupAvailable = !!arraySafeVal($chainLookup, 'available', false);

$accepted24 = 0;
$rejected24 = 0;
$sumdiff24 = 0;
foreach($shares as $row) {
	if (intval(arraySafeVal($row, 'valid', 0)) == 1) {
		$accepted24 += intval(arraySafeVal($row, 'rows_count', 0));
		$sumdiff24 += (double) arraySafeVal($row, 'sumdiff', 0);
	} else {
		$rejected24 += intval(arraySafeVal($row, 'rows_count', 0));
	}
}

$immatureAmount = 0.0;
$matureAmount = 0.0;
$paidAmount = 0.0;
foreach($earnings as $row) {
	$status = intval(arraySafeVal($row, 'status', 0));
	$amount = (double) arraySafeVal($row, 'amount', 0);
	if ($status == 0)
		$immatureAmount += $amount;
	elseif ($status == 1)
		$matureAmount += $amount;
	else
		$paidAmount += $amount;
}

$chainReceived = 0.0;
foreach($chainTxs as $tx)
	$chainReceived += (double) arraySafeVal($tx, 'received', 0);

echo '<section class="vexon-page-title">';
echo '<div><p class="vexon-kicker">Explorer</p><h1>Address Details</h1></div>';
echo '<p>Review mining account activity, credited work, payout readiness, and chain transactions for a VEX address.</p>';
echo '</section>';

echo '<section class="vexon-telemetry-card">';
echo '<div class="vexon-card-heading"><div><span class="vexon-card-kicker">VEX Address</span><h2>'.vexon_explorer_h(vexon_explorer_short($address, 18, 12)).'</h2></div><img src="'.$logo.'" alt="Vexon"></div>';
echo '<div class="vexon-detail-grid">';
echo '<div><span>Address</span><code>'.vexon_explorer_h($address).'</code></div>';
echo '<div><span>Chain validation</span><code>'.($isValidAddress ? 'Valid VEX address' : 'Invalid or not recognized by node').'</code></div>';
echo '<div><span>Pool account</span><code>'.($account ? 'Registered miner account #'.$userid : 'Not registered yet').'</code></div>';
echo '<div><span>Chain transaction index</span><code>'.($chainLookupAvailable ? 'Available from node RPC' : 'Not available from node RPC yet').'</code></div>';
echo '</div>';
echo '<div class="vexon-metric-grid vexon-metric-grid-five">';
echo '<div><span>Pool balance</span><strong>'.vexon_explorer_amount($balance, 8).' VEX</strong></div>';
echo '<div><span>Minimum payout</span><strong>'.vexon_explorer_amount($minPayout, 8).' VEX</strong></div>';
echo '<div><span>Active workers</span><strong>'.$activeWorkers.'</strong><em>15 minutes</em></div>';
echo '<div><span>Accepted shares</span><strong>'.$accepted24.'</strong><em>24 hours</em></div>';
echo '<div><span>Chain received</span><strong>'.($chainLookupAvailable ? vexon_explorer_amount($chainReceived, 8).' VEX' : 'Waiting').'</strong></div>';
	echo '</div>';

if (!$isValidAddress)
	echo '<div class="vexon-empty-state">This address does not pass Vexon node validation. Check the address before mining or receiving payments.</div>';
if (!$account)
	echo '<div class="vexon-empty-state">This address has not connected to Vexon Pool yet. Start mining with <code>'.vexon_explorer_h($address).'.worker</code> to create the account automatically.</div>';
echo '</section>';

echo '<section class="vexon-explorer-grid">';
echo '<div class="vexon-telemetry-card">';
echo '<div class="vexon-card-heading"><div><span class="vexon-card-kicker">Mining</span><h2>Workers</h2></div><img src="'.$logo.'" alt="Vexon"></div>';
if (!count($workers)) {
	echo '<div class="vexon-empty-state">No worker records yet.</div>';
} else {
	echo '<div class="vexon-table-scroll"><table class="vexon-stat-table vexon-explorer-table"><thead><tr><th>Worker</th><th>Version</th><th>Difficulty</th><th>Last seen</th></tr></thead><tbody>';
	foreach($workers as $worker) {
		echo '<tr>';
		echo '<td>'.vexon_explorer_h(arraySafeVal($worker, 'worker', 'default')).'</td>';
		echo '<td>'.vexon_explorer_h(arraySafeVal($worker, 'version', 'Unknown')).'</td>';
		echo '<td>'.vexon_explorer_h(arraySafeVal($worker, 'difficulty', 0)).'</td>';
		echo '<td>'.vexon_explorer_h(arraySafeVal($worker, 'last_seen', '')).'</td>';
		echo '</tr>';
	}
echo '</tbody></table></div>';
}
	echo '</div>';

	echo '<div class="vexon-telemetry-card">';
echo '<div class="vexon-card-heading"><div><span class="vexon-card-kicker">Shares</span><h2>Share Summary</h2></div><img src="'.$logo.'" alt="Vexon"></div>';
if (!count($shares)) {
	echo '<div class="vexon-empty-state">No share rows in the last 24 hours.</div>';
} else {
	echo '<div class="vexon-table-scroll"><table class="vexon-stat-table vexon-explorer-table"><thead><tr><th>Status</th><th>Rows</th><th>Difficulty</th><th>First</th><th>Last</th></tr></thead><tbody>';
	foreach($shares as $row) {
		$isValid = intval(arraySafeVal($row, 'valid', 0)) == 1;
		echo '<tr>';
		echo '<td><span class="vexon-status-pill">'.($isValid ? 'Accepted' : 'Rejected').'</span></td>';
		echo '<td>'.intval(arraySafeVal($row, 'rows_count', 0)).'</td>';
		echo '<td>'.vexon_explorer_h(vexon_explorer_metric(arraySafeVal($row, 'sumdiff', 0), 3)).'</td>';
		echo '<td>'.vexon_explorer_h(vexon_explorer_time(arraySafeVal($row, 'first_time', 0))).'</td>';
		echo '<td>'.vexon_explorer_h(vexon_explorer_time(arraySafeVal($row, 'last_time', 0))).'</td>';
		echo '</tr>';
	}
	echo '</tbody></table></div>';
}
echo '<p class="vexon-muted">Last share: '.vexon_explorer_h(vexon_explorer_time($lastShareTime)).'</p>';
echo '</div>';
echo '</section>';

echo '<section class="vexon-explorer-grid">';
echo '<div class="vexon-telemetry-card">';
echo '<div class="vexon-card-heading"><div><span class="vexon-card-kicker">Accounting</span><h2>Reward Lifecycle</h2></div><img src="'.$logo.'" alt="Vexon"></div>';
echo '<div class="vexon-metric-grid">';
echo '<div><span>Immature</span><strong>'.vexon_explorer_amount($immatureAmount, 8).' VEX</strong></div>';
echo '<div><span>Mature</span><strong>'.vexon_explorer_amount($matureAmount, 8).' VEX</strong></div>';
echo '<div><span>Paid/closed</span><strong>'.vexon_explorer_amount($paidAmount, 8).' VEX</strong></div>';
echo '</div>';
if (!count($earnings)) {
	echo '<div class="vexon-empty-state">No block earnings have been credited yet. Earnings begin after the pool finds a block.</div>';
} else {
	echo '<div class="vexon-table-scroll"><table class="vexon-stat-table vexon-explorer-table"><thead><tr><th>Status</th><th>Rows</th><th>Amount</th></tr></thead><tbody>';
	foreach($earnings as $row) {
		$status = intval(arraySafeVal($row, 'status', 0));
		$statusText = $status == 0 ? 'Immature' : ($status == 1 ? 'Mature' : 'Paid/closed');
		echo '<tr>';
		echo '<td><span class="vexon-status-pill">'.vexon_explorer_h($statusText).'</span></td>';
		echo '<td>'.intval(arraySafeVal($row, 'rows_count', 0)).'</td>';
		echo '<td>'.vexon_explorer_amount(arraySafeVal($row, 'amount', 0), 8).' VEX</td>';
		echo '</tr>';
	}
	echo '</tbody></table></div>';
}
echo '</div>';

echo '<div class="vexon-telemetry-card">';
echo '<div class="vexon-card-heading"><div><span class="vexon-card-kicker">Payouts</span><h2>Pool Payments</h2></div><img src="'.$logo.'" alt="Vexon"></div>';
if (!count($payouts)) {
	echo '<div class="vexon-empty-state">No payout rows yet. Payouts run daily at 08:00 CST when mature balance is at least '.vexon_explorer_amount($minPayout, 8).' VEX.</div>';
} else {
	echo '<div class="vexon-table-scroll"><table class="vexon-stat-table vexon-explorer-table"><thead><tr><th>Amount</th><th>Status</th><th>Time</th><th>Transaction</th></tr></thead><tbody>';
	foreach($payouts as $row) {
		$tx = arraySafeVal($row, 'tx', '');
		$completed = intval(arraySafeVal($row, 'completed', 0));
		$errmsg = arraySafeVal($row, 'errmsg', '');
		$status = $completed ? 'Completed' : ($errmsg ? 'Failed' : 'Queued');
		echo '<tr>';
		echo '<td>'.vexon_explorer_amount(arraySafeVal($row, 'amount', 0), 8).' VEX</td>';
		echo '<td><span class="vexon-status-pill">'.vexon_explorer_h($status).'</span></td>';
		echo '<td>'.vexon_explorer_h(vexon_explorer_time(arraySafeVal($row, 'time', 0))).'</td>';
		echo '<td>'.($tx ? '<a class="vexon-hash" href="/explorer?txid='.vexon_explorer_h($tx).'">'.vexon_explorer_h(vexon_explorer_short($tx, 16, 10)).'</a>' : 'Pending').'</td>';
		echo '</tr>';
	}
	echo '</tbody></table></div>';
}
echo '</div>';
echo '</section>';

echo '<section class="vexon-telemetry-card">';
echo '<div class="vexon-card-heading"><div><span class="vexon-card-kicker">Chain</span><h2>Address Transactions</h2></div><img src="'.$logo.'" alt="Vexon"></div>';
if (!$isValidAddress) {
	echo '<div class="vexon-empty-state">Chain transaction lookup was skipped because the address is not valid.</div>';
} elseif (!$chainLookupAvailable) {
	echo '<div class="vexon-empty-state">Address transaction lookup is not available from the local node yet. Enable address indexing/searchrawtransactions to expose full chain history.</div>';
} elseif (!count($chainTxs)) {
	echo '<div class="vexon-empty-state">No chain transactions were returned for this address.</div>';
} else {
	echo '<div class="vexon-table-scroll"><table class="vexon-stat-table vexon-explorer-table"><thead><tr><th>Transaction</th><th>Received</th><th>Confirmations</th><th>Time</th><th>Block</th></tr></thead><tbody>';
	foreach($chainTxs as $tx) {
		$txid = arraySafeVal($tx, 'txid', '');
		$blockHash = arraySafeVal($tx, 'blockhash', '');
		echo '<tr>';
		echo '<td><a class="vexon-hash" href="/explorer?txid='.vexon_explorer_h($txid).'">'.vexon_explorer_h(vexon_explorer_short($txid, 18, 10)).'</a></td>';
		echo '<td>'.vexon_explorer_amount(arraySafeVal($tx, 'received', 0), 8).' VEX</td>';
		echo '<td>'.intval(arraySafeVal($tx, 'confirmations', 0)).'</td>';
		echo '<td>'.vexon_explorer_h(vexon_explorer_time(arraySafeVal($tx, 'time', arraySafeVal($tx, 'blocktime', 0)))).'</td>';
		echo '<td>'.($blockHash ? '<a class="vexon-hash" href="/explorer?hash='.vexon_explorer_h($blockHash).'">'.vexon_explorer_h(vexon_explorer_short($blockHash, 14, 8)).'</a>' : 'Mempool').'</td>';
		echo '</tr>';
	}
	echo '</tbody></table></div>';
}
echo '</section>';
