<?php
require_once dirname(__DIR__) . '/config/config.php';
requireLogin();
requireAdmin();

$pdo = getDBConnection();
$userModel = new User();
$isAdmin = $_SESSION['role'] === 'admin';

$error = $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';
    $userId = intval($_POST['user_id'] ?? 0);
    
    if ($action === 'update_status' && $userId) {
        $status = $_POST['status'] ?? '';
        if (in_array($status, ['active', 'suspended', 'banned'])) {
            $userModel->update($userId, ['status' => $status]);
            $success = 'User status updated';
        }
    } elseif ($action === 'add_balance' && $isAdmin && $userId) {
        $amount = floatval($_POST['amount'] ?? 0);
        $type = $_POST['type'] ?? 'bonus';
        if ($amount > 0) {
            $userModel->recordTransaction($userId, $type, $amount, 'Admin adjustment');
            $success = 'Balance updated';
        }
    } elseif ($action === 'change_role' && $isAdmin && $userId) {
        $newRole = $_POST['new_role'] ?? '';
        if (in_array($newRole, ['user', 'assistant'])) {
            $userModel->update($userId, ['role' => $newRole]);
            if ($newRole === 'assistant') {
                $userModel->setAssistantPermissions($userId, ['can_view_users' => 1, 'can_view_orders' => 1, 'can_manage_support' => 1]);
            }
            $success = 'User role updated';
        }
    } elseif ($action === 'reset_password' && $isAdmin && $userId) {
        $newPassword = $_POST['new_user_password'] ?? '';
        if (!empty($newPassword)) {
            if (strlen($newPassword) < 8) {
                $error = 'Password must be at least 8 characters';
            } else {
                $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$hashedPassword, $userId]);
                $success = 'User password has been reset';
            }
        } else {
            $error = 'Please enter a new password';
        }
    } elseif ($action === 'create_assistant' && $isAdmin) {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        
        if (empty($name) || empty($email) || empty($password)) {
            $error = 'All fields are required';
        } elseif ($userModel->emailExists($email)) {
            $error = 'Email already exists';
        } else {
            $result = $userModel->create(['name' => $name, 'email' => $email, 'password' => $password, 'role' => 'assistant', 'status' => 'active']);
            if ($result['success']) {
                $userModel->setAssistantPermissions($result['user_id'], ['can_view_users' => 1, 'can_view_orders' => 1, 'can_manage_support' => 1]);
                $success = 'Assistant created';
            } else {
                $error = $result['message'];
            }
        }
    }
}

$page = max(1, intval($_GET['page'] ?? 1));
$search = trim($_GET['search'] ?? '');
$roleFilter = $_GET['role'] ?? '';
$filters = [];
if ($roleFilter) $filters['role'] = $roleFilter;
if ($search) $filters['search'] = $search;

$result = $userModel->getAll($page, 20, $filters);
$users = $result['users'];
$pagination = $result['pagination'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Users - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #0A1628; color: #fff; min-height: 100vh; display: flex; }
        
        .sidebar { width: 260px; background: #0F2744; height: 100vh; position: fixed; left: 0; top: 0; z-index: 100; display: flex; flex-direction: column; transition: transform 0.3s; }
        .sidebar-header { padding: 1.5rem; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #1E3A5F; }
        .sidebar-header i { font-size: 1.5rem; color: #F5A623; }
        .sidebar-header span { font-weight: 700; color: #F5A623; font-size: 1.25rem; }
        .sidebar-nav { flex: 1; padding: 1rem 0; overflow-y: auto; }
        .nav-link { display: flex; align-items: center; gap: 12px; padding: 0.875rem 1.5rem; color: #E5E7EB; text-decoration: none; border-left: 3px solid transparent; }
        .nav-link:hover, .nav-link.active { background: #1E3A5F; color: #F5A623; border-left-color: #F5A623; }
        .nav-link i { width: 20px; text-align: center; }
        .nav-divider { height: 1px; background: #1E3A5F; margin: 0.75rem 1.5rem; }
        
        .main { flex: 1; margin-left: 260px; min-height: 100vh; }
        .header { background: #0F2744; padding: 1rem 1.5rem; display: flex; align-items: center; justify-content: space-between; position: sticky; top: 0; z-index: 50; }
        .header-toggle { background: none; border: none; color: #fff; font-size: 1.25rem; cursor: pointer; display: none; }
        
        .content { padding: 1.5rem; }
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; flex-wrap: wrap; gap: 1rem; }
        .page-title { font-size: 1.5rem; }
        .page-title i { color: #F5A623; margin-right: 0.5rem; }
        
        .btn { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.75rem 1.5rem; border: none; border-radius: 8px; font-size: 0.9rem; font-weight: 600; cursor: pointer; text-decoration: none; }
        .btn-gold { background: #F5A623; color: #0A1628; }
        .btn-gold:hover { background: #FFD93D; }
        .btn-navy { background: #1E3A5F; color: #fff; }
        .btn-red { background: #EF4444; color: #fff; }
        .btn-sm { padding: 0.5rem 1rem; font-size: 0.85rem; }
        
        .card { background: #0F2744; border-radius: 12px; margin-bottom: 1.5rem; overflow: hidden; }
        .card-header { padding: 1rem 1.5rem; border-bottom: 1px solid #1E3A5F; }
        .card-header h3 { margin: 0; font-size: 1.1rem; }
        .card-body { padding: 1.5rem; overflow-x: auto; }
        
        .tabs { display: flex; gap: 0.5rem; margin-bottom: 1rem; flex-wrap: wrap; }
        
        .filter-bar { display: flex; gap: 0.75rem; flex-wrap: wrap; margin-bottom: 1rem; }
        .form-control { padding: 0.75rem 1rem; background: #0A1628; border: 1px solid #1E3A5F; border-radius: 8px; color: #fff; font-size: 0.9rem; }
        .form-control:focus { outline: none; border-color: #F5A623; }
        
        table { width: 100%; border-collapse: collapse; min-width: 600px; }
        th, td { padding: 1rem; text-align: left; border-bottom: 1px solid #1E3A5F; }
        th { background: #1E3A5F; color: #F5A623; font-size: 0.85rem; text-transform: uppercase; }
        tr:hover { background: rgba(255,255,255,0.02); }
        
        .badge { display: inline-block; padding: 0.25rem 0.5rem; border-radius: 20px; font-size: 0.7rem; font-weight: 600; text-transform: uppercase; }
        .badge-success { background: rgba(16,185,129,0.2); color: #10B981; }
        .badge-warning { background: rgba(245,166,35,0.2); color: #F5A623; }
        .badge-danger { background: rgba(239,68,68,0.2); color: #EF4444; }
        .badge-info { background: rgba(59,130,246,0.2); color: #3B82F6; }
        
        .action-btn { width: 32px; height: 32px; border: none; border-radius: 8px; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; }
        .action-btn.edit { background: rgba(245,166,35,0.2); color: #F5A623; }
        
        .alert { padding: 1rem; border-radius: 8px; margin-bottom: 1rem; }
        .alert-success { background: rgba(16,185,129,0.2); border: 1px solid #10B981; color: #10B981; }
        .alert-danger { background: rgba(239,68,68,0.2); border: 1px solid #EF4444; color: #EF4444; }
        
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); display: none; align-items: center; justify-content: center; z-index: 2000; }
        .modal-overlay.active { display: flex; }
        .modal-content { background: #0F2744; border-radius: 12px; width: 90%; max-width: 500px; max-height: 90vh; overflow-y: auto; }
        .modal-header { padding: 1rem 1.5rem; border-bottom: 1px solid #1E3A5F; display: flex; justify-content: space-between; align-items: center; }
        .modal-header h3 { margin: 0; color: #F5A623; }
        .modal-close { background: none; border: none; color: #9CA3AF; font-size: 1.5rem; cursor: pointer; }
        .modal-body { padding: 1.5rem; }
        .modal-footer { padding: 1rem 1.5rem; border-top: 1px solid #1E3A5F; display: flex; gap: 0.5rem; justify-content: flex-end; flex-wrap: wrap; }
        
        .form-group { margin-bottom: 1rem; }
        .form-label { display: block; margin-bottom: 0.5rem; color: #E5E7EB; font-size: 0.9rem; }
        
        .input-wrapper { position: relative; }
        .input-wrapper .form-control { padding-right: 45px; }
        .toggle-pass { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; color: #9CA3AF; cursor: pointer; padding: 5px; }
        .toggle-pass:hover { color: #F5A623; }
        
        .pagination { display: flex; gap: 0.5rem; justify-content: center; margin-top: 1rem; }
        .pagination a, .pagination span { padding: 0.5rem 1rem; background: #1E3A5F; color: #fff; border-radius: 5px; text-decoration: none; }
        .pagination span { background: #F5A623; color: #0A1628; }
        
        .menu-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 99; display: none; }
        .menu-overlay.active { display: block; }
        
        .section-divider { border: none; border-top: 1px solid #1E3A5F; margin: 1.25rem 0; }
        .section-title { font-size: 0.85rem; color: #F5A623; margin-bottom: 0.75rem; font-weight: 600; }
        
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-260px); }
            .sidebar.active { transform: translateX(0); }
            .main { margin-left: 0; }
            .header-toggle { display: block; }
            .modal-footer { flex-direction: column; }
            .modal-footer .btn { width: 100%; justify-content: center; }
        }
    </style>
</head>
<body>
    <div class="menu-overlay" id="menuOverlay" onclick="toggleSidebar()"></div>
    
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header"><i class="fas fa-feather-alt"></i><span><?php echo SITE_NAME; ?></span></div>
        <nav class="sidebar-nav">
            <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
            <a href="users.php" class="nav-link active"><i class="fas fa-users"></i> Users</a>
            <a href="orders.php" class="nav-link"><i class="fas fa-shopping-cart"></i> Orders</a>
            <a href="fund-requests.php" class="nav-link"><i class="fas fa-money-bill"></i> Fund Requests</a>
            <a href="deposits.php" class="nav-link"><i class="fas fa-coins"></i> Deposit History</a>
            <div class="nav-divider"></div>
            <a href="smm-services.php" class="nav-link"><i class="fas fa-rocket"></i> SMM Services</a>
            <a href="sms-services.php" class="nav-link"><i class="fas fa-sms"></i> SMS Services</a>
            <div class="nav-divider"></div>
            <a href="offers.php" class="nav-link"><i class="fas fa-tags"></i> Offers</a>
            <a href="banners.php" class="nav-link"><i class="fas fa-ad"></i> Banners</a>
            <a href="support.php" class="nav-link"><i class="fas fa-headset"></i> Support</a>
            <?php if ($isAdmin): ?>
            <div class="nav-divider"></div>
            <a href="settings.php" class="nav-link"><i class="fas fa-cog"></i> Settings</a>
            <?php endif; ?>
            <div class="nav-divider"></div>
            <a href="<?php echo SITE_URL; ?>/logout.php" class="nav-link"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </nav>
    </aside>
    
    <main class="main">
        <header class="header">
            <button class="header-toggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
            <span><?php echo htmlspecialchars($_SESSION['name']); ?></span>
        </header>
        
        <div class="content">
            <div class="page-header">
                <h1 class="page-title"><i class="fas fa-users"></i> Users</h1>
                <?php if ($isAdmin): ?>
                <button class="btn btn-gold" onclick="document.getElementById('createModal').classList.add('active')"><i class="fas fa-user-plus"></i> Create Assistant</button>
                <?php endif; ?>
            </div>
            
            <?php if ($error): ?><div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?></div><?php endif; ?>
            <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?></div><?php endif; ?>
            
            <div class="tabs">
                <a href="?role=" class="btn <?php echo $roleFilter === '' ? 'btn-gold' : 'btn-navy'; ?> btn-sm">All</a>
                <a href="?role=user" class="btn <?php echo $roleFilter === 'user' ? 'btn-gold' : 'btn-navy'; ?> btn-sm">Users</a>
                <a href="?role=assistant" class="btn <?php echo $roleFilter === 'assistant' ? 'btn-gold' : 'btn-navy'; ?> btn-sm">Assistants</a>
            </div>
            
            <div class="card">
                <div class="card-header"><h3>Users (<?php echo $pagination['total_items']; ?>)</h3></div>
                <div class="card-body">
                    <form method="GET" class="filter-bar">
                        <input type="hidden" name="role" value="<?php echo htmlspecialchars($roleFilter); ?>">
                        <input type="text" name="search" class="form-control" placeholder="Search name or email..." value="<?php echo htmlspecialchars($search); ?>" style="flex:1;min-width:200px;">
                        <button type="submit" class="btn btn-gold btn-sm"><i class="fas fa-search"></i></button>
                    </form>
                    
                    <table>
                        <thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Role</th><th>Balance</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php foreach ($users as $user): ?>
                            <tr>
                                <td>#<?php echo $user['id']; ?></td>
                                <td><?php echo htmlspecialchars($user['name']); ?></td>
                                <td><?php echo htmlspecialchars($user['email']); ?></td>
                                <td><span class="badge <?php echo $user['role'] === 'admin' ? 'badge-danger' : ($user['role'] === 'assistant' ? 'badge-info' : 'badge-success'); ?>"><?php echo ucfirst($user['role']); ?></span></td>
                                <td style="color:#F5A623;"><?php echo formatCurrency($user['balance']); ?></td>
                                <td><span class="badge <?php echo $user['status'] === 'active' ? 'badge-success' : 'badge-danger'; ?>"><?php echo ucfirst($user['status']); ?></span></td>
                                <td><?php if ($user['role'] !== 'admin'): ?><button class="action-btn edit" onclick='editUser(<?php echo json_encode($user); ?>)'><i class="fas fa-edit"></i></button><?php endif; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <?php if ($pagination['total_pages'] > 1): ?>
                    <div class="pagination">
                        <?php if ($pagination['has_prev']): ?><a href="?role=<?php echo urlencode($roleFilter); ?>&search=<?php echo urlencode($search); ?>&page=<?php echo $pagination['current_page'] - 1; ?>">Prev</a><?php endif; ?>
                        <span><?php echo $pagination['current_page']; ?> / <?php echo $pagination['total_pages']; ?></span>
                        <?php if ($pagination['has_next']): ?><a href="?role=<?php echo urlencode($roleFilter); ?>&search=<?php echo urlencode($search); ?>&page=<?php echo $pagination['current_page'] + 1; ?>">Next</a><?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </main>
    
    <!-- Edit Modal -->
    <div class="modal-overlay" id="editModal">
        <div class="modal-content">
            <div class="modal-header"><h3><i class="fas fa-user-edit"></i> Edit User</h3><button class="modal-close" onclick="closeModal('editModal')">&times;</button></div>
            <form method="POST">
                <?php echo csrfTokenField(); ?>
                <input type="hidden" name="user_id" id="editUserId">
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">Name</label>
                        <input type="text" id="editUserName" class="form-control" disabled>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Email</label>
                        <input type="email" id="editUserEmail" class="form-control" disabled>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Status</label>
                        <select name="status" id="editUserStatus" class="form-control">
                            <option value="active">Active</option>
                            <option value="suspended">Suspended</option>
                            <option value="banned">Banned</option>
                        </select>
                    </div>
                    
                    <?php if ($isAdmin): ?>
                    <div class="form-group">
                        <label class="form-label">Role</label>
                        <select name="new_role" id="editUserRole" class="form-control">
                            <option value="user">User</option>
                            <option value="assistant">Assistant</option>
                        </select>
                    </div>
                    
                    <hr class="section-divider">
                    <div class="section-title"><i class="fas fa-wallet"></i> Add Balance</div>
                    
                    <div class="form-group">
                        <label class="form-label">Amount ($)</label>
                        <input type="number" name="amount" class="form-control" min="0" step="0.01" placeholder="0.00">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Type</label>
                        <select name="type" class="form-control">
                            <option value="bonus">Bonus</option>
                            <option value="refund">Refund</option>
                        </select>
                    </div>
                    
                    <hr class="section-divider">
                    <div class="section-title"><i class="fas fa-key"></i> Reset Password</div>
                    
                    <div class="form-group">
                        <label class="form-label">New Password</label>
                        <div class="input-wrapper">
                            <input type="password" name="new_user_password" id="newUserPass" class="form-control" placeholder="Leave empty to keep current" minlength="8">
                            <button type="button" class="toggle-pass" onclick="togglePass('newUserPass', this)"><i class="fas fa-eye"></i></button>
                        </div>
                        <small style="color:#9CA3AF;font-size:0.75rem;margin-top:0.25rem;display:block;">Minimum 8 characters. Leave empty to keep current password.</small>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-navy" onclick="closeModal('editModal')">Cancel</button>
                    <button type="submit" name="action" value="update_status" class="btn btn-gold"><i class="fas fa-check"></i> Update Status</button>
                    <?php if ($isAdmin): ?>
                    <button type="submit" name="action" value="change_role" class="btn btn-gold"><i class="fas fa-user-tag"></i> Change Role</button>
                    <button type="submit" name="action" value="add_balance" class="btn btn-gold"><i class="fas fa-plus"></i> Add Balance</button>
                    <button type="submit" name="action" value="reset_password" class="btn btn-red"><i class="fas fa-key"></i> Reset Password</button>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Create Assistant Modal -->
    <?php if ($isAdmin): ?>
    <div class="modal-overlay" id="createModal">
        <div class="modal-content">
            <div class="modal-header"><h3><i class="fas fa-user-plus"></i> Create Assistant</h3><button class="modal-close" onclick="closeModal('createModal')">&times;</button></div>
            <form method="POST">
                <?php echo csrfTokenField(); ?>
                <input type="hidden" name="action" value="create_assistant">
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">Full Name</label>
                        <input type="text" name="name" class="form-control" required placeholder="John Doe">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-control" required placeholder="assistant@example.com">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Password</label>
                        <div class="input-wrapper">
                            <input type="password" name="password" id="createPass" class="form-control" required minlength="8" placeholder="Minimum 8 characters">
                            <button type="button" class="toggle-pass" onclick="togglePass('createPass', this)"><i class="fas fa-eye"></i></button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-navy" onclick="closeModal('createModal')">Cancel</button>
                    <button type="submit" class="btn btn-gold"><i class="fas fa-user-plus"></i> Create</button>
                </div>
            </form>
        </div>
    </div>
    <?php endif; ?>
    
    <script>
        function toggleSidebar() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('menuOverlay').classList.toggle('active'); 
        }
        
        function closeModal(id) { 
            document.getElementById(id).classList.remove('active'); 
        }
        
        function editUser(user) {
            document.getElementById('editUserId').value = user.id;
            document.getElementById('editUserName').value = user.name;
            document.getElementById('editUserEmail').value = user.email;
            document.getElementById('editUserStatus').value = user.status;
            if (document.getElementById('editUserRole')) {
                document.getElementById('editUserRole').value = user.role;
            }
            // Clear password field
            if (document.getElementById('newUserPass')) {
                document.getElementById('newUserPass').value = '';
            }
            document.getElementById('editModal').classList.add('active');
        }
        
        function togglePass(inputId, btn) {
            var input = document.getElementById(inputId);
            var icon = btn.querySelector('i');
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }
    </script>
</body>
</html>