<?php
/**
 * Admin - User Management
 */

// Load required files for AJAX handling
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Auth.php';

// Check admin auth for AJAX
if (!auth()->isAdmin()) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }
}

// Handle AJAX POST requests BEFORE any HTML output
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['action'])) {
    header('Content-Type: application/json');
    
    $action = $_POST['action'] ?? '';
    $userId = (int)($_POST['user_id'] ?? 0);
    
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        echo json_encode(['success' => false, 'error' => 'Invalid request']);
        exit;
    }
    
    switch ($action) {
        case 'block':
            $reason = $_POST['reason'] ?? 'Blocked by admin';
            dbUpdate('users', ['status' => 'blocked', 'block_reason' => $reason], 'id = :id', ['id' => $userId]);
            logActivity('admin', auth()->getAdminId(), 'user_block', "Blocked user #{$userId}");
            echo json_encode(['success' => true, 'message' => 'User blocked successfully']);
            exit;
            
        case 'unblock':
            dbUpdate('users', ['status' => 'active', 'block_reason' => null], 'id = :id', ['id' => $userId]);
            logActivity('admin', auth()->getAdminId(), 'user_unblock', "Unblocked user #{$userId}");
            echo json_encode(['success' => true, 'message' => 'User unblocked successfully']);
            exit;
            
        case 'adjust_balance':
            $amount = (float)($_POST['amount'] ?? 0);
            $type = $_POST['type'] ?? 'add';
            $note = $_POST['note'] ?? 'Manual adjustment';
            
            if ($amount <= 0) {
                echo json_encode(['success' => false, 'error' => 'Invalid amount']);
                exit;
            }
            
            // Get current user
            $userInfo = dbFetch("SELECT id FROM users WHERE id = :id", ['id' => $userId]);
            if (!$userInfo) {
                echo json_encode(['success' => false, 'error' => 'User not found']);
                exit;
            }
            
            // Get current balance from user_wallets table
            $wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = :id", ['id' => $userId]);
            $currentBalance = $wallet ? (float)($wallet['balance'] ?? 0) : 0;
            
            $newBalance = $type === 'add' ? $currentBalance + $amount : $currentBalance - $amount;
            if ($newBalance < 0) {
                echo json_encode(['success' => false, 'error' => 'Insufficient balance for deduction']);
                exit;
            }
            
            // Update or create wallet
            if ($wallet) {
                dbQuery("UPDATE user_wallets SET balance = :bal WHERE user_id = :id", ['bal' => $newBalance, 'id' => $userId]);
            } else {
                dbInsert('user_wallets', ['user_id' => $userId, 'balance' => $newBalance]);
            }
            
            // Create transaction record
            dbInsert('transactions', [
                'transaction_id' => generateTransactionId('ADJ'),
                'user_id' => $userId,
                'type' => 'adjustment',
                'amount' => $type === 'add' ? $amount : -$amount,
                'balance_before' => $currentBalance,
                'balance_after' => $newBalance,
                'description' => $note,
                'status' => 'completed'
            ]);
            
            logActivity('admin', auth()->getAdminId(), 'balance_adjust', "Adjusted user #{$userId} balance by " . ($type === 'add' ? '+' : '-') . $amount);
            echo json_encode(['success' => true, 'message' => 'Balance adjusted successfully. New balance: ' . CURRENCY_SYMBOL . number_format($newBalance, 2)]);
            exit;
            
        case 'set_win_rate':
            $winRate = (int)($_POST['win_rate'] ?? 0);
            if ($winRate < 0 || $winRate > 100) {
                echo json_encode(['success' => false, 'error' => 'Win rate must be between 0 and 100']);
                exit;
            }
            
            dbUpdate('users', ['win_rate_override' => $winRate], 'id = :id', ['id' => $userId]);
            logActivity('admin', auth()->getAdminId(), 'win_rate_set', "Set user #{$userId} win rate to {$winRate}%");
            echo json_encode(['success' => true, 'message' => 'Win rate updated successfully']);
            exit;
            
        default:
            echo json_encode(['success' => false, 'error' => 'Invalid action']);
            exit;
    }
}

// Now include header for HTML page
$pageTitle = 'User Management';
require_once 'includes/header.php';

// Get filters
$status = get('status', '');
$search = get('search', '');
$page = max(1, (int)get('page', 1));
$perPage = 25;

// Build query
$where = "1=1";
$params = [];

if ($status) {
    $where .= " AND u.status = :status";
    $params['status'] = $status;
}

if ($search) {
    $where .= " AND (u.email LIKE :search OR u.first_name LIKE :search OR u.last_name LIKE :search OR u.user_id LIKE :search OR u.phone LIKE :search)";
    $params['search'] = "%{$search}%";
}

$total = dbFetch("SELECT COUNT(*) as count FROM users u WHERE {$where}", $params)['count'];
$pagination = paginate($total, $perPage, $page, 'users.php');

$users = dbFetchAll(
    "SELECT u.*, w.balance, w.demo_balance, w.total_deposit, w.total_withdrawal, w.total_trades, w.total_won, w.total_lost
     FROM users u 
     LEFT JOIN user_wallets w ON u.id = w.user_id 
     WHERE {$where}
     ORDER BY u.created_at DESC
     LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}",
    $params
);
?>

<style>
.filters-bar {
    display: flex;
    gap: 1rem;
    margin-bottom: 1.5rem;
    flex-wrap: wrap;
}

.filters-bar .form-control,
.filters-bar .form-select {
    width: auto;
    min-width: 150px;
}

.user-stats {
    display: flex;
    gap: 0.5rem;
    font-size: 0.75rem;
}

.user-stats span {
    padding: 0.2rem 0.5rem;
    background: var(--bg-tertiary);
    border-radius: var(--radius-sm);
}

/* Modal Fixes */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.7);
    display: flex; /* Changed from none to flex */
    align-items: center;
    justify-content: center;
    z-index: 9999;
    opacity: 0;
    visibility: hidden;
    pointer-events: none; /* Prevent clicks when hidden */
    transition: all 0.3s ease;
}

.modal-overlay.active {
    opacity: 1;
    visibility: visible;
    pointer-events: auto; /* Enable clicks when visible */
}

.modal {
    background: var(--bg-card, #151c28);
    border: 1px solid var(--border-color, #1f2937);
    border-radius: 12px;
    width: 100%;
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;
    transform: scale(0.9);
    transition: transform 0.3s ease;
    display: block; /* Ensure it's block */
}

.modal-overlay.active .modal {
    transform: scale(1);
}

</style>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <form class="filters-bar" method="GET">
            <input type="text" name="search" class="form-control" placeholder="Search users..." value="<?= htmlspecialchars($search) ?>">
            
            <select name="status" class="form-control form-select">
                <option value="">All Status</option>
                <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Active</option>
                <option value="blocked" <?= $status === 'blocked' ? 'selected' : '' ?>>Blocked</option>
                <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>Inactive</option>
            </select>
            
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-search"></i> Filter
            </button>
            
            <a href="users.php" class="btn btn-secondary">
                <i class="fas fa-times"></i> Clear
            </a>
        </form>
    </div>
</div>

<!-- Users Table -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">Users (<?= number_format($total) ?>)</h3>
        <button class="btn btn-primary btn-sm" onclick="exportUsers()">
            <i class="fas fa-download"></i> Export
        </button>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Balance</th>
                        <th>Deposits</th>
                        <th>Trades</th>
                        <th>Win Rate</th>
                        <th>Status</th>
                        <th>Joined</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td>
                            <div class="d-flex align-items-center gap-2">
                                <div class="user-avatar" style="width: 36px; height: 36px; font-size: 0.875rem;">
                                    <?= strtoupper(substr($user['first_name'] ?? $user['email'], 0, 1)) ?>
                                </div>
                                <div>
                                    <div class="font-semibold">
                                        <?= htmlspecialchars(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')) ?: 'N/A' ?>
                                    </div>
                                    <div class="text-muted" style="font-size: 0.75rem;">
                                        <?= htmlspecialchars($user['email']) ?>
                                        <br><?= $user['user_id'] ?>
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <div class="font-mono font-semibold"><?= formatCurrency($user['balance'] ?? 0) ?></div>
                            <div class="text-muted" style="font-size: 0.75rem;">Demo: <?= formatCurrency($user['demo_balance'] ?? 0) ?></div>
                        </td>
                        <td>
                            <div class="text-green"><?= formatCurrency($user['total_deposit'] ?? 0) ?></div>
                            <div class="text-red" style="font-size: 0.75rem;">-<?= formatCurrency($user['total_withdrawal'] ?? 0) ?></div>
                        </td>
                        <td>
                            <div><?= number_format($user['total_trades'] ?? 0) ?> trades</div>
                            <div class="user-stats">
                                <span class="text-green"><?= $user['total_won'] ?? 0 ?> W</span>
                                <span class="text-red"><?= $user['total_lost'] ?? 0 ?> L</span>
                            </div>
                        </td>
                        <td>
                            <?php
                            $totalUserTrades = ($user['total_won'] ?? 0) + ($user['total_lost'] ?? 0);
                            $userWinRate = $totalUserTrades > 0 ? round(($user['total_won'] / $totalUserTrades) * 100) : 0;
                            $overrideRate = $user['win_rate_override'];
                            ?>
                            <div><?= $userWinRate ?>%</div>
                            <?php if ($overrideRate !== null): ?>
                            <div class="text-yellow" style="font-size: 0.75rem;">Override: <?= $overrideRate ?>%</div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php
                            $statusClasses = ['active' => 'success', 'blocked' => 'danger', 'suspended' => 'warning'];
                            $statusClass = $statusClasses[$user['status']] ?? 'secondary';
                            ?>
                            <span class="badge badge-<?= $statusClass ?>"><?= ucfirst($user['status']) ?></span>
                            <?php if ($user['kyc_status'] === 'verified'): ?>
                            <span class="badge badge-info"><i class="fas fa-check"></i> KYC</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div><?= formatDate($user['created_at']) ?></div>
                            <div class="text-muted" style="font-size: 0.75rem;">
                                <?php if ($user['last_login']): ?>
                                Last: <?= timeAgo($user['last_login']) ?>
                                <?php else: ?>
                                Never logged in
                                <?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <div class="d-flex gap-1">
                                <a href="user-detail.php?id=<?= $user['id'] ?>" class="btn btn-sm btn-secondary" title="View Details">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <button class="btn btn-sm btn-secondary" onclick="adjustBalance(<?= $user['id'] ?>, '<?= htmlspecialchars($user['email'], ENT_QUOTES) ?>')" title="Adjust Balance">
                                    <i class="fas fa-wallet"></i>
                                </button>
                                <button class="btn btn-sm btn-secondary" onclick="setWinRate(<?= $user['id'] ?>, <?= $user['win_rate_override'] ?? 'null' ?>)" title="Set Win Rate">
                                    <i class="fas fa-percentage"></i>
                                </button>
                                <?php if ($user['status'] === 'active'): ?>
                                <button class="btn btn-sm btn-danger" onclick="blockUser(<?= $user['id'] ?>)" title="Block User">
                                    <i class="fas fa-ban"></i>
                                </button>
                                <?php else: ?>
                                <button class="btn btn-sm btn-success" onclick="unblockUser(<?= $user['id'] ?>)" title="Unblock User">
                                    <i class="fas fa-check"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($users)): ?>
                    <tr>
                        <td colspan="8" class="text-center text-muted py-4">No users found</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php if ($total > $perPage): ?>
    <div class="card-footer">
        <?= $pagination['html'] ?>
    </div>
    <?php endif; ?>
</div>

<!-- Balance Adjustment Modal -->
<div class="modal-overlay" id="balanceModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title">Adjust Balance</h3>
            <button class="modal-close" onclick="closeModal('balanceModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="balanceForm" onsubmit="submitBalanceForm(event)">
            <div class="modal-body">
                <input type="hidden" name="action" value="adjust_balance">
                <input type="hidden" name="user_id" id="balance_user_id">
                <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
                
                <p class="mb-3">Adjusting balance for: <strong id="balance_user_email"></strong></p>
                
                <div class="form-group">
                    <label class="form-label">Type</label>
                    <select name="type" class="form-control form-select" required>
                        <option value="add">Add Balance</option>
                        <option value="deduct">Deduct Balance</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Amount (<?= CURRENCY_SYMBOL ?>)</label>
                    <input type="number" name="amount" class="form-control" min="1" step="0.01" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Note</label>
                    <input type="text" name="note" class="form-control" placeholder="Reason for adjustment">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('balanceModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Adjust Balance</button>
            </div>
        </form>
    </div>
</div>

<!-- Win Rate Modal -->
<div class="modal-overlay" id="winRateModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title">Set Win Rate Override</h3>
            <button class="modal-close" onclick="closeModal('winRateModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="winRateForm" onsubmit="submitWinRateForm(event)">
            <div class="modal-body">
                <input type="hidden" name="action" value="set_win_rate">
                <input type="hidden" name="user_id" id="winrate_user_id">
                <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
                
                <p class="mb-3 text-muted">Set a custom win rate for this user. This overrides the global win rate setting.</p>
                
                <div class="form-group">
                    <label class="form-label">Win Rate (%)</label>
                    <input type="number" name="win_rate" id="win_rate_input" class="form-control" min="0" max="100" required>
                    <div class="form-text">0% = Always lose, 100% = Always win, Global default: <?= getSetting('global_win_rate', 50) ?>%</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('winRateModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Win Rate</button>
            </div>
        </form>
    </div>
</div>

<?php ob_start(); ?>
<script>
// Diagnostic Check
document.addEventListener('DOMContentLoaded', function() {
    console.log('Users page loaded');
    
    // Check jQuery
    if (typeof jQuery === 'undefined') {
        console.error('CRITICAL: jQuery is NOT loaded!');
        alert('Error: jQuery is not loaded. Please check your internet connection or console logs.');
    } else {
        console.log('jQuery v' + jQuery.fn.jquery + ' loaded');
    }
    
    // Check Modal Elements
    const modals = ['balanceModal', 'winRateModal'];
    modals.forEach(id => {
        const el = document.getElementById(id);
        if (el) {
            console.log('Modal found:', id);
        } else {
            console.error('CRITICAL: Modal missing:', id);
        }
    });

    // Check ajaxRequest
    if (typeof ajaxRequest !== 'function') {
        console.error('CRITICAL: ajaxRequest function is missing!');
    } else {
        console.log('ajaxRequest function is available');
    }
});
function openModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
        modal.classList.add('active');
        console.log('Opening modal:', id);
    } else {
        console.error('Modal not found:', id);
    }
}

function closeModal(id) {
    document.getElementById(id).classList.remove('active');
}

function adjustBalance(userId, email) {
    console.log('Adjust balance for:', userId, email);
    document.getElementById('balance_user_id').value = userId;
    document.getElementById('balance_user_email').textContent = email;
    openModal('balanceModal');
}

function setWinRate(userId, currentRate) {
    console.log('Set win rate for:', userId, currentRate);
    document.getElementById('winrate_user_id').value = userId;
    document.getElementById('win_rate_input').value = currentRate !== null ? currentRate : <?= getSetting('global_win_rate', 50) ?>;
    openModal('winRateModal');
}

function blockUser(userId) {
    const reason = prompt('Enter reason for blocking:');
    if (reason !== null) {
        console.log('Blocking user:', userId, reason);
        ajaxRequest('users.php', {
            action: 'block',
            user_id: userId,
            reason: reason,
            csrf_token: '<?= generateCsrfToken() ?>'
        }, function(response) {
            if (response.success) {
                showToast(response.message);
                location.reload();
            } else {
                showToast(response.error, 'danger');
            }
        });
    }
}

function unblockUser(userId) {
    if (confirm('Are you sure you want to unblock this user?')) {
        ajaxRequest('users.php', {
            action: 'unblock',
            user_id: userId,
            csrf_token: '<?= generateCsrfToken() ?>'
        }, function(response) {
            if (response.success) {
                showToast(response.message);
                location.reload();
            } else {
                showToast(response.error, 'danger');
            }
        });
    }
}

function submitBalanceForm(e) {
    e.preventDefault();
    const form = document.getElementById('balanceForm');
    const formData = new FormData(form);
    
    ajaxRequest('users.php', Object.fromEntries(formData), function(response) {
        if (response.success) {
            showToast(response.message);
            closeModal('balanceModal');
            location.reload();
        } else {
            showToast(response.error, 'danger');
        }
    });
}

function submitWinRateForm(e) {
    e.preventDefault();
    const form = document.getElementById('winRateForm');
    const formData = new FormData(form);
    
    ajaxRequest('users.php', Object.fromEntries(formData), function(response) {
        if (response.success) {
            showToast(response.message);
            closeModal('winRateModal');
            location.reload();
        } else {
            showToast(response.error, 'danger');
        }
    });
}

function exportUsers() {
    window.location.href = 'export.php?type=users&<?= http_build_query($_GET) ?>';
}
</script>
<?php $extraJs = ob_get_clean(); ?>

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