<?php
$pageTitle = 'Manage Users';
include_once 'includes/header.php';

$userModel = new User();
$error = '';

// --- Handle POST Actions ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id_to_update = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);

    // Security checks
    if (!in_array($current_user_role, ['super_admin', 'admin'])) {
        $error = "You don't have permission to perform this action.";
    } elseif (!$user_id_to_update || $user_id_to_update == $_SESSION['admin_user_id']) {
        $error = "Invalid action. You cannot modify your own account.";
    } else {
        $target_user = $userModel->findById($user_id_to_update);
        if ($target_user && $target_user->role === 'super_admin' && $current_user_role !== 'super_admin') {
            $error = "You cannot modify a Super Admin account.";
        } else {
            // Process action
            if (isset($_POST['update_role'])) {
                $new_role = $_POST['role'] ?? '';
                if ($userModel->updateRole($user_id_to_update, $new_role)) {
                    $_SESSION['flash_message'] = "User role updated successfully!";
                } else { $error = "Failed to update user role."; }
            } elseif (isset($_POST['ban_user'])) {
                $reason = trim($_POST['ban_reason'] ?? 'No reason provided.');
                if ($userModel->banUser($user_id_to_update, $reason)) {
                    $_SESSION['flash_message'] = "User has been banned.";
                } else { $error = "Failed to ban user."; }
            } elseif (isset($_POST['unban_user'])) {
                if ($userModel->unbanUser($user_id_to_update)) {
                    $_SESSION['flash_message'] = "User has been unbanned.";
                } else { $error = "Failed to unban user."; }
            } elseif (isset($_POST['delete_user'])) {
                if ($userModel->deleteUser($user_id_to_update)) {
                    $_SESSION['flash_message'] = "User permanently deleted.";
                } else { $error = "Failed to delete user."; }
            }
            if (empty($error)) {
                header('Location: manage_users.php');
                exit();
            }
        }
    }
}

// --- Fetch Data ---
$search_query = $_GET['q'] ?? '';
if (!empty($search_query)) {
    $users = $userModel->searchUsers($search_query);
} else {
    $users = $userModel->getAll();
}
$roles = ['fan', 'player', 'team_manager', 'club_manager', 'league_manager', 'referee', 'commissioner', 'fantasy_manager', 'super_fantasy_manager', 'finance_manager', 'fixtures_manager', 'admin', 'super_admin'];

if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}

include_once 'includes/sidebar.php';
?>

<h1>Manage Users & Roles</h1>

<?php if (!empty($message)): ?><div class="message success"><?php echo $message; ?></div><?php endif; ?>
<?php if (!empty($error)): ?><div class="message error"><?php echo $error; ?></div><?php endif; ?>

<div class="dashboard-section">
    <form action="manage_users.php" method="GET" class="search-form">
        <div class="search-group">
            <input type="text" name="q" placeholder="Search by name, username, or email..." value="<?php echo htmlspecialchars($search_query); ?>">
            <button type="submit" class="btn"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
        </div>
        <?php if(!empty($search_query)): ?>
            <a href="manage_users.php" class="btn btn-secondary">Clear</a>
        <?php endif; ?>
    </form>
</div>

<div class="table-wrapper">
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Email</th>
                <th>Status</th>
                <th>Role</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $user): ?>
            <?php 
            // Super admins can see everyone. Admins cannot see super admins.
            if ($user->role === 'super_admin' && $current_user_role !== 'super_admin') {
                continue;
            }
            ?>
            <tr>
                <td><?php echo htmlspecialchars($user->id); ?></td>
                <td><?php echo htmlspecialchars($user->username); ?></td>
                <td><?php echo htmlspecialchars($user->email); ?></td>
                <td>
                    <span class="status-badge status-<?php echo strtolower($user->status ?? 'active'); ?>">
                        <?php echo ucfirst($user->status ?? 'active'); ?>
                    </span>
                </td>
                <td>
                    <form action="manage_users.php" method="POST" class="role-form">
                        <input type="hidden" name="user_id" value="<?php echo $user->id; ?>">
                        <?php 
                        $can_edit_role = ($current_user_role === 'super_admin' && $user->id != $_SESSION['admin_user_id']) || 
                                         ($current_user_role === 'admin' && $user->role !== 'super_admin' && $user->id != $_SESSION['admin_user_id']);
                        
                        if ($can_edit_role): ?>
                            <select name="role" onchange="this.form.submit()">
                                <?php foreach ($roles as $role): ?>
                                    <?php 
                                    // Admin cannot assign super_admin role
                                    if ($current_user_role === 'admin' && $role === 'super_admin') continue;
                                    ?>
                                    <option value="<?php echo $role; ?>" <?php echo $user->role === $role ? 'selected' : ''; ?>><?php echo $role; ?></option>
                                <?php endforeach; ?>
                            </select>
                            <input type="hidden" name="update_role" value="1">
                        <?php else: ?>
                            <?php echo htmlspecialchars($user->role); ?>
                        <?php endif; ?>
                    </form>
                </td>
                <td class="actions-cell">
                    <?php if ($can_edit_role): ?>
                        <?php if (($user->status ?? 'active') === 'active'): ?>
                            <button class="btn-sm btn-warning" onclick="openBanModal(<?php echo $user->id; ?>, '<?php echo htmlspecialchars($user->username, ENT_QUOTES); ?>')">Ban</button>
                        <?php else: ?>
                            <form action="manage_users.php" method="POST" style="display:inline;">
                                <input type="hidden" name="user_id" value="<?php echo $user->id; ?>">
                                <button type="submit" name="unban_user" value="1" class="btn-sm btn-success">Unban</button>
                            </form>
                        <?php endif; ?>
                        <form action="manage_users.php" method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to permanently delete this user? This cannot be undone.');">
                            <input type="hidden" name="user_id" value="<?php echo $user->id; ?>">
                            <button type="submit" name="delete_user" value="1" class="btn-sm btn-danger">Delete</button>
                        </form>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Ban Modal -->
<div id="banModal" class="modal">
    <div class="modal-content" style="max-width: 450px;">
        <div class="modal-header">
            <h3>Ban User: <span id="ban_username"></span></h3>
            <button class="modal-close-btn" onclick="closeBanModal()">&times;</button>
        </div>
        <form action="manage_users.php" method="POST">
            <input type="hidden" name="ban_user" value="1">
            <input type="hidden" name="user_id" id="ban_user_id">
            <div class="form-group">
                <label for="ban_reason">Reason for Ban (Optional)</label>
                <textarea name="ban_reason" id="ban_reason" rows="3" class="form-control" style="width: 100%; padding: 8px;"></textarea>
            </div>
            <div style="text-align: right; margin-top: 15px;">
                <button type="button" class="btn btn-secondary" onclick="closeBanModal()">Cancel</button>
                <button type="submit" class="btn btn-danger">Confirm Ban</button>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const banModal = document.getElementById('banModal');
    
    window.openBanModal = function(userId, username) {
        document.getElementById('ban_user_id').value = userId;
        document.getElementById('ban_username').textContent = username;
        banModal.classList.add('show');
    }
    
    window.closeBanModal = function() { 
        banModal.classList.remove('show'); 
    }
    
    window.addEventListener('click', function(event) {
        if (event.target == banModal) closeBanModal();
    });
});
</script>

<style>
.search-form { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.search-group { display: flex; flex: 1; gap: 0; }
.search-group input { border-top-right-radius: 0; border-bottom-right-radius: 0; border-right: none; }
.search-group .btn { border-top-left-radius: 0; border-bottom-left-radius: 0; }

/* Ensure modal works if global styles fail */
.modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.5); align-items: center; justify-content: center; }
.modal.show { display: flex; }
</style>

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