<?php
session_start();
require_once 'includes/auth_check.php';
require_once '../config/database.php';

$page = 'deposit_history';
$database = new Database();
$db = $database->getConnection();

// Check if crypto_deposits table exists
$stmt = $db->prepare("
    SELECT COUNT(*) 
    FROM information_schema.tables 
    WHERE table_schema = DATABASE() 
    AND table_name = 'crypto_deposits'
");
$stmt->execute();
$depositsTableExists = $stmt->fetchColumn();

// Get all user's deposits
$deposits = [];
if ($depositsTableExists) {
    try {
        $stmt = $db->prepare("SELECT * FROM crypto_deposits WHERE user_id = ? ORDER BY created_at DESC");
        $stmt->execute([$_SESSION['user_id']]);
        $deposits = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("Error fetching deposit history: " . $e->getMessage());
    }
}

// Calculate totals
$totalDeposited = 0;
$totalApproved = 0;
$totalPending = 0;
$totalRejected = 0;

$btcDeposited = 0;
$usdtDeposited = 0;

foreach ($deposits as $deposit) {
    if ($deposit['status'] === 'approved') {
        $totalApproved += $deposit['amount'];
        
        if ($deposit['currency'] === 'BTC') {
            $btcDeposited += $deposit['amount'];
        } elseif ($deposit['currency'] === 'USDT') {
            $usdtDeposited += $deposit['amount'];
        }
    } elseif ($deposit['status'] === 'pending') {
        $totalPending += $deposit['amount'];
    } elseif ($deposit['status'] === 'rejected') {
        $totalRejected += $deposit['amount'];
    }
    
    $totalDeposited += $deposit['amount'];
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* Base Styles */
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --primary-dark: #4338ca;
    --success-color: #10b981;
    --success-light: #ecfdf5;
    --danger-color: #ef4444;
    --danger-light: #fef2f2;
    --warning-color: #f59e0b;
    --warning-light: #fffbeb;
    --info-color: #0ea5e9;
    --info-light: #e0f9ff;
    --dark-color: #1e293b;
    --light-color: #f8fafc;
    --gray-color: #64748b;
    --border-color: #e5e7eb;
    --animation-speed: 0.5s;
}

/* Animation Keyframes */
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes slideInRight {
    from {
        opacity: 0;
        transform: translateX(20px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

/* Animated Elements */
.fade-in {
    animation: fadeIn var(--animation-speed) ease forwards;
}

.slide-up {
    animation: slideInUp var(--animation-speed) ease forwards;
}

.slide-right {
    animation: slideInRight var(--animation-speed) ease forwards;
}

.staggered-item {
    opacity: 0;
}

/* Card Styles with Animation */
.dashboard-card {
    background: white;
    border-radius: 15px;
    border: none;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 1.5rem;
    transition: all 0.3s ease;
    overflow: hidden;
    position: relative;
}

.dashboard-card:hover {
    box-shadow: 0 15px 30px -10px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1);
    transform: translateY(-5px);
}

.card-header {
    background: none;
    padding: 1.25rem;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    z-index: 2;
}

.card-header::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 0;
    height: 2px;
    background: var(--primary-color);
    transition: width 0.3s ease;
    z-index: 3;
}

.dashboard-card:hover .card-header::after {
    width: 100%;
}

.card-title {
    margin-bottom: 0;
    font-size: 1.1rem;
    font-weight: 600;
    display: flex;
    align-items: center;
}

.card-title i {
    margin-right: 0.5rem;
    font-size: 1.25rem;
    color: var(--primary-color);
}

.card-body {
    padding: 1.5rem;
    position: relative;
    z-index: 1;
}

/* Stats Card */
.stats-card {
    border-radius: 15px;
    padding: 1.5rem;
    height: 100%;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.stats-card::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
    transform: rotate(30deg);
    z-index: 1;
}

.stats-card .stats-icon {
    font-size: 2rem;
    margin-bottom: 1rem;
    position: relative;
    z-index: 2;
}

.stats-card .stats-value {
    font-size: 1.75rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
    position: relative;
    z-index: 2;
}

.stats-card .stats-label {
    font-size: 0.875rem;
    color: rgba(255, 255, 255, 0.8);
    position: relative;
    z-index: 2;
}

.stats-card.primary {
    background: linear-gradient(135deg, #4f46e5, #818cf8);
    color: white;
}

.stats-card.success {
    background: linear-gradient(135deg, #10b981, #34d399);
    color: white;
}

.stats-card.warning {
    background: linear-gradient(135deg, #f59e0b, #fbbf24);
    color: white;
}

.stats-card.danger {
    background: linear-gradient(135deg, #ef4444, #f87171);
    color: white;
}

/* Table Styles */
.table {
    margin-bottom: 0;
}

.table th {
    border-top: none;
    font-weight: 600;
    color: var(--gray-color);
    text-transform: uppercase;
    font-size: 0.75rem;
    letter-spacing: 0.05em;
}

.table td {
    vertical-align: middle;
}

.transaction-item {
    transition: all 0.3s ease;
}

.transaction-item:hover {
    background-color: var(--light-color);
    transform: translateX(5px);
}

/* Badge Styles */
.badge {
    font-weight: 500;
    padding: 0.35em 0.65em;
    border-radius: 0.375rem;
}

.badge-light {
    background-color: var(--light-color);
    color: var(--dark-color);
}

/* Empty States with Animation */
.empty-state {
    text-align: center;
    padding: 2rem 1rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
}

.empty-state-icon {
    font-size: 2.5rem;
    color: #d1d5db;
    margin-bottom: 0.5rem;
    transition: all 0.3s ease;
}

.empty-state:hover .empty-state-icon {
    transform: scale(1.1);
    color: var(--primary-color);
}

.empty-state-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.empty-state-text {
    color: var(--gray-color);
    margin-bottom: 1rem;
    font-size: 0.875rem;
}

/* Filter Styles */
.filter-btn {
    border-radius: 0.5rem;
    padding: 0.5rem 1rem;
    font-weight: 500;
    transition: all 0.3s ease;
    background-color: var(--light-color);
    border: none;
    color: var(--dark-color);
}

.filter-btn:hover, .filter-btn.active {
    background-color: var(--primary-color);
    color: white;
}

/* Background Colors */
.bg-primary-light { background-color: rgba(79, 70, 229, 0.1); }
.bg-success-light { background-color: rgba(16, 185, 129, 0.1); }
.bg-warning-light { background-color: rgba(245, 158, 11, 0.1); }
.bg-danger-light { background-color: rgba(239, 68, 68, 0.1); }
.bg-info-light { background-color: rgba(14, 165, 233, 0.1); }

/* Text Colors */
.text-primary { color: var(--primary-color) !important; }
.text-success { color: var(--success-color) !important; }
.text-warning { color: var(--warning-color) !important; }
.text-danger { color: var(--danger-color) !important; }
.text-info { color: var(--info-color) !important; }

/* Tooltip Animation */
.tooltip {
    opacity: 0;
    transition: opacity 0.3s ease;
}

.tooltip.show {
    opacity: 1;
}

/* Transaction Details */
.transaction-details {
    background-color: var(--light-color);
    border-radius: 0.5rem;
    padding: 1rem;
    margin-top: 0.5rem;
    display: none;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
}

.detail-label {
    font-weight: 500;
    color: var(--gray-color);
}

.detail-value {
    font-weight: 500;
}

/* Pagination Styles */
.pagination {
    margin-bottom: 0;
}

.page-link {
    color: var(--primary-color);
    border-radius: 0.375rem;
    margin: 0 0.25rem;
    border: none;
    transition: all 0.3s ease;
}

.page-link:hover {
    background-color: var(--primary-light);
    color: var(--primary-color);
    transform: translateY(-2px);
}

.page-item.active .page-link {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

/* Search Box */
.search-box {
    position: relative;
}

.search-box .form-control {
    padding-left: 2.5rem;
    border-radius: 0.5rem;
    border: 1px solid var(--border-color);
}

.search-box .search-icon {
    position: absolute;
    left: 1rem;
    top: 50%;
    transform: translateY(-50%);
    color: var(--gray-color);
}
</style>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-4 fade-in">
            <div>
                <h1 class="h3 mb-1">Deposit History</h1>
                <p class="text-muted mb-0">View all your cryptocurrency deposit transactions</p>
            </div>
            <a href="deposit.php" class="btn btn-primary">
                <i class='bx bx-plus me-1'></i> New Deposit
            </a>
        </div>

        <!-- Stats Cards -->
        <div class="row mb-4">
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="stats-card primary slide-up" style="animation-delay: 0.1s;">
                    <div class="stats-icon">
                        <i class='bx bx-coin-stack'></i>
                    </div>
                    <div class="stats-value"><?php echo number_format($totalDeposited, 8); ?></div>
                    <div class="stats-label">Total Deposited</div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="stats-card success slide-up" style="animation-delay: 0.2s;">
                    <div class="stats-icon">
                        <i class='bx bx-check-circle'></i>
                    </div>
                    <div class="stats-value"><?php echo number_format($totalApproved, 8); ?></div>
                    <div class="stats-label">Total Approved</div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="stats-card warning slide-up" style="animation-delay: 0.3s;">
                    <div class="stats-icon">
                        <i class='bx bx-time'></i>
                    </div>
                    <div class="stats-value"><?php echo number_format($totalPending, 8); ?></div>
                    <div class="stats-label">Total Pending</div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="stats-card danger slide-up" style="animation-delay: 0.4s;">
                    <div class="stats-icon">
                        <i class='bx bx-x-circle'></i>
                    </div>
                    <div class="stats-value"><?php echo number_format($totalRejected, 8); ?></div>
                    <div class="stats-label">Total Rejected</div>
                </div>
            </div>
        </div>

        <!-- Currency Stats -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="dashboard-card slide-up" style="animation-delay: 0.5s;">
                    <div class="card-header">
                        <h5 class="card-title"><i class='bx bxl-bitcoin'></i> BTC Deposits</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h3 class="mb-1"><?php echo number_format($btcDeposited, 8); ?> BTC</h3>
                                <p class="text-muted mb-0">Total BTC Deposited</p>
                            </div>
                            <div class="bg-warning-light text-warning p-3 rounded-circle">
                                <i class='bx bxl-bitcoin fs-1'></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="dashboard-card slide-up" style="animation-delay: 0.6s;">
                    <div class="card-header">
                        <h5 class="card-title"><i class='bx bx-dollar-circle'></i> USDT Deposits</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h3 class="mb-1"><?php echo number_format($usdtDeposited, 2); ?> USDT</h3>
                                <p class="text-muted mb-0">Total USDT Deposited</p>
                            </div>
                            <div class="bg-success-light text-success p-3 rounded-circle">
                                <i class='bx bx-dollar-circle fs-1'></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Deposit History Card -->
        <div class="dashboard-card slide-up" style="animation-delay: 0.7s;">
            <div class="card-header">
                <h5 class="card-title"><i class='bx bx-history'></i> Deposit History</h5>
                <div class="d-flex">
                    <div class="btn-group me-2">
                        <button type="button" class="filter-btn active" data-filter="all">All</button>
                        <button type="button" class="filter-btn" data-filter="pending">Pending</button>
                        <button type="button" class="filter-btn" data-filter="approved">Approved</button>
                        <button type="button" class="filter-btn" data-filter="rejected">Rejected</button>
                    </div>
                    <div class="search-box">
                        <i class='bx bx-search search-icon'></i>
                        <input type="text" class="form-control" id="searchInput" placeholder="Search...">
                    </div>
                </div>
            </div>
            <div class="card-body p-0">
                <?php if (empty($deposits)): ?>
                    <div class="empty-state" style="height: 300px;">
                        <i class='bx bx-coin-stack empty-state-icon'></i>
                        <h5 class="empty-state-title">No Deposits Found</h5>
                        <p class="empty-state-text">You haven't made any cryptocurrency deposits yet.</p>
                        <a href="deposit.php" class="btn btn-primary">
                            <i class='bx bx-plus me-1'></i> Make a Deposit
                        </a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover" id="depositsTable">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Currency</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Transaction Hash</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($deposits as $index => $deposit): ?>
                                    <tr class="transaction-item staggered-item" data-index="<?php echo $index; ?>" data-status="<?php echo $deposit['status']; ?>">
                                        <td><?php echo date('M d, Y H:i', strtotime($deposit['created_at'])); ?></td>
                                        <td>
                                            <?php if ($deposit['currency'] === 'BTC'): ?>
                                                <i class='bx bxl-bitcoin text-warning me-1'></i>
                                            <?php elseif ($deposit['currency'] === 'USDT'): ?>
                                                <i class='bx bx-dollar-circle text-success me-1'></i>
                                            <?php endif; ?>
                                            <?php echo htmlspecialchars($deposit['currency']); ?>
                                            <?php if ($deposit['network']): ?>
                                                <span class="badge badge-light"><?php echo htmlspecialchars($deposit['network']); ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo number_format($deposit['amount'], 8); ?></td>
                                        <td>
                                            <?php if ($deposit['status'] === 'pending'): ?>
                                                <span class="badge bg-warning">Pending</span>
                                            <?php elseif ($deposit['status'] === 'approved'): ?>
                                                <span class="badge bg-success">Approved</span>
                                            <?php elseif ($deposit['status'] === 'rejected'): ?>
                                                <span class="badge bg-danger">Rejected</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="text-monospace text-truncate d-inline-block" style="max-width: 150px;"><?php echo htmlspecialchars($deposit['transaction_hash']); ?></span>
                                            <button class="btn btn-sm btn-link p-0 ms-2 copy-hash" data-hash="<?php echo htmlspecialchars($deposit['transaction_hash']); ?>" data-bs-toggle="tooltip" title="Copy Hash">
                                                <i class='bx bx-copy'></i>
                                            </button>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-info view-details" data-id="<?php echo $deposit['id']; ?>">
                                                <i class='bx bx-detail'></i> Details
                                            </button>
                                            <?php if ($deposit['status'] === 'rejected' && !empty($deposit['admin_notes'])): ?>
                                                <button class="btn btn-sm btn-outline-danger ms-1 view-notes" data-notes="<?php echo htmlspecialchars($deposit['admin_notes']); ?>">
                                                    <i class='bx bx-message-square-detail'></i>
                                                </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <tr class="transaction-details-row" id="details-<?php echo $deposit['id']; ?>" style="display: none;">
                                        <td colspan="6">
                                            <div class="transaction-details">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="detail-row">
                                                            <div class="detail-label">Transaction ID:</div>
                                                            <div class="detail-value"><?php echo $deposit['id']; ?></div>
                                                        </div>
                                                        <div class="detail-row">
                                                            <div class="detail-label">Date Submitted:</div>
                                                            <div class="detail-value"><?php echo date('M d, Y H:i:s', strtotime($deposit['created_at'])); ?></div>
                                                        </div>
                                                        <div class="detail-row">
                                                            <div class="detail-label">Last Updated:</div>
                                                            <div class="detail-value"><?php echo date('M d, Y H:i:s', strtotime($deposit['updated_at'])); ?></div>
                                                        </div>
                                                        <div class="detail-row">
                                                            <div class="detail-label">Currency:</div>
                                                            <div class="detail-value"><?php echo htmlspecialchars($deposit['currency']); ?></div>
                                                        </div>
                                                        <?php if ($deposit['network']): ?>
                                                        <div class="detail-row">
                                                            <div class="detail-label">Network:</div>
                                                            <div class="detail-value"><?php echo htmlspecialchars($deposit['network']); ?></div>
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="detail-row">
                                                            <div class="detail-label">Amount:</div>
                                                            <div class="detail-value"><?php echo number_format($deposit['amount'], 8); ?> <?php echo htmlspecialchars($deposit['currency']); ?></div>
                                                        </div>
                                                        <div class="detail-row">
                                                            <div class="detail-label">Status:</div>
                                                            <div class="detail-value">
                                                                <?php if ($deposit['status'] === 'pending'): ?>
                                                                    <span class="badge bg-warning">Pending</span>
                                                                <?php elseif ($deposit['status'] === 'approved'): ?>
                                                                    <span class="badge bg-success">Approved</span>
                                                                <?php elseif ($deposit['status'] === 'rejected'): ?>
                                                                    <span class="badge bg-danger">Rejected</span>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                        <div class="detail-row">
                                                            <div class="detail-label">Wallet Address:</div>
                                                            <div class="detail-value text-truncate" style="max-width: 200px;"><?php echo htmlspecialchars($deposit['wallet_address']); ?></div>
                                                        </div>
                                                        <div class="detail-row">
                                                            <div class="detail-label">Transaction Hash:</div>
                                                            <div class="detail-value text-truncate" style="max-width: 200px;"><?php echo htmlspecialchars($deposit['transaction_hash']); ?></div>
                                                        </div>
                                                        <?php if (!empty($deposit['admin_notes'])): ?>
                                                        <div class="detail-row">
                                                            <div class="detail-label">Admin Notes:</div>
                                                            <div class="detail-value"><?php echo htmlspecialchars($deposit['admin_notes']); ?></div>
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <?php if (!empty($deposit['screenshot'])): ?>
                                                <div class="mt-3">
                                                    <h6 class="mb-2">Proof of Payment:</h6>
                                                    <div class="text-center">
                                                        <img src="../uploads/deposit_proofs/<?php echo htmlspecialchars($deposit['screenshot']); ?>" alt="Proof of Payment" class="img-fluid img-thumbnail" style="max-height: 200px;">
                                                    </div>
                                                </div>
                                                <?php endif; ?>
                                                <?php if ($deposit['currency'] === 'BTC'): ?>
                                                <div class="mt-3 text-center">
                                                    <a href="https://www.blockchain.com/btc/tx/<?php echo htmlspecialchars($deposit['transaction_hash']); ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                                        <i class='bx bx-link-external me-1'></i> View on Blockchain Explorer
                                                    </a>
                                                </div>
                                                <?php elseif ($deposit['currency'] === 'USDT'): ?>
                                                <div class="mt-3 text-center">
                                                    <?php
                                                    $explorerUrl = '#';
                                                    if ($deposit['network'] === 'TRC20') {
                                                        $explorerUrl = 'https://tronscan.org/#/transaction/' . $deposit['transaction_hash'];
                                                    } elseif ($deposit['network'] === 'ERC20') {
                                                        $explorerUrl = 'https://etherscan.io/tx/' . $deposit['transaction_hash'];
                                                    } elseif ($deposit['network'] === 'BEP20') {
                                                        $explorerUrl = 'https://bscscan.com/tx/' . $deposit['transaction_hash'];
                                                    }
                                                    ?>
                                                    <a href="<?php echo $explorerUrl; ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                                        <i class='bx bx-link-external me-1'></i> View on Blockchain Explorer
                                                    </a>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Notes Modal -->
<div class="modal fade" id="notesModal" tabindex="-1" aria-labelledby="notesModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="notesModalLabel">Admin Notes</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger">
                    <i class='bx bx-info-circle me-2'></i>
                    <span id="notesContent"></span>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // Copy transaction hash to clipboard
    document.querySelectorAll('.copy-hash').forEach(button => {
        button.addEventListener('click', function() {
            const hash = this.dataset.hash;
            navigator.clipboard.writeText(hash).then(() => {
                // Show tooltip
                const tooltip = bootstrap.Tooltip.getInstance(this);
                tooltip.setContent({ '.tooltip-inner': 'Copied!' });
                
                // Reset tooltip after 2 seconds
                setTimeout(() => {
                    tooltip.setContent({ '.tooltip-inner': 'Copy Hash' });
                }, 2000);
            });
        });
    });
    
    // View transaction details
    document.querySelectorAll('.view-details').forEach(button => {
        button.addEventListener('click', function() {
            const id = this.dataset.id;
            const detailsRow = document.getElementById('details-' + id);
            
            // Close all other open details
            document.querySelectorAll('.transaction-details-row').forEach(row => {
                if (row.id !== 'details-' + id && row.style.display !== 'none') {
                    row.style.display = 'none';
                }
            });
            
            // Toggle this details row
            if (detailsRow.style.display === 'none') {
                detailsRow.style.display = 'table-row';
                
                // Add animation
                const detailsContent = detailsRow.querySelector('.transaction-details');
                detailsContent.style.animation = 'slideInUp 0.3s ease forwards';
            } else {
                detailsRow.style.display = 'none';
            }
        });
    });
    
    // View admin notes
    document.querySelectorAll('.view-notes').forEach(button => {
        button.addEventListener('click', function() {
            const notes = this.dataset.notes;
            document.getElementById('notesContent').textContent = notes;
            
            // Show modal
            const notesModal = new bootstrap.Modal(document.getElementById('notesModal'));
            notesModal.show();
        });
    });
    
    // Filter deposits by status
    document.querySelectorAll('.filter-btn').forEach(button => {
        button.addEventListener('click', function() {
            // Remove active class from all buttons
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // Add active class to clicked button
            this.classList.add('active');
            
            const filter = this.dataset.filter;
            const rows = document.querySelectorAll('.transaction-item');
            
            rows.forEach(row => {
                if (filter === 'all' || row.dataset.status === filter) {
                    row.style.display = 'table-row';
                } else {
                    row.style.display = 'none';
                    
                    // Hide details row if it's open
                    const id = row.querySelector('.view-details').dataset.id;
                    const detailsRow = document.getElementById('details-' + id);
                    if (detailsRow) {
                        detailsRow.style.display = 'none';
                    }
                }
            });
        });
    });
    
    // Search functionality
    document.getElementById('searchInput').addEventListener('keyup', function() {
        const searchValue = this.value.toLowerCase();
        const rows = document.querySelectorAll('.transaction-item');
        
        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            if (text.includes(searchValue)) {
                row.style.display = 'table-row';
            } else {
                row.style.display = 'none';
                
                // Hide details row if it's open
                const id = row.querySelector('.view-details').dataset.id;
                const detailsRow = document.getElementById('details-' + id);
                if (detailsRow) {
                    detailsRow.style.display = 'none';
                }
            }
        });
    });
    
    // Staggered animations for items
    const staggeredItems = document.querySelectorAll('.staggered-item');
    staggeredItems.forEach((item, index) => {
        setTimeout(() => {
            item.style.opacity = '1';
            item.style.animation = 'slideInRight 0.5s ease forwards';
        }, 300 + (index * 50));
    });
    
    // Add hover effects to cards
    const cards = document.querySelectorAll('.dashboard-card');
    cards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 15px 30px -10px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = '';
            this.style.boxShadow = '';
        });
    });
    
    // Add hover effects to stats cards
    const statsCards = document.querySelectorAll('.stats-card');
    statsCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 15px 30px -10px rgba(0,0,0,0.2), 0 4px 6px -4px rgba(0,0,0,0.1)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = '';
            this.style.boxShadow = '';
        });
    });
    
    // Animated counters for stats
    const animateValue = (element, start, end, duration) => {
        if (start === end) return;
        
        let startTimestamp = null;
        const step = (timestamp) => {
            if (!startTimestamp) startTimestamp = timestamp;
            const progress = Math.min((timestamp - startTimestamp) / duration, 1);
            const value = progress * (end - start) + start;
            
            // Format the number with appropriate decimal places
            const decimals = element.textContent.includes('.') ? 
                (element.textContent.split('.')[1] || '').length : 
                (end.toString().includes('.') ? end.toString().split('.')[1].length : 0);
            
            element.textContent = value.toFixed(decimals);
            
            if (progress < 1) {
                window.requestAnimationFrame(step);
            }
        };
        window.requestAnimationFrame(step);
    };
    
    // Animate all stats values
    document.querySelectorAll('.stats-value').forEach(element => {
        const value = parseFloat(element.textContent.replace(/,/g, ''));
        const originalText = element.textContent;
        const hasCurrency = originalText.includes('BTC') || originalText.includes('USDT');
        
        // Store original text to restore currency symbol if present
        const currencySymbol = hasCurrency ? 
            originalText.replace(/[\d,\.]/g, '').trim() : 
            '';
        
        element.textContent = '0';
        
        // Animate the value
        animateValue(element, 0, value, 1500);
        
        // If there was a currency symbol, add it back after animation
        if (hasCurrency) {
            setTimeout(() => {
                element.textContent = element.textContent + ' ' + currencySymbol;
            }, 1500);
        }
    });
    
    // Export to CSV functionality
    document.getElementById('exportCSV')?.addEventListener('click', function() {
        // Get visible rows only (respecting filters)
        const visibleRows = Array.from(document.querySelectorAll('.transaction-item'))
            .filter(row => row.style.display !== 'none');
        
        if (visibleRows.length === 0) {
            alert('No data to export.');
            return;
        }
        
        // Create CSV content
        let csvContent = 'Date,Currency,Network,Amount,Status,Transaction Hash\n';
        
        visibleRows.forEach(row => {
            const cells = row.querySelectorAll('td');
            const date = cells[0].textContent.trim();
            
            // Get currency and network
            const currencyCell = cells[1];
            const currency = currencyCell.textContent.trim().split(' ')[0];
            const networkBadge = currencyCell.querySelector('.badge');
            const network = networkBadge ? networkBadge.textContent.trim() : '';
            
            const amount = cells[2].textContent.trim();
            
            // Get status without the badge styling
            const statusCell = cells[3];
            const status = statusCell.textContent.trim();
            
            // Get transaction hash without the copy button
            const hashCell = cells[4];
            const hash = hashCell.querySelector('.text-monospace').textContent.trim();
            
            // Add row to CSV
            csvContent += `"${date}","${currency}","${network}","${amount}","${status}","${hash}"\n`;
        });
        
        // Create download link
        const encodedUri = encodeURI('data:text/csv;charset=utf-8,' + csvContent);
        const link = document.createElement('a');
        link.setAttribute('href', encodedUri);
        link.setAttribute('download', 'deposit_history.csv');
        document.body.appendChild(link);
        
        // Trigger download and remove link
        link.click();
        document.body.removeChild(link);
    });
    
    // Print functionality
    document.getElementById('printHistory')?.addEventListener('click', function() {
        window.print();
    });
    
    // Handle date range filter if present
    const dateRangeFilter = document.getElementById('dateRangeFilter');
    if (dateRangeFilter) {
        dateRangeFilter.addEventListener('change', function() {
            const range = this.value;
            const today = new Date();
            let startDate = new Date();
            
            // Calculate start date based on selected range
            switch (range) {
                case 'today':
                    startDate.setHours(0, 0, 0, 0);
                    break;
                case 'yesterday':
                    startDate.setDate(today.getDate() - 1);
                    startDate.setHours(0, 0, 0, 0);
                    break;
                case 'week':
                    startDate.setDate(today.getDate() - 7);
                    break;
                case 'month':
                    startDate.setMonth(today.getMonth() - 1);
                    break;
                case 'year':
                    startDate.setFullYear(today.getFullYear() - 1);
                    break;
                default:
                    // All time - no filtering
                    startDate = null;
            }
            
            // Filter rows by date
            const rows = document.querySelectorAll('.transaction-item');
            
            rows.forEach(row => {
                if (!startDate) {
                    // Show all rows for "all time"
                    row.style.display = 'table-row';
                    return;
                }
                
                const dateCell = row.querySelector('td:first-child');
                const rowDate = new Date(dateCell.textContent.trim());
                
                if (rowDate >= startDate && rowDate <= today) {
                    row.style.display = 'table-row';
                } else {
                    row.style.display = 'none';
                    
                    // Hide details row if it's open
                    const id = row.querySelector('.view-details').dataset.id;
                    const detailsRow = document.getElementById('details-' + id);
                    if (detailsRow) {
                        detailsRow.style.display = 'none';
                    }
                }
            });
        });
    }
    
    // Handle currency filter if present
    const currencyFilter = document.getElementById('currencyFilter');
    if (currencyFilter) {
        currencyFilter.addEventListener('change', function() {
            const currency = this.value;
            const rows = document.querySelectorAll('.transaction-item');
            
            rows.forEach(row => {
                const currencyCell = row.querySelector('td:nth-child(2)');
                const rowCurrency = currencyCell.textContent.trim().split(' ')[0];
                
                if (currency === 'all' || rowCurrency.includes(currency)) {
                    row.style.display = 'table-row';
                } else {
                    row.style.display = 'none';
                    
                    // Hide details row if it's open
                    const id = row.querySelector('.view-details').dataset.id;
                    const detailsRow = document.getElementById('details-' + id);
                    if (detailsRow) {
                        detailsRow.style.display = 'none';
                    }
                }
            });
        });
    }
    
    // Handle blockchain explorer links
    document.querySelectorAll('.explorer-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const url = this.getAttribute('href');
            
            // Open in new tab/window
            window.open(url, '_blank');
        });
    });
});
</script>

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