<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header('Location: login.php');
    exit();
}
include 'db.php'; // Include your database connection file

// Handle create new profile
if (isset($_POST['create_profile'])) {
    $username = trim($_POST['username']);
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone_number = trim($_POST['phone_number']);
    $password = $_POST['password'];
    $status = $_POST['status'];

    // Validate inputs
    if (empty($username) || empty($full_name) || empty($email) || empty($password) || !in_array($status, ['active', 'inactive'])) {
        $_SESSION['error_message'] = "Please fill all required fields and select a valid status.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $_SESSION['error_message'] = "Invalid email format.";
    } elseif (strlen($password) < 8) {
        $_SESSION['error_message'] = "Password must be at least 8 characters long.";
    } else {
        // Check for duplicate username or email
        $stmt = $conn->prepare("SELECT UserID FROM users WHERE Username = ? OR Email = ?");
        $stmt->bind_param("ss", $username, $email);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $_SESSION['error_message'] = "Username or email already exists.";
        } else {
            // Hash password and insert user
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("INSERT INTO users (Username, FullName, Email, PhoneNumber, Password, Status) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssss", $username, $full_name, $email, $phone_number, $hashed_password, $status);
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Profile created successfully!";
            } else {
                $_SESSION['error_message'] = "Error creating profile: " . $stmt->error;
            }
        }
        $stmt->close();
    }
    header("Location: profile_management.php");
    exit;
}

// Handle bulk delete
if (isset($_POST['bulk_delete']) && !empty($_POST['user_ids'])) {
    $user_ids = array_filter($_POST['user_ids'], 'is_numeric');
    if (!empty($user_ids)) {
        $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
        $stmt = $conn->prepare("DELETE FROM users WHERE UserID IN ($placeholders)");
        $stmt->bind_param(str_repeat('i', count($user_ids)), ...$user_ids);
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Selected profiles deleted successfully!";
        } else {
            $_SESSION['error_message'] = "Error deleting profiles: " . $stmt->error;
        }
        $stmt->close();
    } else {
        $_SESSION['error_message'] = "No valid user IDs selected.";
    }
    header("Location: profile_management.php");
    exit;
}

// Initialize search and pagination
$search_term = isset($_GET['search']) ? trim($_GET['search']) : '';
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = isset($_GET['limit']) && in_array($_GET['limit'], [10, 25, 50, 100]) ? (int)$_GET['limit'] : 10;
$offset = ($page - 1) * $limit;

// Build SQL query
$sql = "SELECT UserID, FullName, Email, PhoneNumber, Username FROM users";
$count_sql = "SELECT COUNT(*) as total FROM users";
$params = [];
$types = '';

if (!empty($search_term)) {
    $sql .= " WHERE Username LIKE ? OR FullName LIKE ? OR Email LIKE ?";
    $count_sql .= " WHERE Username LIKE ? OR FullName LIKE ? OR Email LIKE ?";
    $search_param = "%$search_term%";
    $params = [$search_param, $search_param, $search_param];
    $types = "sss";
}

// Get total count for pagination
$stmt = $conn->prepare($count_sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$total_users = $stmt->get_result()->fetch_assoc()['total'];
$stmt->close();
$total_pages = ceil($total_users / $limit);

// Fetch users for current page
$sql .= " LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;
$types .= "ii";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile Management</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f0f4f8;
        }
        .sidebar {
            background-color: #343a40;
            min-height: 100vh;
            padding-top: 20px;
        }
        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 10px;
            display: block;
            border-radius: 5px;
            margin: 5px;
            transition: background-color 0.3s;
        }
        .sidebar a:hover {
            background-color: #007bff;
        }
        .content {
            margin-left: 250px;
            padding: 30px;
        }
        h2, h4 {
            color: #343a40;
        }
        .pagination {
            justify-content: center;
        }
    </style>
</head>
<body>
    <div class="d-flex">
        <!-- Sidebar -->
        <div class="sidebar col-md-2">
            <h3 class="text-center text-white">Admin Panel</h3>
            
            <a href="index.php">Dashboard</a>
            <a href="games.php">Manage Games</a>
            <a href="game_categories.php">Manage Categories</a>
            <a href="leaderboard.php">Leaderboard</a>
            <a href="events.php">Manage Events</a>
            <a href="profile_management.php">Profile Management</a>
            <a href="logout.php">Logout</a>
        </div>

        <!-- Main Content -->
        <div class="content col-md-9">
            <div class="container py-5">
                <?php
                if (isset($_SESSION['success_message'])) {
                    echo "<div class='alert alert-success'>" . htmlspecialchars($_SESSION['success_message']) . "</div>";
                    unset($_SESSION['success_message']);
                }
                if (isset($_SESSION['error_message'])) {
                    echo "<div class='alert alert-danger'>" . htmlspecialchars($_SESSION['error_message']) . "</div>";
                    unset($_SESSION['error_message']);
                }
                ?>
                <h2>Profile Management</h2>
                <p>Here you can manage user profiles.</p>

                <!-- Create New Profile Form -->
                <h4>Create New Profile</h4>
                <form method="POST" class="mb-4">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="username" class="form-label">Username</label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="full_name" class="form-label">Full Name</label>
                            <input type="text" class="form-control" id="full_name" name="full_name" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="email" class="form-label">Email Address</label>
                            <input type="email" class="form-control" id="email" name="email" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="phone_number" class="form-label">Phone Number</label>
                            <input type="text" class="form-control" id="phone_number" name="phone_number">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="password" class="form-label">Password</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="status" class="form-label">Account Status</label>
                            <select class="form-select" id="status" name="status" required>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                    <button type="submit" name="create_profile" class="btn btn-primary">Create Profile</button>
                </form>

                <!-- Search Form -->
                <h4>Search Profiles</h4>
                <form method="GET" class="mb-4">
                    <div class="input-group">
                        <input type="text" class="form-control" name="search" placeholder="Search by username, full name, or email" value="<?php echo htmlspecialchars($search_term); ?>">
                        <button type="submit" class="btn btn-primary">Search</button>
                        <?php if (!empty($search_term)): ?>
                            <a href="profile_management.php" class="btn btn-secondary ms-2">Clear</a>
                        <?php endif; ?>
                    </div>
                </form>

                <!-- User Profiles Table -->
                <h4>User Profiles</h4>
                <form method="POST">
                    <div class="mb-3">
                        <button type="submit" name="bulk_delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete the selected profiles?');">Delete Selected</button>
                    </div>
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="select_all"></th>
                                <th>Username</th>
                                <th>Full Name</th>
                                <th>Email</th>
                                <th>Phone Number</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            if ($result->num_rows > 0) {
                                while ($user = $result->fetch_assoc()) {
                                    echo "<tr>";
                                    echo "<td><input type='checkbox' name='user_ids[]' value='{$user['UserID']}'></td>";
                                    echo "<td>" . htmlspecialchars($user['Username']) . "</td>";
                                    echo "<td>" . htmlspecialchars($user['FullName']) . "</td>";
                                    echo "<td>" . htmlspecialchars($user['Email']) . "</td>";
                                    echo "<td>" . htmlspecialchars($user['PhoneNumber']) . "</td>";
                                    echo "<td>
                                        <a href='edit_profile.php?id={$user['UserID']}' class='btn btn-warning btn-sm'>Edit</a>
                                        <a href='delete_profile.php?id={$user['UserID']}' class='btn btn-danger btn-sm' onclick='return confirm(\"Are you sure you want to delete this profile?\");'>Delete</a>
                                        </td>";
                                    echo "</tr>";
                                }
                            } else {
                                echo "<tr><td colspan='6' class='text-center'>" . (empty($search_term) ? "No users found" : "No users match your search") . "</td></tr>";
                            }
                            $stmt->close();
                            ?>
                        </tbody>
                    </table>
                </form>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <nav aria-label="Page navigation">
                        <ul class="pagination">
                            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $page - 1; ?>&limit=<?php echo $limit; ?>&search=<?php echo urlencode($search_term); ?>">Previous</a>
                            </li>
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&limit=<?php echo $limit; ?>&search=<?php echo urlencode($search_term); ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $page + 1; ?>&limit=<?php echo $limit; ?>&search=<?php echo urlencode($search_term); ?>">Next</a>
                            </li>
                        </ul>
                    </nav>
                    <form method="GET" class="mt-3">
                        <input type="hidden" name="search" value="<?php echo htmlspecialchars($search_term); ?>">
                        <label for="limit" class="form-label">Users per page:</label>
                        <select name="limit" id="limit" class="form-select d-inline w-auto" onchange="this.form.submit()">
                            <option value="10" <?php echo $limit === 10 ? 'selected' : ''; ?>>10</option>
                            <option value="25" <?php echo $limit === 25 ? 'selected' : ''; ?>>25</option>
                            <option value="50" <?php echo $limit === 50 ? 'selected' : ''; ?>>50</option>
                            <option value="100" <?php echo $limit === 100 ? 'selected' : ''; ?>>100</option>
                        </select>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- JavaScript for Select All Checkbox -->
    <script>
        document.getElementById('select_all').addEventListener('change', function() {
            document.querySelectorAll('input[name="user_ids[]"]').forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    </script>
</body>
</html>