<?php
// Fungsi untuk mengambil data blockchain dari endpoint
function getBlockchainData() {
    $url = 'https://blockchain.sisiteknis.com/getBlockchain';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

// Mengambil data blockchain
$blockchainData = getBlockchainData();

// Fungsi untuk mendapatkan block terbaru
function getLatestBlockNumber($blockchainData) {
    return end($blockchainData)['index'];
}

// Fungsi untuk mendapatkan detail block berdasarkan nomor
function getBlockDetails($blockchainData, $blockNumber) {
    foreach ($blockchainData as $block) {
        if ($block['index'] == $blockNumber) {
            return $block;
        }
    }
    return null;
}

// Ambil block terbaru
$latestBlockNumber = getLatestBlockNumber($blockchainData);

// Hitung total coin yang beredar
$totalCirculatingCoins = 0;

foreach ($blockchainData as $block) {
    foreach ($block['transactions'] as $transaction) {
        if ($transaction['type'] == 'coin') {
            $totalCirculatingCoins += (float) $transaction['amount'];
        }
    }
}

// Ambil 6 block terakhir untuk Latest Blocks
$blocks = [];
for ($i = $latestBlockNumber; $i > $latestBlockNumber - 6; $i--) {
    $blocks[] = getBlockDetails($blockchainData, $i);
}

// Ambil transaksi dari 6 block terakhir untuk Latest Transactions
$transactions = [];
for ($i = $latestBlockNumber; $i > $latestBlockNumber - 6; $i--) {
    $block = getBlockDetails($blockchainData, $i);
    if ($block) {
        foreach ($block['transactions'] as $transaction) {
            $transactions[] = [
                'from' => $transaction['from'],
                'to' => $transaction['to'],
                'amount' => $transaction['amount'],
                'timestamp' => $block['timestamp']
            ];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta content="width=device-width, initial-scale=1.0" name="viewport" />
    <title>EBC explore</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&amp;display=swap" rel="stylesheet" />
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            background-image: url('https://img.freepik.com/free-vector/gradient-white-monochrome-background_23-2149008074.jpg?w=1380&t=st=1729140734~exp=1729141334~hmac=ef043d9d0397da3f4cb3c362374887666419fd2a121c685c38abdff05831f9b3');
            background-size: cover;
            background-repeat: no-repeat;
            background-attachment: fixed;
        }

        .bg-pattern {
            background: #0d0d0d;
            background-image: url('https://www.bscscan.com/images/svg/components/pattern-light.svg');
        }

        #transactionModal {
            display: none;
        }

        .hidden {
            display: none;
        }

        #transactionModal.active {
            display: block;
        }

        #transactionModal.hidden {
            display: none;
        }
    </style>
</head>
<body class="bg-gray-100">
    <header class="bg-pattern text-white py-4">
        <div class="container mx-auto flex justify-between items-center">
            <div class="flex items-center"></div>
            <nav class="flex space-x-4">
                <a class="hover:underline" href="#">Home</a>
                <a class="hover:underline" href="#">Blockchain</a>
                <a class="hover:underline" href="#">Validators</a>
                <a class="hover:underline" href="#">Tokens</a>
                <a class="hover:underline" href="#">Resources</a>
                <a class="hover:underline" href="#">More</a>
                <a class="hover:underline" href="#">Sign in</a>
            </nav>
        </div>
    </header>
    <main class="container mx-auto py-6">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold">EBC explore</h2>
            <div class="flex items-center space-x-2">
                <form action="search.php" method="GET">
                    <select class="border border-gray-300 rounded px-2 py-1" name="filter">
                        <option>All Filters</option>
                    </select>
                    <input class="border border-gray-300 rounded px-2 py-1 w-96" placeholder="Search by Address / Txn Hash / Block / Token" type="text" name="txHash" />
                    <button class="bg-blue-500 text-white px-4 py-1 rounded">
                        <i class="fas fa-search"></i>
                    </button>
                </form>
            </div>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
            <div class="bg-white p-4 rounded shadow">
                <h3 class="text-lg font-bold">EBC PRICE</h3>
                <p class="text-2xl">$1.1 <span class="text-green-500">(0.20%)</span></p>
            </div>
            <div class="bg-white p-4 rounded shadow">
                <h3 class="text-lg font-bold">BLOCK</h3>
                <p class="text-2xl"><?= $latestBlockNumber ?></p>
            </div>
            <div class="bg-white p-4 rounded shadow">
                <h3 class="text-lg font-bold">TOTAL COINS IN CIRCULATION</h3>
                <p class="text-2xl"><?= number_format($totalCirculatingCoins, 2) ?> EBC</p>
            </div>
            <div class="bg-white p-4 rounded shadow">
                <h3 class="text-lg font-bold">CONNECTED PEERS</h3>
                <p class="text-2xl font-bold text-blue-600"><?= count($blockchainData) ?></p>
            </div>
        </div>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <div class="bg-white p-4 rounded shadow">
                <h3 class="text-lg font-bold mb-4">Latest Blocks</h3>
                <div class="space-y-2">
                    <?php foreach ($blocks as $block): ?>
                        <div class="flex justify-between items-center">
                            <div class="flex items-center space-x-2">
                                <div class="bg-gray-200 p-2 rounded">Bk</div>
                                <div>
                                    <p class="font-bold text-blue-600">Block #<?= $block['index'] ?></p>
                                    <p class="text-sm text-gray-800">Validated by: <span class="font-semibold"><?= $block['transactions'][0]['from'] ?></span></p>
                                    <p class="text-xs text-gray-500"><?= count($block['transactions']) ?> txns in <?= gmdate("i:s", strtotime($block['timestamp']) % 60) ?> mins</p>
                                </div>
                            </div>
                            <p class="text-sm font-semibold text-green-600">0 EBC</p>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="text-center mt-4">
                    <a class="text-blue-500 hover:underline" href="#">View all blocks</a>
                </div>
            </div>
            <div class="bg-white p-4 rounded shadow same-height">
                <h3 class="text-lg font-bold mb-4">Latest Transactions</h3>
                <div class="space-y-2">
                    <?php foreach ($transactions as $transaction): ?>
                        <div class="flex justify-between items-center cursor-pointer" onclick='openModal(<?= htmlspecialchars(json_encode($transaction), ENT_QUOTES, 'UTF-8') ?>)'>
                            <div class="flex items-center space-x-2">
                                <div class="bg-gray-200 p-2 rounded">Tx</div>
                                <div>
                                    <p class="font-bold"><?= substr($transaction['from'], 0, 10) ?>...</p>
                                    <p class="text-sm">From <?= substr($transaction['from'], 0, 10) ?>... to <?= substr($transaction['to'], 0, 10) ?>...</p>
                                    <p class="text-xs text-gray-500">At <?= date('Y-m-d H:i:s', strtotime($transaction['timestamp'])) ?></p>
                                </div>
                            </div>
                            <p class="text-sm"><?= $transaction['amount'] ?> EBC</p>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="text-center mt-4">
                    <a class="text-blue-500 hover:underline" href="#">View all transactions</a>
                </div>
            </div>
        </div>
    </main>
    <footer class="bg-pattern text-white py-6">
        <div class="container mx-auto">
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h3 class="text-lg font-bold">Powered by Engine Blockchain</h3>
                </div>
                <div class="flex space-x-4">
                    <button class="bg-gray-800 px-4 py-2 rounded">Add EBC Network</button>
                    <button class="bg-gray-800 px-4 py-2 rounded">Preferences</button>
                </div>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <h4 class="font-bold mb-2">Company</h4>
                    <ul class="space-y-1">
                        <li><a class="hover:underline" href="#">Advertise</a></li>
                        <li><a class="hover:underline" href="#">Delegate to EBC explore</a></li>
                        <li><a class="hover:underline" href="#">Contact Us</a></li>
                        <li><a class="hover:underline" href="#">Brand Assets</a></li>
                        <li><a class="hover:underline" href="#">Terms of Service</a></li>
                    </ul>
                </div>
                <div>
                    <h4 class="font-bold mb-2">Community</h4>
                    <ul class="space-y-1">
                        <li><a class="hover:underline" href="#">API Documentation</a></li>
                        <li><a class="hover:underline" href="#">Knowledge Base</a></li>
                        <li><a class="hover:underline" href="#">Network Status</a></li>
                        <li><a class="hover:underline" href="#">Learn EBC</a></li>
                    </ul>
                </div>
                <div>
                    <h4 class="font-bold mb-2">Products</h4>
                    <ul class="space-y-1">
                        <li><a class="hover:underline" href="#">Developer APIs</a></li>
                    </ul>
                </div>
            </div>
            <div class="flex justify-between items-center mt-6">
                <p>EBC explore © 2024 (EBC) | Dibuat oleh tim yang sama mengembangkan blockchain EngineBlockchain.io</p>
                <div class="flex space-x-4">
                    <a class="text-white hover:text-gray-400" href="#"><i class="fab fa-twitter"></i></a>
                    <a class="text-white hover:text-gray-400" href="#"><i class="fab fa-telegram"></i></a>
                    <a class="text-white hover:text-gray-400" href="#"><i class="fab fa-instagram"></i></a>
                    <a class="text-white hover:text-gray-400" href="#"><i class="fab fa-facebook"></i></a>
                    <a class="text-white hover:text-gray-400" href="#"><i class="fab fa-tiktok"></i></a>
                </div>
            </div>
        </div>
    </footer>
    <!-- Modal -->
    <div id="transactionModal" class="fixed z-10 inset-0 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen px-4 text-center">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            <div class="bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:max-w-lg sm:w-full">
                <div class="bg-white p-6">
                    <h3 class="text-lg leading-6 font-medium text-gray-900" id="modalTitle">Transaction Details</h3>
                    <div class="mt-4">
                        <p><strong>From:</strong> <span id="modalFrom"></span></p>
                        <p><strong>To:</strong> <span id="modalTo"></span></p>
                        <p><strong>Amount:</strong> <span id="modalAmount"></span></p>
                        <p><strong>Timestamp:</strong> <span id="modalTimestamp"></span></p>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="button" class="bg-blue-500 text-white px-4 py-2 rounded" onclick="closeModal()">Close</button>
                </div>
            </div>
        </div>
    </div>
    <script>
        function openModal(transaction) {
            console.log(transaction); // Debugging
            document.getElementById('modalFrom').textContent = transaction.from;
            document.getElementById('modalTo').textContent = transaction.to;
            document.getElementById('modalAmount').textContent = transaction.amount + ' EBC';
            document.getElementById('modalTimestamp').textContent = new Date(transaction.timestamp).toLocaleString();
            document.getElementById('transactionModal').classList.add('active');
            document.getElementById('transactionModal').classList.remove('hidden');
        }

        function closeModal() {
            document.getElementById('transactionModal').classList.add('hidden');
        }
    </script>
</body>
</html>