<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

session_start();
include('../include/config.php');

// Check if user is admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ../login.php');
    exit();
}

// Verify admin status
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || $user['is_admin'] != 1) {
    header('Location: ../user/dashboard.php');
    exit();
}

// Handle Transaction Deletion
if (isset($_GET['delete'])) {
    $transaction_id = (int)$_GET['delete'];
    
    try {
        $stmt = $pdo->prepare("DELETE FROM transactions WHERE id = ?");
        $stmt->execute([$transaction_id]);
        
        $_SESSION['success'] = "Transaction deleted successfully!";
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error deleting transaction!";
    }
    
    header('Location: manage-emails.php');
    exit();
}

// Pagination and filtering
$records_per_page = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

// Filters
$status_filter = isset($_GET['status']) && !empty($_GET['status']) ? $_GET['status'] : null;
$user_filter = isset($_GET['user_id']) && is_numeric($_GET['user_id']) ? (int)$_GET['user_id'] : null;
$exchange_filter = isset($_GET['exchange']) && !empty($_GET['exchange']) ? $_GET['exchange'] : null;
$search = isset($_GET['search']) && !empty($_GET['search']) ? trim($_GET['search']) : null;

// Build query
$where_conditions = [];
$params = [];

if ($status_filter) {
    $where_conditions[] = "status = ?";
    $params[] = $status_filter;
}

if ($user_filter) {
    $where_conditions[] = "user_id = ?";
    $params[] = $user_filter;
}

if ($exchange_filter) {
    $where_conditions[] = "exchange = ?";
    $params[] = $exchange_filter;
}

if ($search) {
    $where_conditions[] = "(username LIKE ? OR receiver_address LIKE ? OR transaction_hash LIKE ?)";
    $search_param = "%{$search}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count
$count_query = "SELECT COUNT(*) FROM transactions $where_clause";
$count_stmt = $pdo->prepare($count_query);
$count_stmt->execute($params);
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $records_per_page);

// Fetch transactions
$query = "SELECT * FROM transactions $where_clause ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($query);

if (!empty($params)) {
    $param_index = 1;
    foreach ($params as $value) {
        $stmt->bindValue($param_index++, $value);
    }
}

$stmt->bindValue(':limit', (int)$records_per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
$stmt->execute();
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$stats_query = "
    SELECT 
        COUNT(*) as total_transactions,
        COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_count,
        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
        COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_count,
        COALESCE(SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END), 0) as total_completed_amount,
        COALESCE(SUM(amount), 0) as total_amount,
        COUNT(DISTINCT user_id) as unique_users,
        COUNT(DISTINCT exchange) as unique_exchanges
    FROM transactions
";
$stats = $pdo->query($stats_query)->fetch(PDO::FETCH_ASSOC);

// Get top exchanges
$top_exchanges = $pdo->query("
    SELECT exchange, COUNT(*) as count, SUM(amount) as total_amount 
    FROM transactions 
    WHERE status = 'completed'
    GROUP BY exchange 
    ORDER BY count DESC 
    LIMIT 5
")->fetchAll(PDO::FETCH_ASSOC);

// Get top users
$top_users = $pdo->query("
    SELECT username, COUNT(*) as transaction_count, SUM(amount) as total_amount 
    FROM transactions 
    WHERE status = 'completed'
    GROUP BY user_id, username 
    ORDER BY transaction_count DESC 
    LIMIT 5
")->fetchAll(PDO::FETCH_ASSOC);

// Fetch all users for filter dropdown
$all_users = $pdo->query("SELECT DISTINCT id, username FROM users ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC);

$page_title = WEB_NAME . " | Manage Transactions";
?>
<!DOCTYPE html>
<html lang="en" class="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        .stat-card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
        }
    </style>
    <link rel="shortcut icon" type="image/png" href="<?php echo $site_data['web_url']; ?>/public/favicons/favicon.png">
</head>
<body class="bg-gradient-to-br from-slate-50 to-slate-100 min-h-screen p-4 lg:p-8">

<div class="max-w-7xl mx-auto space-y-6">
    
    <!-- Header -->
    <div class="flex items-center justify-between">
        <div>
            <h1 class="text-3xl font-bold text-slate-900">Manage Transactions</h1>
            <p class="text-slate-600 mt-1">View and manage all platform transactions</p>
        </div>
        <a href="dashboard.php" class="px-4 py-2 bg-slate-200 hover:bg-slate-300 rounded-lg transition-colors">
            <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
        </a>
    </div>

    <!-- Alert Messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="p-4 bg-green-50 border border-green-200 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-check-circle text-green-600 mr-3"></i>
                <span class="text-green-800 font-medium"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></span>
            </div>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="p-4 bg-red-50 border border-red-200 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-times-circle text-red-600 mr-3"></i>
                <span class="text-red-800 font-medium"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></span>
            </div>
        </div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div class="stat-card bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between mb-2">
                <div class="text-sm text-slate-600">Total Transactions</div>
                <i class="fas fa-exchange-alt text-blue-600"></i>
            </div>
            <div class="text-2xl font-bold text-slate-900"><?php echo number_format($stats['total_transactions']); ?></div>
        </div>
        
        <div class="stat-card bg-green-50 rounded-xl shadow p-4">
            <div class="flex items-center justify-between mb-2">
                <div class="text-sm text-green-600">Completed</div>
                <i class="fas fa-check-circle text-green-600"></i>
            </div>
            <div class="text-2xl font-bold text-green-700"><?php echo number_format($stats['completed_count']); ?></div>
        </div>
        
        <div class="stat-card bg-yellow-50 rounded-xl shadow p-4">
            <div class="flex items-center justify-between mb-2">
                <div class="text-sm text-yellow-600">Pending</div>
                <i class="fas fa-clock text-yellow-600"></i>
            </div>
            <div class="text-2xl font-bold text-yellow-700"><?php echo number_format($stats['pending_count']); ?></div>
        </div>
        
        <div class="stat-card bg-red-50 rounded-xl shadow p-4">
            <div class="flex items-center justify-between mb-2">
                <div class="text-sm text-red-600">Failed</div>
                <i class="fas fa-times-circle text-red-600"></i>
            </div>
            <div class="text-2xl font-bold text-red-700"><?php echo number_format($stats['failed_count']); ?></div>
        </div>
    </div>

    <!-- More Statistics -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="stat-card bg-gradient-to-br from-purple-50 to-blue-50 rounded-xl shadow p-4">
            <div class="text-sm text-purple-700 mb-1">Total Amount (All)</div>
            <div class="text-2xl font-bold text-purple-900"><?php echo number_format($stats['total_amount'], 2); ?></div>
        </div>
        
        <div class="stat-card bg-gradient-to-br from-green-50 to-emerald-50 rounded-xl shadow p-4">
            <div class="text-sm text-green-700 mb-1">Completed Amount</div>
            <div class="text-2xl font-bold text-green-900"><?php echo number_format($stats['total_completed_amount'], 2); ?></div>
        </div>
        
        <div class="stat-card bg-gradient-to-br from-orange-50 to-yellow-50 rounded-xl shadow p-4">
            <div class="text-sm text-orange-700 mb-1">Unique Users</div>
            <div class="text-2xl font-bold text-orange-900"><?php echo number_format($stats['unique_users']); ?></div>
        </div>
    </div>

    <!-- Top Statistics -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <!-- Top Exchanges -->
        <div class="bg-white rounded-xl shadow p-4">
            <h3 class="text-lg font-bold text-slate-900 mb-4">
                <i class="fas fa-trophy text-yellow-500 mr-2"></i>Top Exchanges
            </h3>
            <div class="space-y-2">
                <?php foreach ($top_exchanges as $ex): ?>
                <div class="flex items-center justify-between p-2 bg-slate-50 rounded">
                    <div>
                        <div class="font-semibold text-slate-900"><?php echo htmlspecialchars($ex['exchange']); ?></div>
                        <div class="text-xs text-slate-600"><?php echo number_format($ex['count']); ?> transactions</div>
                    </div>
                    <div class="text-sm font-semibold text-green-600">
                        <?php echo number_format($ex['total_amount'], 2); ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Top Users -->
        <div class="bg-white rounded-xl shadow p-4">
            <h3 class="text-lg font-bold text-slate-900 mb-4">
                <i class="fas fa-users text-blue-500 mr-2"></i>Top Users
            </h3>
            <div class="space-y-2">
                <?php foreach ($top_users as $tu): ?>
                <div class="flex items-center justify-between p-2 bg-slate-50 rounded">
                    <div>
                        <div class="font-semibold text-slate-900"><?php echo htmlspecialchars($tu['username']); ?></div>
                        <div class="text-xs text-slate-600"><?php echo number_format($tu['transaction_count']); ?> transactions</div>
                    </div>
                    <div class="text-sm font-semibold text-green-600">
                        <?php echo number_format($tu['total_amount'], 2); ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow p-4">
        <form method="GET" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-5 gap-3">
                <input type="text" name="search" value="<?php echo htmlspecialchars($search ?? ''); ?>" 
                       placeholder="Search username, address, hash..."
                       class="px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                
                <select name="user_id" class="px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="">All Users</option>
                    <?php foreach ($all_users as $u): ?>
                        <option value="<?php echo $u['id']; ?>" <?php echo $user_filter == $u['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($u['username']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                
                <select name="exchange" class="px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="">All Exchanges</option>
                    <option value="Binance" <?php echo $exchange_filter == 'Binance' ? 'selected' : ''; ?>>Binance</option>
                    <option value="Coinbase" <?php echo $exchange_filter == 'Coinbase' ? 'selected' : ''; ?>>Coinbase</option>
                    <option value="OKX" <?php echo $exchange_filter == 'OKX' ? 'selected' : ''; ?>>OKX</option>
                    <option value="CashApp" <?php echo $exchange_filter == 'CashApp' ? 'selected' : ''; ?>>CashApp</option>
                    <option value="Zelle" <?php echo $exchange_filter == 'Zelle' ? 'selected' : ''; ?>>Zelle</option>
                    <option value="PayPal" <?php echo $exchange_filter == 'PayPal' ? 'selected' : ''; ?>>PayPal</option>
                    <option value="Gcash" <?php echo $exchange_filter == 'Gcash' ? 'selected' : ''; ?>>Gcash</option>
                </select>
                
                <select name="status" class="px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="">All Status</option>
                    <option value="completed" <?php echo $status_filter == 'completed' ? 'selected' : ''; ?>>Completed</option>
                    <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="failed" <?php echo $status_filter == 'failed' ? 'selected' : ''; ?>>Failed</option>
                </select>
                
                <div class="flex gap-2">
                    <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
                        <i class="fas fa-search mr-2"></i>Filter
                    </button>
                    
                    <?php if ($search || $status_filter || $user_filter || $exchange_filter): ?>
                    <a href="manage-emails.php" class="px-4 py-2 bg-slate-200 hover:bg-slate-300 text-slate-700 rounded-lg transition-colors">
                        <i class="fas fa-times"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </form>
    </div>

    <!-- Transactions List -->
    <div class="bg-white rounded-2xl shadow-lg p-6">
        <h2 class="text-xl font-bold text-slate-900 mb-6">
            <i class="fas fa-list text-blue-600 mr-2"></i>Transactions (<?php echo $total_records; ?>)
        </h2>

        <?php if (count($transactions) > 0): ?>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="border-b border-slate-200">
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">ID</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">User</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Exchange</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Coin/Amount</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Receiver</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Hash</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Status</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Date</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($transactions as $tx): 
                        $status_colors = [
                            'completed' => 'bg-green-100 text-green-800',
                            'pending' => 'bg-yellow-100 text-yellow-800',
                            'failed' => 'bg-red-100 text-red-800'
                        ];
                    ?>
                        <tr class="border-b border-slate-100 hover:bg-slate-50">
                            <td class="p-3 text-sm font-mono text-slate-600">#<?php echo $tx['id']; ?></td>
                            <td class="p-3">
                                <div class="font-semibold text-slate-900"><?php echo htmlspecialchars($tx['username']); ?></div>
                                <div class="text-xs text-slate-500"><?php echo htmlspecialchars($tx['sender_email']); ?></div>
                            </td>
                            <td class="p-3 text-sm text-slate-700"><?php echo htmlspecialchars($tx['exchange']); ?></td>
                            <td class="p-3">
                                <?php if ($tx['coin']): ?>
                                    <div class="font-semibold text-blue-600"><?php echo htmlspecialchars($tx['coin']); ?></div>
                                    <div class="text-xs text-slate-600"><?php echo number_format($tx['amount'], 8); ?></div>
                                <?php else: ?>
                                    <div class="font-semibold text-green-600"><?php echo number_format($tx['amount'], 2); ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="p-3">
                                <?php if ($tx['receiver_address']): ?>
                                    <div class="text-xs font-mono text-slate-600 max-w-[150px] truncate" title="<?php echo htmlspecialchars($tx['receiver_address']); ?>">
                                        <?php echo htmlspecialchars($tx['receiver_address']); ?>
                                    </div>
                                <?php endif; ?>
                                <div class="text-xs text-slate-500"><?php echo htmlspecialchars($tx['receiver_email']); ?></div>
                            </td>
                            <td class="p-3">
                                <div class="text-xs font-mono text-slate-600 max-w-[120px] truncate" title="<?php echo htmlspecialchars($tx['transaction_hash']); ?>">
                                    <?php echo htmlspecialchars(substr($tx['transaction_hash'], 0, 12)); ?>...
                                </div>
                            </td>
                            <td class="p-3">
                                <span class="px-2 py-1 rounded text-xs font-semibold <?php echo $status_colors[$tx['status']]; ?>">
                                    <?php echo ucfirst($tx['status']); ?>
                                </span>
                            </td>
                            <td class="p-3 text-xs text-slate-600">
                                <?php echo date('M d, Y', strtotime($tx['created_at'])); ?>
                                <div class="text-xs text-slate-400"><?php echo date('H:i', strtotime($tx['created_at'])); ?></div>
                            </td>
                            <td class="p-3">
                                <a href="?delete=<?php echo $tx['id']; ?>" onclick="return confirm('Delete this transaction?')" 
                                   class="px-3 py-1 bg-red-600 hover:bg-red-700 text-white rounded text-xs">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="flex items-center justify-center gap-3 mt-6">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $status_filter ? '&status=' . $status_filter : ''; ?><?php echo $user_filter ? '&user_id=' . $user_filter : ''; ?><?php echo $exchange_filter ? '&exchange=' . urlencode($exchange_filter) : ''; ?>" 
                   class="px-4 py-2 bg-slate-200 hover:bg-slate-300 rounded-lg transition-colors">
                    <i class="fas fa-chevron-left"></i>
                </a>
            <?php endif; ?>

            <span class="px-4 py-2 bg-slate-100 rounded-lg text-sm font-medium">
                Page <?php echo $page; ?> of <?php echo $total_pages; ?>
            </span>

            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $status_filter ? '&status=' . $status_filter : ''; ?><?php echo $user_filter ? '&user_id=' . $user_filter : ''; ?><?php echo $exchange_filter ? '&exchange=' . urlencode($exchange_filter) : ''; ?>" 
                   class="px-4 py-2 bg-slate-200 hover:bg-slate-300 rounded-lg transition-colors">
                    <i class="fas fa-chevron-right"></i>
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <?php else: ?>
        <div class="text-center py-12">
            <i class="fas fa-exchange-alt text-4xl text-slate-300 mb-4"></i>
            <p class="text-slate-600">No transactions found.</p>
        </div>
        <?php endif; ?>
    </div>

</div>

</body>
</html>