<?php
session_start();
require_once '../config/database.php';
require_once 'includes/auth_check.php';
require_once 'includes/admin_notifications.php'; // Fixed path to admin_notifications.php

$page = 'crypto_deposits';
$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();

// Create table if it doesn't exist
if (!$depositsTableExists) {
    try {
        // Create crypto_deposits table
        $db->exec("
            CREATE TABLE crypto_deposits (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                currency VARCHAR(20) NOT NULL,
                amount DECIMAL(18, 8) NOT NULL,
                wallet_address VARCHAR(255) NOT NULL,
                transaction_hash VARCHAR(255) NOT NULL,
                network VARCHAR(50) DEFAULT NULL,
                screenshot VARCHAR(255) DEFAULT NULL,
                status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
                admin_notes TEXT DEFAULT NULL,
                admin_id INT DEFAULT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            )
        ");
        
        $_SESSION['success'] = "Crypto deposits table created successfully.";
    } catch (PDOException $e) {
        $_SESSION['error'] = "Error creating crypto_deposits table: " . $e->getMessage();
    }
}

// Handle form submission for approving/rejecting deposits
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && isset($_POST['deposit_id'])) {
        $deposit_id = $_POST['deposit_id'];
        $action = $_POST['action'];
        $admin_notes = $_POST['admin_notes'] ?? '';
        
        try {
            $db->beginTransaction();
            
            // Get deposit details
            $stmt = $db->prepare("SELECT * FROM crypto_deposits WHERE id = ?");
            $stmt->execute([$deposit_id]);
            $deposit = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$deposit) {
                throw new Exception("Deposit not found.");
            }
            
            if ($action === 'approve') {
                try {
                    // Update deposit status
                    $stmt = $db->prepare("UPDATE crypto_deposits SET status = 'approved', admin_notes = ?, admin_id = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$admin_notes, $_SESSION['admin_id'], $deposit_id]);
                    
                    // Get the deposit currency
                    $deposit_currency = $deposit['currency'];
                    
                    // Check if user has an account balance record for this currency
                    $balance_stmt = $db->prepare("
                        SELECT * FROM account_balances 
                        WHERE user_id = ? AND currency = ?
                        LIMIT 1
                    ");
                    $balance_stmt->execute([$deposit['user_id'], $deposit_currency]);
                    $balance_record = $balance_stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($balance_record) {
                        // Update existing balance record
                        $update_stmt = $db->prepare("
                            UPDATE account_balances 
                            SET balance = balance + ?, last_updated = NOW() 
                            WHERE id = ?
                        ");
                        $update_stmt->execute([$deposit['amount'], $balance_record['id']]);
                    } else {
                        // Create new balance record
                        // First, get user's account number
                        $user_stmt = $db->prepare("SELECT account_number FROM users WHERE id = ?");
                        $user_stmt->execute([$deposit['user_id']]);
                        $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if (!$user) {
                            throw new Exception("User not found with ID: " . $deposit['user_id']);
                        }
                        
                        $insert_stmt = $db->prepare("
                            INSERT INTO account_balances (user_id, account_number, currency, balance, last_updated)
                            VALUES (?, ?, ?, ?, NOW())
                        ");
                        $insert_stmt->execute([
                            $deposit['user_id'],
                            $user['account_number'],
                            $deposit_currency,
                            $deposit['amount']
                        ]);
                    }
                    
                 // Generate a unique reference for the transaction
$reference = 'CRYPTO_' . strtoupper($deposit['currency']) . '_' . time() . '_' . rand(1000, 9999);

// Create transaction record
$stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, status, description, transaction_type, currency, reference) 
                     VALUES (?, 'credit', ?, 'completed', ?, 'deposit', ?, ?)");
$stmt->execute([
    $deposit['user_id'], 
    $deposit['amount'], 
    'Crypto deposit (' . $deposit['currency'] . ') - Transaction: ' . substr($deposit['transaction_hash'], 0, 10) . '...',
    $deposit_currency,
    $reference
]);

                    
                    // Create notification for user
                    $stmt = $db->prepare("
                        INSERT INTO notifications (user_id, type, title, message, link, is_read, created_at)
                        VALUES (?, 'deposit_approved', 'Deposit Approved', ?, 'transactions.php', 0, NOW())
                    ");
                    $stmt->execute([
                        $deposit['user_id'],
                        'Your ' . $deposit['currency'] . ' deposit of ' . $deposit['amount'] . ' has been approved and credited to your account.'
                    ]);
                    
                    $_SESSION['success'] = "Deposit approved and funds credited to user account.";
                    $db->commit();
                } catch (Exception $e) {
                    $db->rollBack();
                    $_SESSION['error'] = "Error processing deposit: " . $e->getMessage();
                }
            } elseif ($action === 'reject') {
                try {
                    // Update deposit status
                    $stmt = $db->prepare("UPDATE crypto_deposits SET status = 'rejected', admin_notes = ?, admin_id = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$admin_notes, $_SESSION['admin_id'], $deposit_id]);
                    
                    // Create notification for user
                    $stmt = $db->prepare("
                        INSERT INTO notifications (user_id, type, title, message, link, is_read, created_at)
                        VALUES (?, 'deposit_rejected', 'Deposit Rejected', ?, 'deposit_history.php', 0, NOW())
                    ");
                    $stmt->execute([
                        $deposit['user_id'],
                        'Your ' . $deposit['currency'] . ' deposit of ' . $deposit['amount'] . ' has been rejected. Reason: ' . $admin_notes
                    ]);
                    
                    $_SESSION['success'] = "Deposit rejected successfully.";
                    $db->commit();
                } catch (Exception $e) {
                    $db->rollBack();
                    $_SESSION['error'] = "Error processing deposit: " . $e->getMessage();
                }
            }
            
            // Redirect to refresh the page
            header("Location: crypto_deposits.php");
            exit();
        } catch (Exception $e) {
            $db->rollBack();
            $_SESSION['error'] = "Error processing deposit: " . $e->getMessage();
            header("Location: crypto_deposits.php");
            exit();
        }
    }
}

// Get all deposits with user information
$deposits = [];
if ($depositsTableExists) {
    try {
        $stmt = $db->prepare("
            SELECT cd.*, u.first_name, u.last_name, u.email, u.account_number 
            FROM crypto_deposits cd
            JOIN users u ON cd.user_id = u.id
            ORDER BY cd.created_at DESC
        ");
        $stmt->execute();
        $deposits = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $_SESSION['error'] = "Error fetching deposits: " . $e->getMessage();
    }
}

// Calculate statistics
$totalDeposits = count($deposits);
$pendingDeposits = 0;
$approvedDeposits = 0;
$rejectedDeposits = 0;

$btcTotal = 0;
$usdtTotal = 0;

foreach ($deposits as $deposit) {
    if ($deposit['status'] === 'pending') {
        $pendingDeposits++;
    } elseif ($deposit['status'] === 'approved') {
        $approvedDeposits++;
        
        if ($deposit['currency'] === 'BTC') {
            $btcTotal += $deposit['amount'];
        } elseif ($deposit['currency'] === 'USDT') {
            $usdtTotal += $deposit['amount'];
        }
    } elseif ($deposit['status'] === 'rejected') {
        $rejectedDeposits++;
    }
}

include 'includes/header.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; }

/* Modal Styles */
.modal-header {
    border-bottom: 1px solid var(--border-color);
    padding: 1.25rem;
}

.modal-footer {
    border-top: 1px solid var(--border-color);
    padding: 1.25rem;
}

.modal-title {
    font-weight: 600;
}

.modal-content {
    border: none;
    border-radius: 0.75rem;
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}

/* Avatar Styles */
.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    color: white;
    background-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);
}



/* Badge Styles for Bootstrap 5 compatibility */
.badge.rounded-pill {
    border-radius: 50rem;
    padding: 0.35em 0.65em;
}

.text-bg-success {
    color: #fff !important;
    background-color: #198754 !important;
}

.text-bg-warning {
    color: #000 !important;
    background-color: #ffc107 !important;
}

.text-bg-danger {
    color: #fff !important;
    background-color: #dc3545 !important;
}

/* Button Group Styles */
.btn-group-sm > .btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
    border-radius: 0.2rem;
}

/* Icon Styles for Boxicons */
.bx {
    font-size: 1.25rem;
    line-height: 1;
    vertical-align: middle;
}

.bx-check {
    font-weight: bold;
}

.bx-x {
    font-weight: bold;
}

</style>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="page-header">
            <div class="row align-items-center">
                <div class="col">
                    <h1 class="page-header-title text-primary">
                        <i class="fas fa-coins mr-2"></i> Crypto Deposits
                    </h1>
                    <p class="text-muted">Review and manage cryptocurrency deposit requests</p>
                </div>
                <div class="col-auto">
                    <a href="crypto_settings.php" class="btn btn-primary">
                        <i class="fas fa-cog mr-1"></i> Wallet Settings
                    </a>
                </div>
            </div>
        </div>

        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
        <?php endif; ?>

        <!-- Deposit Statistics -->
        <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="fas fa-coins"></i>
                    </div>
                    <div class="stats-value"><?php echo $totalDeposits; ?></div>
                    <div class="stats-label">Total Deposits</div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="stats-card warning slide-up" style="animation-delay: 0.2s;">
                    <div class="stats-icon">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stats-value"><?php echo $pendingDeposits; ?></div>
                    <div class="stats-label">Pending Deposits</div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="stats-card success slide-up" style="animation-delay: 0.3s;">
                    <div class="stats-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stats-value"><?php echo $approvedDeposits; ?></div>
                    <div class="stats-label">Approved Deposits</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="fas fa-times-circle"></i>
                    </div>
                    <div class="stats-value"><?php echo $rejectedDeposits; ?></div>
                    <div class="stats-label">Rejected Deposits</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="fab fa-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($btcTotal, 8); ?> BTC</h3>
                                <p class="text-muted mb-0">Total BTC Approved</p>
                            </div>
                            <div class="bg-warning-light text-warning p-3 rounded-circle">
                                <i class="fab fa-bitcoin fa-2x"></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="fas fa-dollar-sign"></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($usdtTotal, 2); ?> USDT</h3>
                                <p class="text-muted mb-0">Total USDT Approved</p>
                            </div>
                            <div class="bg-success-light text-success p-3 rounded-circle">
                                <i class="fas fa-dollar-sign fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

<!-- Deposits Table -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <h6 class="m-0 font-weight-bold text-primary">All Crypto Deposits</h6>
        <div class="d-flex">
            <div class="btn-group mr-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="fas fa-search search-icon"></i>
                <input type="text" class="form-control" id="searchInput" placeholder="Search...">
            </div>
        </div>
    </div>
    <div class="card-body">
        <?php if (empty($deposits)): ?>
            <div class="empty-state" style="height: 300px;">
                <i class="fas fa-coins empty-state-icon"></i>
                <h5 class="empty-state-title">No Crypto Deposits Found</h5>
                <p class="empty-state-text">There are no cryptocurrency deposit requests at this time.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-bordered" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Customer</th>
                            <th>Currency</th>
                            <th>Amount</th>
                            <th>Transaction Hash</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($deposits as $deposit): ?>
                            <tr>
                                <td><?php echo $deposit['id']; ?></td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar mr-2" style="background-color: #4e73df; color: white; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600;">
                                            <?php echo strtoupper(substr($deposit['first_name'], 0, 1) . substr($deposit['last_name'], 0, 1)); ?>
                                        </div>
                                        <div>
                                            <a href="view_user.php?id=<?php echo $deposit['user_id']; ?>" class="font-weight-bold text-primary">
                                                <?php echo htmlspecialchars($deposit['first_name'] . ' ' . $deposit['last_name']); ?>
                                            </a>
                                            <div class="small text-muted"><?php echo htmlspecialchars($deposit['account_number']); ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <?php if ($deposit['currency'] === 'BTC'): ?>
                                            <i class="fab fa-bitcoin text-warning mr-2"></i>
                                        <?php elseif ($deposit['currency'] === 'USDT'): ?>
                                            <i class="fas fa-dollar-sign text-success mr-2"></i>
                                        <?php else: ?>
                                            <i class="fas fa-coins text-primary mr-2"></i>
                                        <?php endif; ?>
                                        <span><?php echo htmlspecialchars($deposit['currency']); ?></span>
                                        <?php if ($deposit['network']): ?>
                                            <span class="badge badge-light ml-1"><?php echo htmlspecialchars($deposit['network']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td><?php echo number_format($deposit['amount'], 8); ?></td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <span class="text-monospace text-truncate" style="max-width: 150px;"><?php echo htmlspecialchars($deposit['transaction_hash']); ?></span>
                                        <button class="btn btn-sm btn-link copy-hash" data-hash="<?php echo htmlspecialchars($deposit['transaction_hash']); ?>">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge rounded-pill text-bg-<?php echo $deposit['status'] == 'approved' ? 'success' : ($deposit['status'] == 'pending' ? 'warning' : 'danger'); ?>">
                                        <?php echo ucfirst($deposit['status']); ?>
                                    </span>
                                </td>
                                <td><?php echo date('M d, Y H:i', strtotime($deposit['created_at'])); ?></td>
                                <td class="text-center">
                                    <?php if ($deposit['status'] === 'pending'): ?>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="handleAction(<?php echo $deposit['id']; ?>, 'approve')" class="btn btn-success" title="Approve"><i class='bx bx-check'></i></button>
                                            <button onclick="handleAction(<?php echo $deposit['id']; ?>, 'reject')" class="btn btn-danger" title="Decline"><i class='bx bx-x'></i></button>
                                        </div>
                                    <?php else: ?>
                                        <span class="text-muted">Processed</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Hidden form that JavaScript will use to submit the status update -->
<form id="actionForm" action="crypto_deposits.php" method="POST" style="display: none;">
    <input type="hidden" name="deposit_id" id="deposit_id_input">
    <input type="hidden" name="action" id="action_input">
    <input type="hidden" name="admin_notes" id="admin_notes_input">
</form>

<script>
function handleAction(depositId, newStatus) {
    if (newStatus === 'approve') {
        Swal.fire({
            title: 'Approve Deposit?',
            text: `Are you sure you want to approve crypto deposit #${depositId}? This action cannot be undone.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#198754',
            confirmButtonText: 'Yes, approve it!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                submitForm(depositId, 'approve');
            }
        });
    } else if (newStatus === 'reject') {
        Swal.fire({
            title: 'Reject Deposit?',
            text: `Please provide a reason for rejecting crypto deposit #${depositId}.`,
            icon: 'warning',
            input: 'text',
            inputPlaceholder: 'Reason for rejection...',
            inputValidator: (value) => {
                if (!value) {
                    return 'You need to provide a reason!'
                }
            },
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            confirmButtonText: 'Yes, reject it!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                submitForm(depositId, 'reject', result.value);
            }
        });
    }
}

function submitForm(depositId, action, notes = '') {
    document.getElementById('deposit_id_input').value = depositId;
    document.getElementById('action_input').value = action;
    document.getElementById('admin_notes_input').value = notes;
    document.getElementById('actionForm').submit();
}
</script>


    </div>
</div>



<!-- View Deposit Modal -->
<div class="modal fade" id="viewDepositModal" tabindex="-1" role="dialog" aria-labelledby="viewDepositModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewDepositModalLabel">Deposit Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="font-weight-bold">Deposit Information</h6>
                        <table class="table table-sm">
                            <tr>
                                <th>ID</th>
                                <td id="view-deposit-id"></td>
                            </tr>
                            <tr>
                                <th>Currency</th>
                                <td id="view-deposit-currency"></td>
                            </tr>
                            <tr>
                                <th>Amount</th>
                                <td id="view-deposit-amount"></td>
                            </tr>
                            <tr>
                                <th>Network</th>
                                <td id="view-deposit-network"></td>
                            </tr>
                            <tr>
                                <th>Status</th>
                                <td id="view-deposit-status"></td>
                            </tr>
                            <tr>
                                <th>Date</th>
                                <td id="view-deposit-date"></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="font-weight-bold">Customer Information</h6>
                        <table class="table table-sm">
                            <tr>
                                <th>Name</th>
                                <td id="view-customer-name"></td>
                            </tr>
                            <tr>
                                <th>Account #</th>
                                <td id="view-customer-account"></td>
                            </tr>
                            <tr>
                                <th>Email</th>
                                <td id="view-customer-email"></td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-md-12">
                        <h6 class="font-weight-bold">Transaction Details</h6>
                        <div class="form-group">
                            <label>Transaction Hash</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="view-transaction-hash" readonly>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary copy-hash-btn" type="button" data-toggle="tooltip" title="Copy Hash">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                    <a href="#" class="btn btn-outline-primary" id="view-explorer-link" target="_blank" data-toggle="tooltip" title="View in Explorer">
                                        <i class="fas fa-external-link-alt"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-md-12">
                        <h6 class="font-weight-bold">Wallet Address</h6>
                        <div class="form-group">
                            <div class="input-group">
                                <input type="text" class="form-control" id="view-wallet-address" readonly>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary copy-address-btn" type="button" data-toggle="tooltip" title="Copy Address">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3" id="screenshot-container" style="display: none;">
                    <div class="col-md-12">
                        <h6 class="font-weight-bold">Proof of Payment</h6>
                        <div class="text-center">
                            <a href="#" id="view-screenshot-link" target="_blank">
                                <img id="view-screenshot" src="" alt="Proof of Payment" class="img-fluid img-thumbnail" style="max-height: 300px;">
                            </a>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3" id="admin-notes-container" style="display: none;">
                    <div class="col-md-12">
                        <h6 class="font-weight-bold">Admin Notes</h6>
                        <p id="view-admin-notes" class="p-2 bg-light rounded"></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <div id="view-action-buttons" style="display: none;">
                    <button type="button" class="btn btn-success" id="view-approve-btn"><i class="fas fa-check mr-1"></i>Approve</button>
                    <button type="button" class="btn btn-danger" id="view-reject-btn"><i class="fas fa-times mr-1"></i>Reject</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Approve Deposit Modal -->
<div class="modal fade" id="approveDepositModal" tabindex="-1" role="dialog" aria-labelledby="approveDepositModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title" id="approveDepositModalLabel">Approve Deposit</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="approve">
                    <input type="hidden" id="approve_deposit_id" name="deposit_id">
                    
                    <div class="text-center mb-4">
                        <div class="avatar avatar-lg bg-success text-white mx-auto mb-3" style="width: 64px; height: 64px; font-size: 1.5rem;">
                            <i class="fas fa-check fa-2x"></i>
                        </div>
                        <h5>Confirm Deposit Approval</h5>
                        <p class="text-muted">You are about to approve this deposit. The funds will be credited to the customer's account.</p>
                    </div>
                    
                    <div class="alert alert-info">
                        <div class="d-flex">
                            <div class="mr-2">
                                <i class="fas fa-info-circle fa-2x"></i>
                            </div>
                            <div>
                                <strong>Verification Required</strong>
                                <p class="mb-0">Please verify that the transaction hash is valid and the payment has been received in your wallet before approving.</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="admin_notes_approve">Admin Notes (Optional)</label>
                        <textarea class="form-control" id="admin_notes_approve" name="admin_notes" rows="3" placeholder="Add any notes regarding this approval..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-check mr-1"></i> Approve Deposit
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reject Deposit Modal -->
<div class="modal fade" id="rejectDepositModal" tabindex="-1" role="dialog" aria-labelledby="rejectDepositModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="rejectDepositModalLabel">Reject Deposit</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="reject">
                    <input type="hidden" id="reject_deposit_id" name="deposit_id">
                    
                    <div class="text-center mb-4">
                        <div class="avatar avatar-lg bg-danger text-white mx-auto mb-3" style="width: 64px; height: 64px; font-size: 1.5rem;">
                            <i class="fas fa-times fa-2x"></i>
                        </div>
                        <h5>Confirm Deposit Rejection</h5>
                        <p class="text-muted">You are about to reject this deposit. The customer will be notified.</p>
                    </div>
                    
                    <div class="form-group">
                        <label for="admin_notes_reject">Reason for Rejection <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="admin_notes_reject" name="admin_notes" rows="3" required placeholder="Please provide a reason for rejecting this deposit..."></textarea>
                        <div class="invalid-feedback">Please provide a reason for rejection.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-times mr-1"></i> Reject Deposit
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Initialize DataTable with minimal configuration
var table = $('#depositsTable').DataTable({
    "ordering": true,
    "searching": true,
    "paging": true,
    "info": true,
    "lengthChange": true,
    "pageLength": 10,
    "order": [[6, "desc"]] // Sort by date column descending
});

// Use custom search box
$('#searchInput').on('keyup', function() {
    table.search(this.value).draw();
});

// Filter by status
$('.filter-btn').on('click', function() {
    $('.filter-btn').removeClass('active');
    $(this).addClass('active');
    const status = $(this).data('filter');
    
    if (status === 'all') {
        table.column(5).search('').draw();
    } else {
        table.column(5).search(status).draw();
    }
});
    
    // View deposit details
    $('.view-deposit').click(function() {
        const depositId = $(this).data('id');
        
        $.ajax({
            url: 'ajax/get_deposit_details.php',
            type: 'GET',
            data: { id: depositId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    const deposit = response.deposit;
                    
                    $('#view-deposit-id').text(deposit.id);
                    $('#view-deposit-currency').text(deposit.currency);
                    $('#view-deposit-amount').text(parseFloat(deposit.amount).toFixed(8));
                    $('#view-deposit-network').text(deposit.network || 'N/A');
                    
                    let statusBadge = '';
                    if (deposit.status === 'pending') statusBadge = '<span class="badge badge-warning">Pending</span>';
                    else if (deposit.status === 'approved') statusBadge = '<span class="badge badge-success">Approved</span>';
                    else if (deposit.status === 'rejected') statusBadge = '<span class="badge badge-danger">Rejected</span>';
                    $('#view-deposit-status').html(statusBadge);
                    
                    $('#view-deposit-date').text(new Date(deposit.created_at).toLocaleString());
                    $('#view-customer-name').text(deposit.first_name + ' ' + deposit.last_name);
                    $('#view-customer-account').text(deposit.account_number);
                    $('#view-customer-email').text(deposit.email);
                    $('#view-transaction-hash').val(deposit.transaction_hash);
                    $('#view-wallet-address').val(deposit.wallet_address);
                    
                    let explorerUrl = '#';
                    if (deposit.currency === 'BTC') explorerUrl = 'https://www.blockchain.com/btc/tx/' + deposit.transaction_hash;
                    else if (deposit.currency === 'USDT') {
                        if (deposit.network === 'TRC20') explorerUrl = 'https://tronscan.org/#/transaction/' + deposit.transaction_hash;
                        else if (deposit.network === 'ERC20') explorerUrl = 'https://etherscan.io/tx/' + deposit.transaction_hash;
                        else if (deposit.network === 'BEP20') explorerUrl = 'https://bscscan.com/tx/' + deposit.transaction_hash;
                    }
                    $('#view-explorer-link').attr('href', explorerUrl);
                    
                    if (deposit.screenshot) {
                        const screenshotUrl = '../uploads/deposit_proofs/' + deposit.screenshot;
                        $('#view-screenshot').attr('src', screenshotUrl);
                        $('#view-screenshot-link').attr('href', screenshotUrl);
                        $('#screenshot-container').show();
                    } else {
                        $('#screenshot-container').hide();
                    }
                    
                    if (deposit.admin_notes) {
                        $('#view-admin-notes').text(deposit.admin_notes);
                        $('#admin-notes-container').show();
                    } else {
                        $('#admin-notes-container').hide();
                    }
                    
                    if (deposit.status === 'pending') {
                        $('#view-action-buttons').show();
                        $('#view-approve-btn').data('id', deposit.id);
                        $('#view-reject-btn').data('id', deposit.id);
                    } else {
                        $('#view-action-buttons').hide();
                    }
                    
                    $('#viewDepositModal').modal('show');
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function() {
                alert('An error occurred while fetching deposit details.');
            }
        });
    });

    // Approve/Reject from table buttons
    $('.approve-deposit').click(function() {
        const depositId = $(this).data('id');
        $('#approve_deposit_id').val(depositId);
        $('#approveDepositModal').modal('show');
    });

    $('.reject-deposit').click(function() {
        const depositId = $(this).data('id');
        $('#reject_deposit_id').val(depositId);
        $('#rejectDepositModal').modal('show');
    });

    // Approve/Reject from view modal buttons
    $('#view-approve-btn').click(function() {
        const depositId = $(this).data('id');
        $('#approve_deposit_id').val(depositId);
        $('#viewDepositModal').modal('hide');
        $('#approveDepositModal').modal('show');
    });

    $('#view-reject-btn').click(function() {
        const depositId = $(this).data('id');
        $('#reject_deposit_id').val(depositId);
        $('#viewDepositModal').modal('hide');
        $('#rejectDepositModal').modal('show');
    });

    // Copy functions
    function copyToClipboard(text, button) {
        navigator.clipboard.writeText(text).then(function() {
            const originalTitle = $(button).attr('data-original-title');
            $(button).tooltip('hide').attr('data-original-title', 'Copied!').tooltip('show');
            setTimeout(() => {
                $(button).tooltip('hide').attr('data-original-title', originalTitle);
            }, 2000);
        });
    }

    $('.copy-hash').click(function() {
        copyToClipboard($(this).data('hash'), this);
    });

    $('.copy-hash-btn').click(function() {
        copyToClipboard($('#view-transaction-hash').val(), this);
    });

    $('.copy-address-btn').click(function() {
        copyToClipboard($('#view-wallet-address').val(), this);
    });

    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // 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
    $('.dashboard-card, .stats-card').hover(
        function() {
            $(this).css({
                'transform': 'translateY(-5px)',
                'box-shadow': '0 15px 30px -10px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1)'
            });
        },
        function() {
            $(this).css({
                'transform': '',
                'box-shadow': ''
            });
        }
    );
});


</script>

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