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

if(!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}

// Handle form submissions
if($_POST) {
    if(isset($_POST['update_balance'])) {
        $user_id = $_POST['user_id'];
        $new_balance = floatval($_POST['new_balance']);
        $reason = $_POST['reason'] ?? 'Admin adjustment';
        
        try {
            $pdo->beginTransaction();
            
            // Get current balance
            $stmt = $pdo->prepare("SELECT balance FROM user_wallets WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $current_wallet = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $current_balance = $current_wallet['balance'] ?? 0;
            $difference = $new_balance - $current_balance;
            
            // Update wallet balance
            $stmt = $pdo->prepare("INSERT INTO user_wallets (user_id, balance) VALUES (?, ?) ON DUPLICATE KEY UPDATE balance = ?");
            $stmt->execute([$user_id, $new_balance, $new_balance]);
            
            // Record transaction
            if($difference != 0) {
                $type = $difference > 0 ? 'bonus' : 'admin_deduction';
                $description = "Admin adjustment: {$reason} (Previous: {$current_balance}, New: {$new_balance})";
                
                $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, ?, ?, ?)");
                $stmt->execute([$user_id, $type, abs($difference), $description]);
            }
            
            $pdo->commit();
            $_SESSION['success'] = "Wallet balance updated successfully!";
            
        } catch(Exception $e) {
            $pdo->rollBack();
            $_SESSION['error'] = "Error updating balance: " . $e->getMessage();
        }
        
        header('Location: manage-wallets.php');
        exit;
        
    } elseif(isset($_POST['select_fan_of_month'])) {
        $month = $_POST['month'];
        $year = $_POST['year'];
        
        try {
            // Get all users who voted in the specified month, ordered by number of votes
            $stmt = $pdo->prepare("
                SELECT u.id, u.username, u.email, COUNT(v.id) as vote_count
                FROM users u 
                JOIN votes v ON u.id = v.user_id 
                WHERE YEAR(v.created_at) = ? AND MONTH(v.created_at) = ?
                GROUP BY u.id 
                HAVING vote_count > 0
                ORDER BY vote_count DESC, u.username ASC
            ");
            $stmt->execute([$year, $month]);
            $voters = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            if(empty($voters)) {
                $_SESSION['error'] = "No voters found for {$month}/{$year}";
            } else {
                // Select random user from top voters (those who voted multiple times get higher chance)
                $weighted_voters = [];
                foreach($voters as $voter) {
                    // Give more weight to users with more votes
                    $weight = min($voter['vote_count'], 10); // Cap at 10 to prevent extreme weighting
                    for($i = 0; $i < $weight; $i++) {
                        $weighted_voters[] = $voter;
                    }
                }
                
                if(!empty($weighted_voters)) {
                    $random_index = array_rand($weighted_voters);
                    $selected_fan = $weighted_voters[$random_index];
                    
                    // Award bonus coins to the Fan of the Month
                    $bonus_coins = 500; // 500 bonus coins
                    
                    $pdo->beginTransaction();
                    
                    // Update wallet
                    $stmt = $pdo->prepare("INSERT INTO user_wallets (user_id, balance) VALUES (?, ?) ON DUPLICATE KEY UPDATE balance = balance + ?");
                    $stmt->execute([$selected_fan['id'], $bonus_coins, $bonus_coins]);
                    
                    // Record transaction
                    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'bonus', ?, ?)");
                    $stmt->execute([$selected_fan['id'], $bonus_coins, "Fan of the Month {$month}/{$year} - {$bonus_coins} bonus coins"]);
                    
                    // Record Fan of the Month selection
                    $stmt = $pdo->prepare("INSERT INTO fan_of_month (user_id, month, year, bonus_coins) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$selected_fan['id'], $month, $year, $bonus_coins]);
                    
                    $pdo->commit();
                    
                    $_SESSION['success'] = "Fan of the Month selected: @{$selected_fan['username']} (Votes: {$selected_fan['vote_count']}) - Awarded {$bonus_coins} ZIT Coins!";
                } else {
                    $_SESSION['error'] = "No eligible voters found for selection.";
                }
            }
            
        } catch(Exception $e) {
            if(isset($pdo) && $pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $_SESSION['error'] = "Error selecting Fan of the Month: " . $e->getMessage();
        }
        
        header('Location: manage-wallets.php');
        exit;
    }
}

// Get all users with their wallet balances
$users = $pdo->query("
    SELECT u.id, u.username, u.email, u.created_at, 
           COALESCE(w.balance, 0) as balance,
           (SELECT COUNT(*) FROM votes v WHERE v.user_id = u.id) as total_votes,
           (SELECT COUNT(*) FROM transactions t WHERE t.user_id = u.id) as total_transactions
    FROM users u 
    LEFT JOIN user_wallets w ON u.id = w.user_id 
    ORDER BY w.balance DESC, u.username ASC
")->fetchAll(PDO::FETCH_ASSOC);

// Get transaction history
$transactions = $pdo->query("
    SELECT t.*, u.username 
    FROM transactions t 
    JOIN users u ON t.user_id = u.id 
    ORDER BY t.created_at DESC 
    LIMIT 100
")->fetchAll(PDO::FETCH_ASSOC);

// Get Fan of the Month history
$fan_history = $pdo->query("
    SELECT f.*, u.username 
    FROM fan_of_month f 
    JOIN users u ON f.user_id = u.id 
    ORDER BY f.year DESC, f.month DESC 
    LIMIT 12
")->fetchAll(PDO::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 Wallets - Admin</title>
    <link rel="stylesheet" href="../css/style.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .admin-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        .admin-nav {
            background: linear-gradient(135deg, #0d47a1, #1a73e8);
            color: white;
            padding: 1rem 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .admin-nav-container {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 2rem;
        }
        
        .admin-menu a {
            color: white;
            text-decoration: none;
            margin-left: 1.5rem;
            padding: 0.5rem 1rem;
            border-radius: 5px;
            transition: background 0.3s ease;
            font-weight: 500;
        }
        
        .admin-menu a:hover {
            background: rgba(255, 255, 255, 0.2);
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin: 2rem 0;
        }
        
        .stat-card {
            background: white;
            padding: 1.5rem;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            border-left: 4px solid #1a73e8;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            color: #1a73e8;
            margin-bottom: 0.5rem;
        }
        
        .section {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }
        
        .table-container {
            overflow-x: auto;
            margin-top: 1rem;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
        }
        
        th, td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }
        
        th {
            background: #f8f9fa;
            font-weight: 600;
            color: #0d47a1;
        }
        
        .balance-positive {
            color: #27ae60;
            font-weight: bold;
        }
        
        .balance-zero {
            color: #f39c12;
            font-weight: bold;
        }
        
        .btn-small {
            padding: 0.5rem 1rem;
            font-size: 0.8rem;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 2rem;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
        }
        
        .fan-of-month {
            background: linear-gradient(135deg, #ffd700, #ffed4e);
            padding: 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            border: 2px solid #ffc107;
        }
        
        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: 1fr 1fr;
            }
        }
    </style>
</head>
<body>
    <nav class="admin-nav">
        <div class="admin-nav-container">
            <div class="nav-logo">
                <a href="index.php" style="color: white; text-decoration: none; font-weight: bold; font-size: 1.2rem;">
                    <i class="fas fa-wallet"></i> Wallet Management
                </a>
            </div>
            <div class="admin-menu">
                <a href="index.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
                <a href="manage-players.php"><i class="fas fa-users"></i> Players</a>
                <a href="manage-coaches.php"><i class="fas fa-user-tie"></i> Coaches</a>
                <a href="manage-voting.php"><i class="fas fa-vote-yea"></i> Voting</a>
                <a href="manage-wallets.php"><i class="fas fa-wallet"></i> Wallets</a>
                <a href="site-settings.php"><i class="fas fa-cogs"></i> Settings</a>
                <a href="../logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </div>
    </nav>
    
    <div class="admin-container">
        <h1>Wallet & Coin Management</h1>
        
        <?php if(isset($_SESSION['success'])): ?>
            <div class="alert success"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div>
        <?php endif; ?>
        
        <?php if(isset($_SESSION['error'])): ?>
            <div class="alert error"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></div>
        <?php endif; ?>
        
        <!-- Statistics -->
        <div class="stats-grid">
            <?php
            $total_coins = $pdo->query("SELECT SUM(balance) as total FROM user_wallets")->fetchColumn();
            $total_users = count($users);
            $active_voters = $pdo->query("SELECT COUNT(DISTINCT user_id) FROM votes")->fetchColumn();
            $total_transactions = $pdo->query("SELECT COUNT(*) FROM transactions")->fetchColumn();
            ?>
            
            <div class="stat-card">
                <div class="stat-number"><?php echo number_format($total_coins, 0); ?></div>
                <div class="stat-label">Total ZIT Coins</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-number"><?php echo $total_users; ?></div>
                <div class="stat-label">Total Users</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-number"><?php echo $active_voters; ?></div>
                <div class="stat-label">Active Voters</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-number"><?php echo $total_transactions; ?></div>
                <div class="stat-label">Total Transactions</div>
            </div>
        </div>
        
        <!-- Fan of the Month Section -->
        <div class="section">
            <h2><i class="fas fa-crown"></i> Fan of the Month</h2>
            
            <div class="fan-of-month">
                <h3>Select Fan of the Month</h3>
                <p>Randomly select a fan from users who voted this month. Users with more votes have higher chances!</p>
                
                <form method="POST" style="display: flex; gap: 1rem; align-items: end; flex-wrap: wrap;">
                    <div>
                        <label>Month:</label>
                        <select name="month" required>
                            <?php for($i = 1; $i <= 12; $i++): ?>
                                <option value="<?php echo $i; ?>" <?php echo $i == date('n') ? 'selected' : ''; ?>>
                                    <?php echo date('F', mktime(0, 0, 0, $i, 1)); ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    
                    <div>
                        <label>Year:</label>
                        <select name="year" required>
                            <?php for($i = date('Y') - 1; $i <= date('Y') + 1; $i++): ?>
                                <option value="<?php echo $i; ?>" <?php echo $i == date('Y') ? 'selected' : ''; ?>>
                                    <?php echo $i; ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    
                    <button type="submit" name="select_fan_of_month" class="btn btn-primary">
                        <i class="fas fa-random"></i> Select Random Fan
                    </button>
                </form>
            </div>
            
            <?php if($fan_history): ?>
            <h3 style="margin-top: 2rem;">Recent Fan of the Month</h3>
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>Month/Year</th>
                            <th>Fan</th>
                            <th>Bonus Coins</th>
                            <th>Selected On</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($fan_history as $fan): ?>
                        <tr>
                            <td><?php echo date('F Y', mktime(0, 0, 0, $fan['month'], 1, $fan['year'])); ?></td>
                            <td><strong>@<?php echo $fan['username']; ?></strong></td>
                            <td class="balance-positive">+<?php echo $fan['bonus_coins']; ?> ZIT</td>
                            <td><?php echo date('M j, Y', strtotime($fan['created_at'])); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- User Wallets -->
        <div class="section">
            <h2><i class="fas fa-wallet"></i> User Wallets</h2>
            
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>User</th>
                            <th>Email</th>
                            <th>Balance</th>
                            <th>Total Votes</th>
                            <th>Transactions</th>
                            <th>Joined</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($users as $user): ?>
                        <tr>
                            <td>
                                <strong>@<?php echo $user['username']; ?></strong>
                            </td>
                            <td><?php echo $user['email']; ?></td>