<?php
require_once 'config.php';
$adminId = requireAdminAuth();
$admin = getCurrentAdmin();

$pdo = getDBConnection();

// Handle search and filters
$search = sanitizeInput($_GET['search'] ?? '');
$level = isset($_GET['level']) ? (int)$_GET['level'] : null;
$status = $_GET['status'] ?? 'all';

// Build query
$where = ["is_deleted = 0"];
$params = [];

if (!empty($search)) {
    $where[] = "(user_name LIKE ? OR email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($level !== null) {
    // Map numeric input to level names for backwards compatibility
    $levelMap = [0 => 'guest', 1 => 'registered', 2 => 'pro', 3 => 'vip'];
    $mappedLevel = $levelMap[$level] ?? null;
    if ($mappedLevel) {
        $where[] = "user_level = ?";
        $params[] = $mappedLevel;
    }
} elseif (isset($_GET['level_name'])) {
    $levelName = sanitizeInput($_GET['level_name']);
    $validLevels = ['guest', 'registered', 'pro', 'vip'];
    if (in_array($levelName, $validLevels)) {
        $where[] = "user_level = ?";
        $params[] = $levelName;
    }
}

if ($status === 'verified') {
    $where[] = "is_verified = 1";
} elseif ($status === 'pending') {
    $where[] = "is_verified = 0";
}

$whereClause = implode(" AND ", $where);

// Get total count
$countStmt = $pdo->prepare("SELECT COUNT(*) as total FROM users WHERE $whereClause");
$countStmt->execute($params);
$totalUsers = $countStmt->fetch()['total'];

// Get users
$stmt = $pdo->prepare("SELECT * FROM users WHERE $whereClause ORDER BY created_at DESC");
$stmt->execute($params);
$users = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Users - Admin Panel</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h1>Manage Users</h1>
            <div class="header-actions">
                <button onclick="showAddUserModal()" class="btn btn-primary">+ Add User</button>
            </div>
        </div>
        
        <div class="content-card">
            <div class="filters">
                <form method="GET" action="" class="filter-form">
                    <input type="text" name="search" placeholder="Search by name or email..." value="<?php echo htmlspecialchars($search); ?>" class="search-input">
                    
                    <select name="level_name" class="filter-select">
                        <option value="">All Levels</option>
                        <option value="guest" <?php echo (isset($_GET['level_name']) && $_GET['level_name'] === 'guest') ? 'selected' : ''; ?>>Guest</option>
                        <option value="registered" <?php echo (isset($_GET['level_name']) && $_GET['level_name'] === 'registered') ? 'selected' : ''; ?>>Registered</option>
                        <option value="pro" <?php echo (isset($_GET['level_name']) && $_GET['level_name'] === 'pro') ? 'selected' : ''; ?>>Pro</option>
                        <option value="vip" <?php echo (isset($_GET['level_name']) && $_GET['level_name'] === 'vip') ? 'selected' : ''; ?>>VIP</option>
                    </select>
                    
                    <select name="status" class="filter-select">
                        <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>All Status</option>
                        <option value="verified" <?php echo $status === 'verified' ? 'selected' : ''; ?>>Verified</option>
                        <option value="pending" <?php echo $status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                    </select>
                    
                    <button type="submit" class="btn btn-secondary">Filter</button>
                    <a href="users.php" class="btn btn-outline">Clear</a>
                </form>
            </div>
            
            <div class="results-info">
                Found <?php echo number_format($totalUsers); ?> user(s)
            </div>
            
            <div class="table-responsive">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Profile</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Level</th>
                            <th>Status</th>
                            <th>Joined</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($users)): ?>
                            <tr>
                                <td colspan="8" style="text-align: center; padding: 30px; color: #999;">
                                    No users found
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($users as $user): ?>
                                <tr>
                                    <td><?php echo $user['id']; ?></td>
                                    <td>
                                        <img src="<?php echo htmlspecialchars($user['profile_picture'] ?? 'https://api.dicebear.com/7.x/fun-emoji/jpg?seed=default'); ?>" 
                                             alt="Profile" 
                                             style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;">
                                    </td>
                                    <td><?php echo htmlspecialchars($user['user_name'] ?? 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars($user['email']); ?></td>
                                    <td>
                                        <?php 
                                        $levelColors = [
                                            'guest' => 'badge-level-0',
                                            'registered' => 'badge-level-3',
                                            'pro' => 'badge-level-7',
                                            'vip' => 'badge-level-10'
                                        ];
                                        $levelClass = $levelColors[$user['user_level']] ?? 'badge-level-3';
                                        $levelName = ucfirst($user['user_level']);
                                        ?>
                                        <span class="badge <?php echo $levelClass; ?>">
                                            <?php echo $levelName; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($user['is_verified']): ?>
                                            <span class="badge badge-success">Verified</span>
                                        <?php else: ?>
                                            <span class="badge badge-warning">Pending</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td>
                                    <td>
                                        <div class="action-buttons">
                                            <button onclick="editUser(<?php echo $user['id']; ?>)" class="btn-icon" title="Edit">✏️</button>
                                            <button onclick="deleteUser(<?php echo $user['id']; ?>)" class="btn-icon" title="Delete">🗑️</button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Add User Modal -->
    <div id="addUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Add New User</h2>
                <span class="close" onclick="closeModal('addUserModal')">&times;</span>
            </div>
            <form id="addUserForm">
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" name="name" required placeholder="Enter username">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" required placeholder="user@example.com">
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" name="password" required placeholder="Minimum 6 characters">
                </div>
                <div class="form-group">
                    <label>User Level</label>
                    <select name="user_level" required>
                        <option value="guest">Guest</option>
                        <option value="registered" selected>Registered</option>
                        <option value="pro">Pro</option>
                        <option value="vip">VIP</option>
                    </select>
                </div>
                <div class="modal-actions">
                    <button type="button" onclick="closeModal('addUserModal')" class="btn btn-outline">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add User</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Edit User Modal -->
    <div id="editUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Edit User</h2>
                <span class="close" onclick="closeModal('editUserModal')">&times;</span>
            </div>
            <form id="editUserForm">
                <input type="hidden" name="user_id" id="edit_user_id">
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" name="name" id="edit_name" required>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" id="edit_email" required>
                </div>
                <div class="form-group">
                    <label>User Level</label>
                    <select name="user_level" id="edit_level" required>
                        <option value="guest">Guest</option>
                        <option value="registered">Registered</option>
                        <option value="pro">Pro</option>
                        <option value="vip">VIP</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" name="email_verified" id="edit_verified">
                        Email Verified
                    </label>
                </div>
                        Email Verified
                    </label>
                </div>
                <div class="modal-actions">
                    <button type="button" onclick="closeModal('editUserModal')" class="btn btn-outline">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update User</button>
                </div>
            </form>
        </div>
    </div>
    
    <script src="assets/script.js"></script>
</body>
</html>
