<?php
session_start();
require_once '../connection.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: ../admin-login.php');
    exit();
}

// Fetch admin data from admin_table
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM admin_table WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header('Location: ../admin-login.php');
    exit();
}

$admin = $result->fetch_assoc();
$stmt->close();

// Initialize variables
$message = '';
$message_type = '';
$selected_deposit = null;
$show_view_modal = false;

// Handle Deposit Actions (Approve, Reject, Update)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $deposit_id = intval($_POST['deposit_id']);
    
    // Get deposit details
    $query = "SELECT d.*, u.email, u.username, u.full_name, u.account_balance, 
                     p.wallet_name, p.bank_name, p.payment_type 
              FROM deposits d 
              JOIN users u ON d.user_id = u.id 
              LEFT JOIN payment_tb p ON d.payment_method_id = p.id 
              WHERE d.id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $deposit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        $message = "Deposit not found!";
        $message_type = "error";
    } else {
        $deposit = $result->fetch_assoc();
        $user_id = $deposit['user_id'];
        $amount = $deposit['amount'];
        $user_email = $deposit['email'];
        $user_name = $deposit['full_name'] ?: $deposit['username'];
        $transaction_id = $deposit['transaction_id'];
        
        switch($action) {
            case 'approve':
                // Start transaction
                $conn->begin_transaction();
                
                try {
                    // Update deposit status to completed
                    $update_query = "UPDATE deposits SET 
                                    status = 'completed',
                                    verified_by = ?,
                                    verified_at = NOW(),
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("ii", $admin_id, $deposit_id);
                    $update_stmt->execute();
                    
                    // Credit user's account balance - THIS UPDATES account_balance
                    $credit_query = "UPDATE users SET 
                                    account_balance = account_balance + ?,
                                    total_deposits = total_deposits + ?,
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $credit_stmt = $conn->prepare($credit_query);
                    $credit_stmt->bind_param("ddi", $amount, $amount, $user_id);
                    $credit_stmt->execute();
                    
                    // Check if transactions table exists before trying to insert
                    $table_check = $conn->query("SHOW TABLES LIKE 'transactions'");
                    if ($table_check->num_rows > 0) {
                        // Create transaction record if table exists
                        $reference = 'DEP' . time() . rand(1000, 9999);
                        
                        // First, check the structure of the transactions table
                        $structure_check = $conn->query("DESCRIBE transactions");
                        $columns = [];
                        while ($row = $structure_check->fetch_assoc()) {
                            $columns[$row['Field']] = $row['Field'];
                        }
                        
                        // Insert transaction based on actual table structure
                        if (isset($columns['transaction_type'])) {
                            // If table has 'transaction_type' column
                            $transaction_query = "INSERT INTO transactions 
                                                 (user_id, transaction_type, amount, status, created_at) 
                                                 VALUES (?, 'deposit', ?, 'completed', NOW())";
                            $transaction_stmt = $conn->prepare($transaction_query);
                            $transaction_stmt->bind_param("id", $user_id, $amount);
                        } else if (isset($columns['type'])) {
                            // If table has 'type' column (based on your structure)
                            $transaction_query = "INSERT INTO transactions 
                                                 (user_id, type, amount, status, created_at) 
                                                 VALUES (?, 'deposit', ?, 'completed', NOW())";
                            $transaction_stmt = $conn->prepare($transaction_query);
                            $transaction_stmt->bind_param("id", $user_id, $amount);
                        } else {
                            // Default fallback
                            $transaction_query = "INSERT INTO transactions 
                                                 (user_id, amount, status, created_at) 
                                                 VALUES (?, ?, 'completed', NOW())";
                            $transaction_stmt = $conn->prepare($transaction_query);
                            $transaction_stmt->bind_param("id", $user_id, $amount);
                        }
                        
                        if (isset($transaction_stmt)) {
                            $transaction_stmt->execute();
                        }
                    }
                    
                    // Check if notifications table exists before creating notification
                    $table_check = $conn->query("SHOW TABLES LIKE 'notifications'");
                    if ($table_check->num_rows > 0) {
                        $notification_query = "INSERT INTO notifications 
                                              (user_id, notification_type, title, message, created_at) 
                                              VALUES (?, 'transaction', 'Deposit Approved', ?, NOW())";
                        $notification_msg = "Your deposit of $" . number_format($amount, 2) . " has been approved and credited to your account.";
                        $notification_stmt = $conn->prepare($notification_query);
                        $notification_stmt->bind_param("is", $user_id, $notification_msg);
                        $notification_stmt->execute();
                    }
                    
                    $conn->commit();
                    
                    // Send email notification
                    $email_sent = sendDepositApprovalEmail($user_email, $user_name, $amount, $transaction_id, $deposit_id);
                    
                    $message = "Deposit approved successfully! User account credited with $" . number_format($amount, 2);
                    if ($email_sent) {
                        $message .= " Email notification sent.";
                    } else {
                        $message .= " Email notification failed to send.";
                    }
                    $message_type = "success";
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error approving deposit: " . $e->getMessage();
                    $message_type = "error";
                }
                break;
                
            case 'reject':
                $admin_notes = trim($_POST['admin_notes'] ?? '');
                
                $update_query = "UPDATE deposits SET 
                                status = 'rejected',
                                admin_notes = ?,
                                verified_by = ?,
                                verified_at = NOW(),
                                updated_at = NOW()
                                WHERE id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("sii", $admin_notes, $admin_id, $deposit_id);
                
                if ($update_stmt->execute()) {
                    // Check if notifications table exists
                    $table_check = $conn->query("SHOW TABLES LIKE 'notifications'");
                    if ($table_check->num_rows > 0) {
                        $notification_query = "INSERT INTO notifications 
                                              (user_id, notification_type, title, message, created_at) 
                                              VALUES (?, 'transaction', 'Deposit Rejected', ?, NOW())";
                        $notification_msg = "Your deposit of $" . number_format($amount, 2) . " has been rejected.";
                        if (!empty($admin_notes)) {
                            $notification_msg .= " Reason: " . $admin_notes;
                        }
                        $notification_stmt = $conn->prepare($notification_query);
                        $notification_stmt->bind_param("is", $user_id, $notification_msg);
                        $notification_stmt->execute();
                    }
                    
                    // Send email notification
                    $email_sent = sendDepositRejectionEmail($user_email, $user_name, $amount, $transaction_id, $admin_notes);
                    
                    $message = "Deposit rejected successfully!";
                    if ($email_sent) {
                        $message .= " Email notification sent.";
                    } else {
                        $message .= " Email notification failed to send.";
                    }
                    $message_type = "success";
                } else {
                    $message = "Error rejecting deposit: " . $update_stmt->error;
                    $message_type = "error";
                }
                break;
                
            case 'update_notes':
                $admin_notes = trim($_POST['admin_notes'] ?? '');
                
                $update_query = "UPDATE deposits SET 
                                admin_notes = ?,
                                updated_at = NOW()
                                WHERE id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("si", $admin_notes, $deposit_id);
                
                if ($update_stmt->execute()) {
                    $message = "Admin notes updated successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error updating notes: " . $update_stmt->error;
                    $message_type = "error";
                }
                break;
                
            case 'pending':
                // Start transaction for rollback
                $conn->begin_transaction();
                
                try {
                    // First, get the deposit amount
                    $amount_query = "SELECT amount, user_id FROM deposits WHERE id = ?";
                    $amount_stmt = $conn->prepare($amount_query);
                    $amount_stmt->bind_param("i", $deposit_id);
                    $amount_stmt->execute();
                    $amount_result = $amount_stmt->get_result();
                    
                    if ($amount_result->num_rows > 0) {
                        $deposit_data = $amount_result->fetch_assoc();
                        $rollback_amount = $deposit_data['amount'];
                        $rollback_user_id = $deposit_data['user_id'];
                        
                        // Debit user's account balance
                        $debit_query = "UPDATE users SET 
                                        account_balance = account_balance - ?,
                                        total_deposits = total_deposits - ?,
                                        updated_at = NOW()
                                        WHERE id = ?";
                        $debit_stmt = $conn->prepare($debit_query);
                        $debit_stmt->bind_param("ddi", $rollback_amount, $rollback_amount, $rollback_user_id);
                        $debit_stmt->execute();
                    }
                    
                    // Set deposit back to pending
                    $update_query = "UPDATE deposits SET 
                                    status = 'pending',
                                    verified_by = NULL,
                                    verified_at = NULL,
                                    admin_notes = NULL,
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("i", $deposit_id);
                    $update_stmt->execute();
                    
                    $conn->commit();
                    
                    $message = "Deposit status reset to pending! Funds removed from user's account.";
                    $message_type = "success";
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error resetting deposit: " . $e->getMessage();
                    $message_type = "error";
                }
                break;
        }
    }
    $stmt->close();
}

// Handle Quick Actions
$actions = ['approve', 'reject', 'view', 'delete'];
foreach ($actions as $action) {
    if (isset($_GET[$action])) {
        $deposit_id = intval($_GET[$action]);
        
        if ($action == 'view') {
            $show_view_modal = true;
            $query = "SELECT d.*, u.email, u.username, u.full_name, u.phone, u.account_balance,
                             p.wallet_name, p.bank_name, p.payment_type, p.wallet_address, 
                             p.account_name, p.account_number, p.bank_name as payment_bank_name,
                             p.swift_code, p.iban, p.crypto_network
                      FROM deposits d 
                      JOIN users u ON d.user_id = u.id 
                      LEFT JOIN payment_tb p ON d.payment_method_id = p.id 
                      WHERE d.id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $deposit_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $selected_deposit = $result->fetch_assoc();
            $stmt->close();
        } elseif ($action == 'delete') {
            $delete_query = "DELETE FROM deposits WHERE id = ?";
            $delete_stmt = $conn->prepare($delete_query);
            $delete_stmt->bind_param("i", $deposit_id);
            
            if ($delete_stmt->execute()) {
                $message = "Deposit deleted successfully!";
                $message_type = "success";
            } else {
                $message = "Error deleting deposit: " . $delete_stmt->error;
                $message_type = "error";
            }
            $delete_stmt->close();
        }
    }
}

// Function to send deposit approval email
function sendDepositApprovalEmail($user_email, $user_name, $amount, $transaction_id, $deposit_id) {
    $site_name = "Unify Grant Trading";
    $site_email = "noreply@unifygrant.com";
    $admin_email = "support@unifygrant.com";
    
    $subject = "Deposit Approved - Transaction #$transaction_id";
    
    $message = "<!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <title>Deposit Approved</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #4CAF50; color: white; padding: 20px; text-align: center; }
            .content { background: #f9f9f9; padding: 30px; border-radius: 5px; }
            .footer { margin-top: 20px; text-align: center; color: #666; font-size: 12px; }
            .amount { font-size: 24px; font-weight: bold; color: #4CAF50; }
            .transaction-id { background: #e8f5e9; padding: 10px; border-radius: 3px; font-family: monospace; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>Deposit Approved</h1>
            </div>
            <div class='content'>
                <h2>Hello $user_name,</h2>
                <p>We are pleased to inform you that your deposit has been approved and credited to your account.</p>
                
                <p><strong>Transaction Details:</strong></p>
                <ul>
                    <li>Amount: <span class='amount'>$" . number_format($amount, 2) . "</span></li>
                    <li>Transaction ID: <div class='transaction-id'>$transaction_id</div></li>
                    <li>Deposit ID: $deposit_id</li>
                    <li>Status: <span style='color: #4CAF50; font-weight: bold;'>Completed</span></li>
                    <li>Date: " . date('F d, Y h:i A') . "</li>
                </ul>
                
                <p>The funds are now available in your trading account. You can start trading immediately.</p>
                
                <p>If you have any questions or need assistance, please contact our support team at <a href='mailto:$admin_email'>$admin_email</a>.</p>
                
                <p>Happy Trading!</p>
                <p>The $site_name Team</p>
            </div>
            <div class='footer'>
                <p>This is an automated message, please do not reply to this email.</p>
                <p>&copy; " . date('Y') . " $site_name. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: $site_name <$site_email>" . "\r\n";
    $headers .= "Reply-To: $admin_email" . "\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    return mail($user_email, $subject, $message, $headers);
}

// Function to send deposit rejection email
function sendDepositRejectionEmail($user_email, $user_name, $amount, $transaction_id, $reason = '') {
    $site_name = "Unify Grant Trading";
    $site_email = "noreply@unifygrant.com";
    $admin_email = "support@unifygrant.com";
    
    $subject = "Deposit Rejected - Transaction #$transaction_id";
    
    $message = "<!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <title>Deposit Rejected</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #f44336; color: white; padding: 20px; text-align: center; }
            .content { background: #f9f9f9; padding: 30px; border-radius: 5px; }
            .footer { margin-top: 20px; text-align: center; color: #666; font-size: 12px; }
            .amount { font-size: 24px; font-weight: bold; color: #f44336; }
            .transaction-id { background: #ffebee; padding: 10px; border-radius: 3px; font-family: monospace; }
            .reason-box { background: #fff3e0; padding: 15px; border-left: 4px solid #ff9800; margin: 15px 0; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>Deposit Rejected</h1>
            </div>
            <div class='content'>
                <h2>Hello $user_name,</h2>
                <p>We regret to inform you that your deposit request has been rejected.</p>
                
                <p><strong>Transaction Details:</strong></p>
                <ul>
                    <li>Amount: <span class='amount'>$" . number_format($amount, 2) . "</span></li>
                    <li>Transaction ID: <div class='transaction-id'>$transaction_id</div></li>
                    <li>Status: <span style='color: #f44336; font-weight: bold;'>Rejected</span></li>
                    <li>Date: " . date('F d, Y h:i A') . "</li>
                </ul>";
    
    if (!empty($reason)) {
        $message .= "<div class='reason-box'>
                        <p><strong>Reason for rejection:</strong></p>
                        <p>$reason</p>
                    </div>";
    }
    
    $message .= "<p>If you believe this is an error, or if you need further clarification, please contact our support team at <a href='mailto:$admin_email'>$admin_email</a>.</p>
                
                <p>You can submit a new deposit request with correct information.</p>
                
                <p>Thank you for your understanding.</p>
                <p>The $site_name Team</p>
            </div>
            <div class='footer'>
                <p>This is an automated message, please do not reply to this email.</p>
                <p>&copy; " . date('Y') . " $site_name. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: $site_name <$site_email>" . "\r\n";
    $headers .= "Reply-To: $admin_email" . "\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    return mail($user_email, $subject, $message, $headers);
}

// Handle search and filters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'pending';
$payment_type_filter = isset($_GET['payment_type']) ? $_GET['payment_type'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build the query with filters
$where_conditions = [];
$params = [];
$param_types = '';

if (!empty($search)) {
    $where_conditions[] = "(d.transaction_id LIKE ? OR u.username LIKE ? OR u.email LIKE ? OR u.full_name LIKE ? OR d.transaction_hash LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term, $search_term, $search_term]);
    $param_types .= 'sssss';
}

if (!empty($status_filter) && $status_filter != 'all') {
    $where_conditions[] = "d.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if (!empty($payment_type_filter) && $payment_type_filter != 'all') {
    $where_conditions[] = "d.payment_type = ?";
    $params[] = $payment_type_filter;
    $param_types .= 's';
}

if (!empty($date_from)) {
    $where_conditions[] = "DATE(d.created_at) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(d.created_at) <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Get total deposits count for pagination
$count_query = "SELECT COUNT(*) as total FROM deposits d 
                JOIN users u ON d.user_id = u.id 
                $where_clause";
if (!empty($params)) {
    $stmt = $conn->prepare($count_query);
    $stmt->bind_param($param_types, ...$params);
    $stmt->execute();
    $count_result = $stmt->get_result();
    $total_deposits = $count_result->fetch_assoc()['total'];
    $stmt->close();
} else {
    $result = $conn->query($count_query);
    $total_deposits = $result->fetch_assoc()['total'];
}

// Pagination
$per_page = 20;
$total_pages = ceil($total_deposits / $per_page);
$current_page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($current_page - 1) * $per_page;

// Get deposits with pagination and filters
$query = "SELECT d.*, u.username, u.email, u.full_name, u.phone,
                 p.wallet_name, p.bank_name, p.payment_type,
                 a.email as verified_by_admin_email
          FROM deposits d 
          JOIN users u ON d.user_id = u.id 
          LEFT JOIN payment_tb p ON d.payment_method_id = p.id 
          LEFT JOIN admin_table a ON d.verified_by = a.id 
          $where_clause 
          ORDER BY d.created_at DESC 
          LIMIT ? OFFSET ?";

$params[] = $per_page;
$params[] = $offset;
$param_types .= 'ii';

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$deposits_result = $stmt->get_result();
$deposits = [];
while ($row = $deposits_result->fetch_assoc()) {
    $deposits[] = $row;
}
$stmt->close();

// Get stats for dashboard
$stats_query = "SELECT 
    COUNT(*) as total_deposits,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_deposits,
    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_deposits,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected_deposits,
    SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_deposits,
    SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as total_approved_amount,
    SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) as pending_amount
    FROM deposits";
$stats_result = $conn->query($stats_query);
$stats = $stats_result->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Deposits - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .sidebar {
            transition: all 0.3s ease;
        }
        
        .sidebar.collapsed {
            width: 70px;
        }
        
        .sidebar.collapsed .sidebar-text {
            display: none;
        }
        
        .sidebar.collapsed .logo-text {
            display: none;
        }
        
        .main-content {
            transition: all 0.3s ease;
        }
        
        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .status-pending {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
            border: 1px solid rgba(245, 158, 11, 0.2);
        }
        
        .status-completed {
            background: rgba(72, 187, 120, 0.1);
            color: #48bb78;
            border: 1px solid rgba(72, 187, 120, 0.2);
        }
        
        .status-rejected {
            background: rgba(245, 101, 101, 0.1);
            color: #f56565;
            border: 1px solid rgba(245, 101, 101, 0.2);
        }
    </style>
</head>
<body class="bg-gray-50 font-inter">
    
    <?php include("nav.php"); ?>

    <!-- Main Content -->
    <div class="main-content ml-64">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-gray-200 px-8 py-4">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-2xl font-bold text-gray-800">Manage Deposits</h2>
                    <p class="text-gray-600">Total Deposits: <?php echo number_format($total_deposits); ?></p>
                </div>
                
                <!-- Quick Stats -->
                <div class="flex items-center space-x-4">
                    <div class="text-sm text-gray-600">
                        <span class="font-medium">Pending: </span>
                        <span class="text-yellow-600"><?php echo number_format($stats['pending_deposits']); ?></span>
                    </div>
                    <div class="text-sm text-gray-600">
                        <span class="font-medium">Completed: </span>
                        <span class="text-green-600"><?php echo number_format($stats['completed_deposits']); ?></span>
                    </div>
                    <div class="text-sm text-gray-600">
                        <span class="font-medium">Today: </span>
                        <span class="text-blue-600"><?php echo number_format($stats['today_deposits']); ?></span>
                    </div>
                </div>
            </div>
        </header>

        <!-- Message Alert -->
        <?php if (!empty($message)): ?>
        <div class="mx-8 mt-6">
            <div class="p-4 rounded-lg <?php echo $message_type == 'success' ? 'bg-green-100 text-green-700 border border-green-200' : 'bg-red-100 text-red-700 border border-red-200'; ?>">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <i class="fas <?php echo $message_type == 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
                        <span><?php echo $message; ?></span>
                    </div>
                    <button onclick="this.parentElement.parentElement.remove()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- View Deposit Modal -->
        <?php if ($show_view_modal && $selected_deposit): ?>
        <div id="viewModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-xl font-bold text-gray-800">
                            Deposit Details - <?php echo htmlspecialchars($selected_deposit['transaction_id']); ?>
                        </h3>
                        <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <!-- Deposit Information -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                        <!-- User Information -->
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <h4 class="font-bold text-gray-700 mb-3 flex items-center">
                                <i class="fas fa-user mr-2 text-blue-500"></i> User Information
                            </h4>
                            <div class="space-y-2">
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Username:</span>
                                    <span class="font-medium"><?php echo htmlspecialchars($selected_deposit['username']); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Full Name:</span>
                                    <span class="font-medium"><?php echo htmlspecialchars($selected_deposit['full_name'] ?: 'N/A'); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Email:</span>
                                    <span class="font-medium"><?php echo htmlspecialchars($selected_deposit['email']); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Phone:</span>
                                    <span class="font-medium"><?php echo htmlspecialchars($selected_deposit['phone'] ?: 'N/A'); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Account Balance:</span>
                                    <span class="font-bold text-green-600">$<?php echo number_format($selected_deposit['account_balance'], 2); ?></span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Deposit Information -->
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <h4 class="font-bold text-gray-700 mb-3 flex items-center">
                                <i class="fas fa-money-bill-wave mr-2 text-green-500"></i> Deposit Information
                            </h4>
                            <div class="space-y-2">
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Amount:</span>
                                    <span class="font-bold text-lg">$<?php echo number_format($selected_deposit['amount'], 2); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Transaction ID:</span>
                                    <span class="font-mono font-medium"><?php echo htmlspecialchars($selected_deposit['transaction_id']); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Payment Type:</span>
                                    <span class="font-medium">
                                        <?php 
                                        if ($selected_deposit['payment_type'] == 'crypto') {
                                            echo 'Cryptocurrency';
                                        } else {
                                            echo 'Bank Transfer';
                                        }
                                        ?>
                                    </span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Status:</span>
                                    <span class="status-badge <?php echo 'status-' . $selected_deposit['status']; ?>">
                                        <?php echo ucfirst($selected_deposit['status']); ?>
                                    </span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Date:</span>
                                    <span><?php echo date('M d, Y h:i A', strtotime($selected_deposit['created_at'])); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Payment Details -->
                    <div class="mb-8">
                        <h4 class="font-bold text-gray-700 mb-3 flex items-center">
                            <i class="fas fa-credit-card mr-2 text-purple-500"></i> Payment Details
                        </h4>
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <?php if ($selected_deposit['payment_type'] == 'crypto'): ?>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <span class="text-gray-600">Wallet Name:</span>
                                        <p class="font-medium"><?php echo htmlspecialchars($selected_deposit['wallet_name'] ?: 'N/A'); ?></p>
                                    </div>
                                    <div>
                                        <span class="text-gray-600">Network:</span>
                                        <p class="font-medium"><?php echo htmlspecialchars($selected_deposit['crypto_network'] ?: 'N/A'); ?></p>
                                    </div>
                                    <div class="md:col-span-2">
                                        <span class="text-gray-600">Wallet Address:</span>
                                        <p class="font-mono bg-gray-100 p-2 rounded mt-1"><?php echo htmlspecialchars($selected_deposit['wallet_address'] ?: 'N/A'); ?></p>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <span class="text-gray-600">Bank Name:</span>
                                        <p class="font-medium"><?php echo htmlspecialchars($selected_deposit['bank_name'] ?: 'N/A'); ?></p>
                                    </div>
                                    <div>
                                        <span class="text-gray-600">Account Name:</span>
                                        <p class="font-medium"><?php echo htmlspecialchars($selected_deposit['account_name'] ?: 'N/A'); ?></p>
                                    </div>
                                    <div>
                                        <span class="text-gray-600">Account Number:</span>
                                        <p class="font-mono font-medium"><?php echo htmlspecialchars($selected_deposit['account_number'] ?: 'N/A'); ?></p>
                                    </div>
                                    <?php if ($selected_deposit['swift_code']): ?>
                                    <div>
                                        <span class="text-gray-600">SWIFT Code:</span>
                                        <p class="font-mono"><?php echo htmlspecialchars($selected_deposit['swift_code']); ?></p>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($selected_deposit['iban']): ?>
                                    <div class="md:col-span-2">
                                        <span class="text-gray-600">IBAN:</span>
                                        <p class="font-mono bg-gray-100 p-2 rounded mt-1"><?php echo htmlspecialchars($selected_deposit['iban']); ?></p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Transaction Details -->
                    <div class="mb-8">
                        <h4 class="font-bold text-gray-700 mb-3 flex items-center">
                            <i class="fas fa-receipt mr-2 text-yellow-500"></i> Transaction Details
                        </h4>
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <?php if ($selected_deposit['transaction_hash']): ?>
                                <div class="md:col-span-2">
                                    <span class="text-gray-600">Transaction Hash:</span>
                                    <p class="font-mono bg-gray-100 p-2 rounded mt-1"><?php echo htmlspecialchars($selected_deposit['transaction_hash']); ?></p>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($selected_deposit['payment_proof']): ?>
                                <div class="md:col-span-2">
                                    <span class="text-gray-600">Payment Proof:</span>
                                    <div class="mt-2">
                                        <a href="../<?php echo htmlspecialchars($selected_deposit['payment_proof']); ?>" 
                                           target="_blank" 
                                           class="inline-flex items-center px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition">
                                            <i class="fas fa-external-link-alt mr-2"></i> View Proof
                                        </a>
                                    </div>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($selected_deposit['admin_notes']): ?>
                                <div class="md:col-span-2">
                                    <span class="text-gray-600">Admin Notes:</span>
                                    <div class="bg-yellow-50 border border-yellow-200 rounded p-3 mt-1">
                                        <?php echo nl2br(htmlspecialchars($selected_deposit['admin_notes'])); ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($selected_deposit['verified_by']): ?>
                                <div>
                                    <span class="text-gray-600">Verified By:</span>
                                    <p class="font-medium"><?php echo htmlspecialchars($selected_deposit['verified_by_admin_email'] ?: 'Admin'); ?></p>
                                </div>
                                <div>
                                    <span class="text-gray-600">Verified At:</span>
                                    <p><?php echo date('M d, Y h:i A', strtotime($selected_deposit['verified_at'])); ?></p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Action Buttons -->
                    <div class="border-t border-gray-200 pt-6">
                        <div class="flex flex-wrap gap-3 justify-end">
                            <?php if ($selected_deposit['status'] == 'pending'): ?>
                                <form method="POST" action="" class="inline" onsubmit="return confirm('Are you sure you want to approve this deposit? This will credit the user\'s account.')">
                                    <input type="hidden" name="action" value="approve">
                                    <input type="hidden" name="deposit_id" value="<?php echo $selected_deposit['id']; ?>">
                                    <button type="submit" class="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                                        <i class="fas fa-check mr-2"></i> Approve Deposit
                                    </button>
                                </form>
                                
                                <button onclick="showRejectForm()" class="flex items-center px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition">
                                    <i class="fas fa-times mr-2"></i> Reject Deposit
                                </button>
                                
                            <?php elseif ($selected_deposit['status'] == 'completed'): ?>
                                <form method="POST" action="" class="inline" onsubmit="return confirm('Reset this deposit to pending? This will remove the funds from user\'s account.')">
                                    <input type="hidden" name="action" value="pending">
                                    <input type="hidden" name="deposit_id" value="<?php echo $selected_deposit['id']; ?>">
                                    <button type="submit" class="flex items-center px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 transition">
                                        <i class="fas fa-undo mr-2"></i> Reset to Pending
                                    </button>
                                </form>
                            <?php endif; ?>
                            
                            <!-- Admin Notes Form -->
                            <form method="POST" action="" class="inline" onsubmit="return confirm('Update admin notes?')">
                                <input type="hidden" name="action" value="update_notes">
                                <input type="hidden" name="deposit_id" value="<?php echo $selected_deposit['id']; ?>">
                                <div class="flex items-center space-x-2">
                                    <input type="text" name="admin_notes" 
                                           placeholder="Add admin notes..." 
                                           value="<?php echo htmlspecialchars($selected_deposit['admin_notes'] ?? ''); ?>"
                                           class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                                    <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                                        <i class="fas fa-save"></i>
                                    </button>
                                </div>
                            </form>
                            
                            <a href="?delete=<?php echo $selected_deposit['id']; ?>" 
                               onclick="return confirm('Are you sure you want to delete this deposit? This action cannot be undone.')"
                               class="flex items-center px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition">
                                <i class="fas fa-trash mr-2"></i> Delete
                            </a>
                            
                            <button onclick="closeModal()" class="flex items-center px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                                <i class="fas fa-times mr-2"></i> Close
                            </button>
                        </div>
                        
                        <!-- Reject Form (Initially Hidden) -->
                        <div id="rejectForm" class="hidden mt-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                            <form method="POST" action="" onsubmit="return confirm('Are you sure you want to reject this deposit?')">
                                <input type="hidden" name="action" value="reject">
                                <input type="hidden" name="deposit_id" value="<?php echo $selected_deposit['id']; ?>">
                                
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Reason for Rejection
                                </label>
                                <textarea name="admin_notes" rows="3" 
                                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                          placeholder="Provide reason for rejection (optional)"></textarea>
                                
                                <div class="mt-3 flex justify-end space-x-3">
                                    <button type="button" onclick="hideRejectForm()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300">
                                        Cancel
                                    </button>
                                    <button type="submit" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">
                                        Confirm Reject
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Filters and Search -->
        <div class="bg-white mx-8 mt-6 rounded-lg shadow-sm border border-gray-200 p-6">
            <form method="GET" action="" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <!-- Search -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Search</label>
                        <div class="relative">
                            <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                                   placeholder="Search by TX ID, username, email, hash..." 
                                   class="w-full px-4 py-2 pl-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                        </div>
                    </div>
                    
                    <!-- Status Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>All Status</option>
                            <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="completed" <?php echo $status_filter == 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="rejected" <?php echo $status_filter == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                        </select>
                    </div>
                    
                    <!-- Payment Type Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Payment Type</label>
                        <select name="payment_type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $payment_type_filter == 'all' ? 'selected' : ''; ?>>All Types</option>
                            <option value="crypto" <?php echo $payment_type_filter == 'crypto' ? 'selected' : ''; ?>>Cryptocurrency</option>
                            <option value="bank" <?php echo $payment_type_filter == 'bank' ? 'selected' : ''; ?>>Bank Transfer</option>
                        </select>
                    </div>
                    
                    <!-- Date Range -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Date Range</label>
                        <div class="grid grid-cols-2 gap-2">
                            <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>"
                                   class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent text-sm">
                            <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>"
                                   class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent text-sm">
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-between items-center">
                    <div>
                        <button type="submit" class="px-6 py-2 bg-primary-600 text-primary rounded-lg hover:bg-primary-700 transition">
                            <i class="fas fa-filter mr-2"></i>Apply Filters
                        </button>
                        <a href="manage-deposits.php" class="ml-2 px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                            <i class="fas fa-times mr-2"></i>Clear
                        </a>
                    </div>
                    
                    <!-- Results Count -->
                    <div class="text-sm text-gray-600">
                        Showing <?php echo min($per_page, count($deposits)); ?> of <?php echo number_format($total_deposits); ?> deposits
                    </div>
                </div>
            </form>
        </div>

        <!-- Stats Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mx-8 mt-6">
            <!-- Total Deposits -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Deposits</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['total_deposits']); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-money-bill-wave text-blue-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    <i class="fas fa-calendar-day mr-1"></i>
                    <?php echo $stats['today_deposits']; ?> today
                </div>
            </div>

            <!-- Pending Deposits -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Pending Deposits</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['pending_deposits']); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-clock text-yellow-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    <span class="text-yellow-600 font-medium">$<?php echo number_format($stats['pending_amount'], 2); ?></span> pending
                </div>
            </div>

            <!-- Completed Deposits -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Completed Deposits</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['completed_deposits']); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-check-circle text-green-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    <span class="text-green-600 font-medium">$<?php echo number_format($stats['total_approved_amount'], 2); ?></span> approved
                </div>
            </div>

            <!-- Rejected Deposits -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Rejected Deposits</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['rejected_deposits']); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-times-circle text-red-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    <?php echo $stats['total_deposits'] > 0 ? round(($stats['rejected_deposits'] / $stats['total_deposits']) * 100, 1) : 0; ?>% rejection rate
                </div>
            </div>
        </div>

        <!-- Deposits Table -->
        <div class="bg-white mx-8 my-6 rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-50">
                        <tr class="text-left text-sm text-gray-500 border-b border-gray-200">
                            <th class="py-3 px-6 font-medium">Transaction</th>
                            <th class="py-3 px-6 font-medium">User</th>
                            <th class="py-3 px-6 font-medium">Amount</th>
                            <th class="py-3 px-6 font-medium">Payment Method</th>
                            <th class="py-3 px-6 font-medium">Status</th>
                            <th class="py-3 px-6 font-medium">Date</th>
                            <th class="py-3 px-6 font-medium">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        <?php if (empty($deposits)): ?>
                        <tr>
                            <td colspan="7" class="py-8 text-center text-gray-500">
                                <i class="fas fa-money-bill-wave text-3xl mb-2 block"></i>
                                No deposits found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($deposits as $deposit): ?>
                        <tr class="hover:bg-gray-50 transition">
                            <!-- Transaction Info -->
                            <td class="py-4 px-6">
                                <p class="font-medium text-gray-800">
                                    <?php echo htmlspecialchars($deposit['transaction_id']); ?>
                                </p>
                                <?php if ($deposit['transaction_hash']): ?>
                                <p class="text-xs text-gray-500 truncate max-w-xs" title="<?php echo htmlspecialchars($deposit['transaction_hash']); ?>">
                                    Hash: <?php echo substr(htmlspecialchars($deposit['transaction_hash']), 0, 15); ?>...
                                </p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- User Info -->
                            <td class="py-4 px-6">
                                <p class="font-medium text-gray-800">
                                    <?php echo htmlspecialchars($deposit['username']); ?>
                                </p>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($deposit['email']); ?></p>
                                <?php if ($deposit['full_name']): ?>
                                <p class="text-xs text-gray-400"><?php echo htmlspecialchars($deposit['full_name']); ?></p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Amount -->
                            <td class="py-4 px-6">
                                <p class="text-lg font-bold text-gray-800">$<?php echo number_format($deposit['amount'], 2); ?></p>
                            </td>
                            
                            <!-- Payment Method -->
                            <td class="py-4 px-6">
                                <div class="flex items-center">
                                    <?php if ($deposit['payment_type'] == 'crypto'): ?>
                                    <i class="fab fa-bitcoin text-yellow-500 mr-2"></i>
                                    <div>
                                        <p class="text-sm font-medium"><?php echo htmlspecialchars($deposit['wallet_name'] ?: 'Crypto'); ?></p>
                                        <p class="text-xs text-gray-500">Cryptocurrency</p>
                                    </div>
                                    <?php else: ?>
                                    <i class="fas fa-university text-blue-500 mr-2"></i>
                                    <div>
                                        <p class="text-sm font-medium"><?php echo htmlspecialchars($deposit['bank_name'] ?: 'Bank'); ?></p>
                                        <p class="text-xs text-gray-500">Bank Transfer</p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            
                            <!-- Status -->
                            <td class="py-4 px-6">
                                <span class="status-badge <?php echo 'status-' . $deposit['status']; ?>">
                                    <?php echo ucfirst($deposit['status']); ?>
                                </span>
                                <?php if ($deposit['admin_notes']): ?>
                                <div class="text-xs text-gray-500 mt-1 truncate max-w-xs" title="<?php echo htmlspecialchars($deposit['admin_notes']); ?>">
                                    <?php echo substr(htmlspecialchars($deposit['admin_notes']), 0, 30); ?>...
                                </div>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Date -->
                            <td class="py-4 px-6">
                                <p class="text-sm text-gray-600">
                                    <?php echo date('M d, Y', strtotime($deposit['created_at'])); ?>
                                </p>
                                <p class="text-xs text-gray-400">
                                    <?php echo date('h:i A', strtotime($deposit['created_at'])); ?>
                                </p>
                            </td>
                            
                            <!-- Actions -->
                            <td class="py-4 px-6">
                                <div class="flex flex-wrap gap-2">
                                    <!-- View Details -->
                                    <a href="?view=<?php echo $deposit['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['view' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-3 py-1 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition text-sm"
                                       title="View Details">
                                        <i class="fas fa-eye mr-1 text-xs"></i> View
                                    </a>
                                    
                                    <!-- Quick Actions -->
                                    <?php if ($deposit['status'] == 'pending'): ?>
                                    <form method="POST" action="" class="inline" onsubmit="return confirm('Approve this deposit?')">
                                        <input type="hidden" name="action" value="approve">
                                        <input type="hidden" name="deposit_id" value="<?php echo $deposit['id']; ?>">
                                        <button type="submit" class="inline-flex items-center px-3 py-1 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition text-sm"
                                                title="Approve Deposit">
                                            <i class="fas fa-check mr-1 text-xs"></i> Approve
                                        </button>
                                    </form>
                                    
                                    <form method="POST" action="" class="inline" onsubmit="return confirm('Reject this deposit?')">
                                        <input type="hidden" name="action" value="reject">
                                        <input type="hidden" name="deposit_id" value="<?php echo $deposit['id']; ?>">
                                        <input type="hidden" name="admin_notes" value="Rejected by admin">
                                        <button type="submit" class="inline-flex items-center px-3 py-1 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition text-sm"
                                                title="Reject Deposit">
                                            <i class="fas fa-times mr-1 text-xs"></i> Reject
                                        </button>
                                    </form>
                                    
                                    <?php elseif ($deposit['status'] == 'completed'): ?>
                                    <form method="POST" action="" class="inline" onsubmit="return confirm('Reset to pending?')">
                                        <input type="hidden" name="action" value="pending">
                                        <input type="hidden" name="deposit_id" value="<?php echo $deposit['id']; ?>">
                                        <button type="submit" class="inline-flex items-center px-3 py-1 bg-yellow-100 text-yellow-700 rounded-lg hover:bg-yellow-200 transition text-sm"
                                                title="Reset to Pending">
                                            <i class="fas fa-undo mr-1 text-xs"></i> Reset
                                        </button>
                                    </form>
                                    <?php endif; ?>
                                    
                                    <!-- Delete -->
                                    <a href="?delete=<?php echo $deposit['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['delete' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-3 py-1 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition text-sm"
                                       title="Delete"
                                       onclick="return confirm('Delete this deposit?')">
                                        <i class="fas fa-trash mr-1 text-xs"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="px-6 py-4 border-t border-gray-200">
                <div class="flex items-center justify-between">
                    <div class="text-sm text-gray-600">
                        Page <?php echo $current_page; ?> of <?php echo $total_pages; ?>
                    </div>
                    <div class="flex space-x-2">
                        <?php if ($current_page > 1): ?>
                        <a href="?page=<?php echo $current_page - 1; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                           class="px-3 py-1 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">
                            <i class="fas fa-chevron-left mr-1"></i> Previous
                        </a>
                        <?php endif; ?>
                        
                        <?php 
                        $start_page = max(1, $current_page - 2);
                        $end_page = min($total_pages, $current_page + 2);
                        
                        for ($page = $start_page; $page <= $end_page; $page++): 
                        ?>
                        <a href="?page=<?php echo $page; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                           class="px-3 py-1 border rounded-lg transition <?php echo $page == $current_page ? 'bg-primary-600 text-white border-primary-600' : 'border-gray-300 text-gray-700 hover:bg-gray-50'; ?>">
                            <?php echo $page; ?>
                        </a>
                        <?php endfor; ?>
                        
                        <?php if ($current_page < $total_pages): ?>
                        <a href="?page=<?php echo $current_page + 1; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                           class="px-3 py-1 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">
                            Next <i class="fas fa-chevron-right ml-1"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // Modal functions
        function closeModal() {
            const modal = document.getElementById('viewModal');
            if (modal) {
                modal.remove();
                // Remove from URL
                const url = new URL(window.location);
                url.searchParams.delete('view');
                window.history.replaceState({}, '', url);
            }
        }

        function showRejectForm() {
            document.getElementById('rejectForm').classList.remove('hidden');
        }

        function hideRejectForm() {
            document.getElementById('rejectForm').classList.add('hidden');
        }

        // Close modal on escape key
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeModal();
            }
        });

        // Close modal when clicking outside
        document.addEventListener('click', function(event) {
            const modal = document.getElementById('viewModal');
            if (modal && event.target === modal) {
                closeModal();
            }
        });

        // Quick approve/reject confirmation
        document.querySelectorAll('form[onsubmit]').forEach(form => {
            form.onsubmit = function() {
                const action = this.querySelector('[name="action"]').value;
                if (action === 'approve') {
                    return confirm('Are you sure you want to approve this deposit? This will credit the user\'s account.');
                } else if (action === 'reject') {
                    return confirm('Are you sure you want to reject this deposit?');
                } else if (action === 'pending') {
                    return confirm('Reset this deposit to pending? This will remove the funds from user\'s account.');
                }
                return true;
            };
        });

        // Auto-focus search input on page load
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.querySelector('input[name="search"]');
            if (searchInput) {
                searchInput.focus();
            }
            
            // Show modal if view parameter exists
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.has('view')) {
                const modal = document.getElementById('viewModal');
                if (modal) {
                    modal.scrollIntoView({ behavior: 'smooth' });
                }
            }
        });

        // Bulk actions
        function selectAllDeposits(checkbox) {
            const checkboxes = document.querySelectorAll('.deposit-checkbox');
            checkboxes.forEach(cb => {
                cb.checked = checkbox.checked;
            });
        }

        function performBulkAction() {
            const selectedIds = [];
            const checkboxes = document.querySelectorAll('.deposit-checkbox:checked');
            
            if (checkboxes.length === 0) {
                alert('Please select at least one deposit.');
                return;
            }
            
            checkboxes.forEach(cb => {
                selectedIds.push(cb.value);
            });
            
            const action = document.getElementById('bulkAction').value;
            if (action === 'approve') {
                if (confirm(`Approve ${selectedIds.length} selected deposit(s)?`)) {
                    // Submit form for each selected deposit
                    selectedIds.forEach(id => {
                        const form = document.createElement('form');
                        form.method = 'POST';
                        form.style.display = 'none';
                        
                        const actionInput = document.createElement('input');
                        actionInput.type = 'hidden';
                        actionInput.name = 'action';
                        actionInput.value = 'approve';
                        form.appendChild(actionInput);
                        
                        const depositInput = document.createElement('input');
                        depositInput.type = 'hidden';
                        depositInput.name = 'deposit_id';
                        depositInput.value = id;
                        form.appendChild(depositInput);
                        
                        document.body.appendChild(form);
                        form.submit();
                    });
                }
            } else if (action === 'reject') {
                const reason = prompt('Enter reason for rejection:');
                if (reason !== null) {
                    if (confirm(`Reject ${selectedIds.length} selected deposit(s)?`)) {
                        // Submit form for each selected deposit
                        selectedIds.forEach(id => {
                            const form = document.createElement('form');
                            form.method = 'POST';
                            form.style.display = 'none';
                            
                            const actionInput = document.createElement('input');
                            actionInput.type = 'hidden';
                            actionInput.name = 'action';
                            actionInput.value = 'reject';
                            form.appendChild(actionInput);
                            
                            const depositInput = document.createElement('input');
                            depositInput.type = 'hidden';
                            depositInput.name = 'deposit_id';
                            depositInput.value = id;
                            form.appendChild(depositInput);
                            
                            const notesInput = document.createElement('input');
                            notesInput.type = 'hidden';
                            notesInput.name = 'admin_notes';
                            notesInput.value = reason;
                            form.appendChild(notesInput);
                            
                            document.body.appendChild(form);
                            form.submit();
                        });
                    }
                }
            } else if (action === 'delete') {
                if (confirm(`Delete ${selectedIds.length} selected deposit(s)? This action cannot be undone.`)) {
                    // Redirect to delete URLs
                    selectedIds.forEach(id => {
                        window.location.href = `?delete=${id}`;
                    });
                }
            }
        }
    </script>
</body>
</html>