<?php
require_once 'config.php';
require_once 'classes/Security.php';
require_once 'classes/Wallet.php';

Security::requireAuth();

$pageTitle = 'My Wallet - CryptoExchange Pro | Secure Cryptocurrency Portfolio Management';
$pageDescription = 'Manage your cryptocurrency portfolio with our secure wallet system. View balances, transaction history, and trade cryptocurrencies safely.';

$wallet = new Wallet();
$userWallets = $wallet->getUserWallets($_SESSION['user_id']);
$transactions = $wallet->getTransactionHistory($_SESSION['user_id'], 50);

// Calculate total portfolio value
$totalValue = 0;
foreach ($userWallets as $w) {
    $totalValue += ($w['balance'] * $w['current_price']);
}

include 'includes/header.php';
?>

<main class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 py-8">
    <div class="container mx-auto px-4">
        <!-- Header Section -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-4xl font-bold text-gray-800 mb-2">
                        <i class="fas fa-wallet text-blue-600 mr-3"></i>My Wallet
                    </h1>
                    <p class="text-gray-600">Welcome back, <?php echo $_SESSION['username']; ?>! Manage your cryptocurrency portfolio</p>
                </div>
                <?php if (Security::isAdmin()): ?>
                <button onclick="openAddFundsModal()" class="bg-green-500 hover:bg-green-600 text-white px-6 py-3 rounded-lg font-semibold transition-all duration-300 transform hover:scale-105 shadow-lg">
                    <i class="fas fa-plus mr-2"></i>Add Demo Funds
                </button>
                <?php endif; ?>
            </div>
        </div>

        <!-- Portfolio Summary Cards -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-gradient-to-r from-blue-500 to-blue-600 rounded-xl p-6 text-white shadow-xl transform hover:scale-105 transition-all duration-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-blue-100 text-sm font-medium">Total Portfolio Value</p>
                        <h3 class="text-3xl font-bold">$<?php echo number_format($totalValue, 2); ?></h3>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <i class="fas fa-wallet text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-gradient-to-r from-green-500 to-green-600 rounded-xl p-6 text-white shadow-xl transform hover:scale-105 transition-all duration-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-green-100 text-sm font-medium">Active Assets</p>
                        <h3 class="text-3xl font-bold"><?php echo count(array_filter($userWallets, function($w) { return $w['balance'] > 0; })); ?></h3>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <i class="fas fa-coins text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-gradient-to-r from-yellow-500 to-orange-500 rounded-xl p-6 text-white shadow-xl transform hover:scale-105 transition-all duration-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-yellow-100 text-sm font-medium">Locked Funds</p>
                        <h3 class="text-3xl font-bold">
                            $<?php 
                            $lockedValue = 0;
                            foreach ($userWallets as $w) {
                                $lockedValue += ($w['locked_balance'] * $w['current_price']);
                            }
                            echo number_format($lockedValue, 2); 
                            ?>
                        </h3>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <i class="fas fa-lock text-2xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Wallets Table -->
        <div class="bg-white rounded-xl shadow-xl overflow-hidden mb-8">
            <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b">
                <h2 class="text-xl font-bold text-gray-800">
                    <i class="fas fa-list text-blue-600 mr-2"></i>Your Cryptocurrency Wallets
                </h2>
            </div>
            <div class="p-6">
                <?php if (!empty($userWallets)): ?>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="border-b-2 border-gray-200">
                                <th class="text-left py-4 px-4 font-semibold text-gray-700">Asset</th>
                                <th class="text-right py-4 px-4 font-semibold text-gray-700">Available Balance</th>
                                <th class="text-right py-4 px-4 font-semibold text-gray-700">Locked Balance</th>
                                <th class="text-right py-4 px-4 font-semibold text-gray-700">Current Price</th>
                                <th class="text-right py-4 px-4 font-semibold text-gray-700">Total Value</th>
                                <th class="text-center py-4 px-4 font-semibold text-gray-700">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($userWallets as $w): ?>
                            <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200">
                                <td class="py-4 px-4">
                                    <div class="flex items-center">
                                        <div class="w-10 h-10 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white font-bold mr-3">
                                            <?php echo substr($w['symbol'], 0, 1); ?>
                                        </div>
                                        <div>
                                            <div class="font-bold text-gray-800"><?php echo $w['symbol']; ?></div>
                                            <div class="text-sm text-gray-500"><?php echo $w['name']; ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td class="py-4 px-4 text-right">
                                    <div class="font-bold text-gray-800"><?php echo number_format($w['balance'], 8); ?></div>
                                    <div class="text-sm text-gray-500"><?php echo $w['symbol']; ?></div>
                                </td>
                                <td class="py-4 px-4 text-right">
                                    <div class="font-bold text-yellow-600"><?php echo number_format($w['locked_balance'], 8); ?></div>
                                    <div class="text-sm text-gray-500"><?php echo $w['symbol']; ?></div>
                                </td>
                                <td class="py-4 px-4 text-right" id="price-<?php echo $w['symbol']; ?>">
                                    <div class="font-bold text-gray-800">$<?php echo number_format($w['current_price'], 8); ?></div>
                                </td>
                                <td class="py-4 px-4 text-right">
                                    <div class="font-bold text-green-600">$<?php echo number_format(($w['balance'] + $w['locked_balance']) * $w['current_price'], 2); ?></div>
                                </td>
                                <td class="py-4 px-4 text-center">
                                    <div class="flex justify-center space-x-2">
                                        <a href="trading.php?crypto=<?php echo $w['crypto_id']; ?>" class="bg-blue-500 hover:bg-blue-600 text-white px-3 py-2 rounded-lg text-sm font-medium transition-colors duration-200">
                                            <i class="fas fa-exchange-alt mr-1"></i>Trade
                                        </a>
                                        <button class="bg-gray-400 text-white px-3 py-2 rounded-lg text-sm font-medium cursor-not-allowed" disabled>
                                            <i class="fas fa-arrow-down mr-1"></i>Deposit
                                        </button>
                                        <button class="bg-gray-400 text-white px-3 py-2 rounded-lg text-sm font-medium cursor-not-allowed" disabled>
                                            <i class="fas fa-arrow-up mr-1"></i>Withdraw
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-12">
                    <i class="fas fa-wallet text-6xl text-gray-300 mb-4"></i>
                    <h3 class="text-xl font-semibold text-gray-600 mb-2">No wallets found</h3>
                    <p class="text-gray-500">Your wallets will appear here once they are created.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Transaction History -->
        <div class="bg-white rounded-xl shadow-xl overflow-hidden">
            <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b">
                <h2 class="text-xl font-bold text-gray-800">
                    <i class="fas fa-history text-blue-600 mr-2"></i>Transaction History
                </h2>
            </div>
            <div class="p-6">
                <?php if (!empty($transactions)): ?>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="border-b-2 border-gray-200">
                                <th class="text-left py-4 px-4 font-semibold text-gray-700">Date</th>
                                <th class="text-left py-4 px-4 font-semibold text-gray-700">Type</th>
                                <th class="text-left py-4 px-4 font-semibold text-gray-700">Asset</th>
                                <th class="text-right py-4 px-4 font-semibold text-gray-700">Amount</th>
                                <th class="text-center py-4 px-4 font-semibold text-gray-700">Status</th>
                                <th class="text-left py-4 px-4 font-semibold text-gray-700">Notes</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($transactions as $tx): ?>
                            <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200">
                                <td class="py-4 px-4 text-sm text-gray-600">
                                    <?php echo date('M j, Y H:i:s', strtotime($tx['created_at'])); ?>
                                </td>
                                <td class="py-4 px-4">
                                    <?php
                                    $typeClasses = [
                                        'deposit' => 'bg-green-100 text-green-800',
                                        'withdrawal' => 'bg-red-100 text-red-800',
                                        'trade_buy' => 'bg-blue-100 text-blue-800',
                                        'trade_sell' => 'bg-yellow-100 text-yellow-800',
                                        'fee' => 'bg-gray-100 text-gray-800'
                                    ];
                                    ?>
                                    <span class="px-3 py-1 rounded-full text-xs font-medium <?php echo $typeClasses[$tx['transaction_type']] ?? 'bg-gray-100 text-gray-800'; ?>">
                                        <?php echo strtoupper(str_replace('_', ' ', $tx['transaction_type'])); ?>
                                    </span>
                                </td>
                                <td class="py-4 px-4 font-medium text-gray-800"><?php echo $tx['symbol']; ?></td>
                                <td class="py-4 px-4 text-right">
                                    <span class="font-bold <?php echo $tx['amount'] > 0 ? 'text-green-600' : 'text-red-600'; ?>">
                                        <?php echo ($tx['amount'] > 0 ? '+' : '') . number_format($tx['amount'], 8); ?>
                                    </span>
                                </td>
                                <td class="py-4 px-4 text-center">
                                    <?php
                                    $statusClasses = [
                                        'pending' => 'bg-yellow-100 text-yellow-800',
                                        'confirmed' => 'bg-green-100 text-green-800',
                                        'failed' => 'bg-red-100 text-red-800'
                                    ];
                                    ?>
                                    <span class="px-3 py-1 rounded-full text-xs font-medium <?php echo $statusClasses[$tx['status']]; ?>">
                                        <?php echo strtoupper($tx['status']); ?>
                                    </span>
                                </td>
                                <td class="py-4 px-4 text-sm text-gray-600"><?php echo $tx['notes'] ?: '-'; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-12">
                    <i class="fas fa-receipt text-6xl text-gray-300 mb-4"></i>
                    <h3 class="text-xl font-semibold text-gray-600 mb-2">No transactions yet</h3>
                    <p class="text-gray-500">Your transaction history will appear here.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

<!-- Add Funds Modal (Admin Only) -->
<?php if (Security::isAdmin()): ?>
<div id="addFundsModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-xl shadow-2xl max-w-md w-full">
            <div class="p-6">
                <h3 class="text-xl font-bold text-gray-800 mb-4">Add Demo Funds</h3>
                <form id="addFundsForm">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Cryptocurrency</label>
                        <select name="crypto_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <?php foreach ($userWallets as $w): ?>
                            <option value="<?php echo $w['crypto_id']; ?>"><?php echo $w['symbol']; ?> - <?php echo $w['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-6">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Amount</label>
                        <input type="number" name="amount" step="0.00000001" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                    </div>
                    <div class="flex space-x-3">
                        <button type="submit" class="flex-1 bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-lg font-medium transition-colors duration-200">
                            Add Funds
                        </button>
                        <button type="button" onclick="closeAddFundsModal()" class="flex-1 bg-gray-500 hover:bg-gray-600 text-white py-2 px-4 rounded-lg font-medium transition-colors duration-200">
                            Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
function openAddFundsModal() {
    document.getElementById('addFundsModal').classList.remove('hidden');
}

function closeAddFundsModal() {
    document.getElementById('addFundsModal').classList.add('hidden');
}

// Handle add funds form submission
document.getElementById('addFundsForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', 'add_funds');
    formData.append('user_id', <?php echo $_SESSION['user_id']; ?>);
    
    try {
        const response = await fetch('api/wallet.php', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('Funds added successfully!');
            location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error adding funds');
    }
    
    closeAddFundsModal();
});
</script>

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