<?php
/**
 * Admin - User Details
 */
$pageTitle = 'User Details';
require_once 'includes/header.php';

$userId = (int)($_GET['id'] ?? 0);

if (!$userId) {
    header('Location: users.php');
    exit;
}

// Get user data
$user = dbFetch("SELECT * FROM users WHERE id = :id", ['id' => $userId]);

if (!$user) {
    echo '<div class="alert alert-danger">User not found</div>';
    require_once 'includes/footer.php';
    exit;
}

// Get user's wallet
$userWallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = :id", ['id' => $userId]);

// Create virtual wallet structure to match template usage
$realWallet = ['id' => $userWallet['id'] ?? 0, 'balance' => $userWallet['balance'] ?? 0, 'type' => 'real'];
$demoWallet = ['id' => $userWallet['id'] ?? 0, 'balance' => $userWallet['demo_balance'] ?? 0, 'type' => 'demo'];

// Get recent trades
$trades = dbFetchAll(
    "SELECT * FROM trades WHERE user_id = :id ORDER BY created_at DESC LIMIT 10",
    ['id' => $userId]
);

// Get recent transactions
$transactions = dbFetchAll(
    "SELECT * FROM transactions WHERE user_id = :id ORDER BY created_at DESC LIMIT 10",
    ['id' => $userId]
);

// Get statistics
$totalDeposits = dbFetch("SELECT COALESCE(SUM(amount), 0) as total FROM transactions WHERE user_id = :id AND type = 'deposit' AND status = 'completed'", ['id' => $userId]);
$totalWithdrawals = dbFetch("SELECT COALESCE(SUM(amount), 0) as total FROM transactions WHERE user_id = :id AND type = 'withdrawal' AND status = 'completed'", ['id' => $userId]);
$totalTrades = dbCount('trades', "user_id = $userId");
$winTrades = dbCount('trades', "user_id = $userId AND result = 'win'");
$lossTrades = dbCount('trades', "user_id = $userId AND result = 'loss'");

// Handle balance update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'update_balance') {
        $walletType = $_POST['wallet_type'];
        $amount = floatval($_POST['amount']);
        $operation = $_POST['operation'];
        
        // Calculate new balance based on current state (fetched above)
        $currentBalance = $walletType === 'real' ? ($realWallet['balance'] ?? 0) : ($demoWallet['balance'] ?? 0);
        $newBalance = $operation === 'add' ? $currentBalance + $amount : $currentBalance - $amount;
        
        if ($newBalance < 0) $newBalance = 0;
        
        if ($walletType === 'real') {
            dbQuery("UPDATE user_wallets SET balance = :bal WHERE user_id = :id", ['bal' => $newBalance, 'id' => $userId]);
            dbQuery("UPDATE users SET balance = :bal WHERE id = :id", ['bal' => $newBalance, 'id' => $userId]);
        } else {
            dbQuery("UPDATE user_wallets SET demo_balance = :bal WHERE user_id = :id", ['bal' => $newBalance, 'id' => $userId]);
        }
            
            // Log transaction
            if ($amount > 0) {
                dbInsert('transactions', [
                    'user_id' => $userId,
                    'type' => $operation === 'add' ? 'admin_credit' : 'admin_debit',
                    'amount' => $amount,
                    'status' => 'completed',
                    'description' => 'Admin adjustment'
                ]);
            }
            
            header("Location: user-detail.php?id=$userId&success=Balance updated");
            exit;

    } elseif ($_POST['action'] === 'update_status') {
        $status = $_POST['status'];
        dbQuery("UPDATE users SET status = :status WHERE id = :id", ['status' => $status, 'id' => $userId]);
        header("Location: user-detail.php?id=$userId&success=Status updated");
        exit;
    }
}

// Refresh wallet data
$userWallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = :id", ['id' => $userId]);
$realWallet = ['id' => $userWallet['id'] ?? 0, 'balance' => $userWallet['balance'] ?? 0, 'type' => 'real'];
$demoWallet = ['id' => $userWallet['id'] ?? 0, 'balance' => $userWallet['demo_balance'] ?? 0, 'type' => 'demo'];
?>

<style>
.user-header {
    display: flex;
    align-items: center;
    gap: 1.5rem;
    margin-bottom: 2rem;
    padding: 1.5rem;
    background: var(--card);
    border-radius: var(--radius);
}
.user-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: linear-gradient(135deg, var(--primary), var(--secondary));
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    font-weight: 600;
    color: white;
}
.user-info h2 { margin-bottom: 0.25rem; }
.user-info p { color: var(--text-muted); margin: 0; }
.status-badge {
    display: inline-block;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 500;
}
.status-active { background: rgba(0, 208, 156, 0.2); color: #00d09c; }
.status-suspended { background: rgba(255, 82, 82, 0.2); color: #ff5252; }
.status-pending { background: rgba(255, 193, 7, 0.2); color: #ffc107; }

.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}
.info-card {
    background: var(--card);
    border-radius: var(--radius);
    padding: 1.25rem;
}
.info-card h4 {
    color: var(--text-muted);
    font-size: 0.85rem;
    margin-bottom: 0.5rem;
}
.info-card .value {
    font-size: 1.5rem;
    font-weight: 600;
}
.info-card .value.green { color: var(--success); }
.info-card .value.red { color: var(--danger); }

.detail-section {
    background: var(--card);
    border-radius: var(--radius);
    padding: 1.5rem;
    margin-bottom: 1.5rem;
}
.detail-section h3 {
    margin-bottom: 1rem;
    padding-bottom: 0.75rem;
    border-bottom: 1px solid var(--border);
}
.detail-row {
    display: flex;
    justify-content: space-between;
    padding: 0.5rem 0;
    border-bottom: 1px solid rgba(255,255,255,0.05);
}
.detail-row:last-child { border-bottom: none; }
.detail-row span:first-child { color: var(--text-muted); }

.balance-form {
    display: flex;
    gap: 0.5rem;
    margin-top: 1rem;
    flex-wrap: wrap;
}
.balance-form input, .balance-form select {
    padding: 0.5rem;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    color: var(--text);
}
.balance-form input[type="number"] { width: 120px; }
</style>

<?php if (isset($_GET['success'])): ?>
<div class="alert alert-success"><?= htmlspecialchars($_GET['success']) ?></div>
<?php endif; ?>

<a href="users.php" class="btn btn-secondary mb-3">
    <i class="fas fa-arrow-left"></i> Back to Users
</a>

<div class="user-header">
    <div class="user-avatar">
        <?= strtoupper(substr($user['first_name'] ?? $user['email'], 0, 1)) ?>
    </div>
    <div class="user-info">
        <h2><?= htmlspecialchars(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')) ?></h2>
        <p><?= htmlspecialchars($user['email']) ?></p>
        <p style="font-size: 0.85rem; margin-top: 0.5rem;">
            <span class="status-badge status-<?= $user['status'] ?>"><?= ucfirst($user['status']) ?></span>
            &nbsp;
            <span style="color: var(--text-muted)">Joined: <?= date('M d, Y', strtotime($user['created_at'])) ?></span>
        </p>
    </div>
    <div style="margin-left: auto;">
        <form method="POST" style="display: inline;">
            <input type="hidden" name="action" value="update_status">
            <select name="status" class="form-control" style="width: auto; display: inline-block;" onchange="this.form.submit()">
                <option value="active" <?= $user['status'] === 'active' ? 'selected' : '' ?>>Active</option>
                <option value="suspended" <?= $user['status'] === 'suspended' ? 'selected' : '' ?>>Suspended</option>
                <option value="pending" <?= $user['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
            </select>
        </form>
    </div>
</div>

<div class="info-grid">
    <div class="info-card">
        <h4>Real Balance</h4>
        <div class="value green">₹<?= number_format($realWallet['balance'] ?? 0, 2) ?></div>
        <form method="POST" class="balance-form">
            <input type="hidden" name="action" value="update_balance">
            <input type="hidden" name="wallet_type" value="real">
            <input type="number" name="amount" placeholder="Amount" step="0.01" min="0" required>
            <select name="operation">
                <option value="add">Add</option>
                <option value="subtract">Subtract</option>
            </select>
            <button type="submit" class="btn btn-sm btn-primary">Update</button>
        </form>
    </div>
    <div class="info-card">
        <h4>Demo Balance</h4>
        <div class="value">₹<?= number_format($demoWallet['balance'] ?? 0, 2) ?></div>
        <form method="POST" class="balance-form">
            <input type="hidden" name="action" value="update_balance">
            <input type="hidden" name="wallet_type" value="demo">
            <input type="number" name="amount" placeholder="Amount" step="0.01" min="0" required>
            <select name="operation">
                <option value="add">Add</option>
                <option value="subtract">Subtract</option>
            </select>
            <button type="submit" class="btn btn-sm btn-secondary">Update</button>
        </form>
    </div>
    <div class="info-card">
        <h4>Total Deposits</h4>
        <div class="value green">₹<?= number_format($totalDeposits['total'] ?? 0, 2) ?></div>
    </div>
    <div class="info-card">
        <h4>Total Withdrawals</h4>
        <div class="value red">₹<?= number_format($totalWithdrawals['total'] ?? 0, 2) ?></div>
    </div>
    <div class="info-card">
        <h4>Total Trades</h4>
        <div class="value"><?= $totalTrades ?></div>
    </div>
    <div class="info-card">
        <h4>Win/Loss</h4>
        <div class="value"><span class="green"><?= $winTrades ?></span> / <span class="red"><?= $lossTrades ?></span></div>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="detail-section">
            <h3><i class="fas fa-user"></i> Personal Information</h3>
            <div class="detail-row">
                <span>User ID</span>
                <span>#<?= $user['id'] ?></span>
            </div>
            <div class="detail-row">
                <span>Email</span>
                <span><?= htmlspecialchars($user['email']) ?></span>
            </div>
            <div class="detail-row">
                <span>Phone</span>
                <span><?= htmlspecialchars($user['phone'] ?? 'N/A') ?></span>
            </div>
            <div class="detail-row">
                <span>Country</span>
                <span><?= htmlspecialchars($user['country'] ?? 'N/A') ?></span>
            </div>
            <div class="detail-row">
                <span>KYC Status</span>
                <span class="badge badge-<?= $user['kyc_status'] === 'verified' ? 'success' : ($user['kyc_status'] === 'pending' ? 'warning' : 'secondary') ?>">
                    <?= ucfirst($user['kyc_status'] ?? 'unverified') ?>
                </span>
            </div>
            <div class="detail-row">
                <span>Referral Code</span>
                <span><?= htmlspecialchars($user['referral_code'] ?? 'N/A') ?></span>
            </div>
            <div class="detail-row">
                <span>Referred By</span>
                <span><?= htmlspecialchars($user['referred_by'] ?? 'N/A') ?></span>
            </div>
            <div class="detail-row">
                <span>Registered</span>
                <span><?= date('M d, Y H:i', strtotime($user['created_at'])) ?></span>
            </div>
            <div class="detail-row">
                <span>Last Login</span>
                <span><?= $user['last_login'] ? date('M d, Y H:i', strtotime($user['last_login'])) : 'Never' ?></span>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="detail-section">
            <h3><i class="fas fa-chart-line"></i> Recent Trades</h3>
            <?php if (empty($trades)): ?>
                <p class="text-muted">No trades yet</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Asset</th>
                                <th>Amount</th>
                                <th>Result</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($trades as $trade): ?>
                            <tr>
                                <td><?= htmlspecialchars($trade['symbol'] ?? 'N/A') ?></td>
                                <td>₹<?= number_format($trade['amount'], 2) ?></td>
                                <td>
                                    <?php if ($trade['result'] === 'win'): ?>
                                        <span class="text-success">Win</span>
                                    <?php elseif ($trade['result'] === 'loss'): ?>
                                        <span class="text-danger">Loss</span>
                                    <?php else: ?>
                                        <span class="text-warning">Pending</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= date('M d, H:i', strtotime($trade['created_at'])) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="detail-section">
    <h3><i class="fas fa-history"></i> Recent Transactions</h3>
    <?php if (empty($transactions)): ?>
        <p class="text-muted">No transactions yet</p>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Amount</th>
                        <th>Status</th>
                        <th>Description</th>
                        <th>Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($transactions as $tx): ?>
                    <tr>
                        <td><?= ucfirst(str_replace('_', ' ', $tx['type'])) ?></td>
                        <td class="<?= in_array($tx['type'], ['deposit', 'trade_win', 'admin_credit', 'referral_commission']) ? 'text-success' : 'text-danger' ?>">
                            <?= in_array($tx['type'], ['deposit', 'trade_win', 'admin_credit', 'referral_commission']) ? '+' : '-' ?>₹<?= number_format($tx['amount'], 2) ?>
                        </td>
                        <td>
                            <span class="badge badge-<?= $tx['status'] === 'completed' ? 'success' : ($tx['status'] === 'pending' ? 'warning' : 'danger') ?>">
                                <?= ucfirst($tx['status']) ?>
                            </span>
                        </td>
                        <td><?= htmlspecialchars($tx['description'] ?? '-') ?></td>
                        <td><?= date('M d, Y H:i', strtotime($tx['created_at'])) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

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