<?php
/**
 * Admin - List Users (search, pagination, export CSV)
 * PHP User Registration - https://rskworld.in
 * Developer: Molla Samser | RSK World
 * Contact: help@rskworld.in | +91 93305 39277
 * Year: 2026
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../config/roles.php';

requireAdmin();
$baseHref = '..';

$pdo = getDbConnection();
$currentUserRole = getCurrentUserRole();

$search = trim($_GET['q'] ?? '');
$filterVerified = isset($_GET['verified']) ? (string) $_GET['verified'] : ''; // '', '1', '0'
$orderBy = isset($_GET['order']) ? (string) $_GET['order'] : 'id';
$orderDir = strtolower((string) ($_GET['dir'] ?? 'desc'));
if (!in_array($orderDir, ['asc', 'desc'], true)) $orderDir = 'desc';
$allowedOrder = ['id', 'name', 'email', 'created_at', 'last_login_at'];
if (!in_array($orderBy, $allowedOrder, true)) $orderBy = 'id';
$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 15;
$currentUserId = (int) ($_SESSION['user_id'] ?? 0);

// Set role (user, moderator, admin, superadmin)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['set_role_id'], $_POST['set_role_value'])) {
    $uid = (int) $_POST['set_role_id'];
    $newRole = trim((string) $_POST['set_role_value']);
    $allowedRoles = getAllRoles();
    if ($uid > 0 && $uid !== $currentUserId && in_array($newRole, $allowedRoles, true) && canAssignRole($currentUserRole, $newRole)) {
        try {
            $pdo->prepare('UPDATE users SET role = ? WHERE id = ?')->execute([$newRole, $uid]);
            try { $pdo->prepare('UPDATE users SET is_admin = ? WHERE id = ?')->execute([in_array($newRole, ['admin', 'superadmin'], true) ? 1 : 0, $uid]); } catch (PDOException $e0) {}
            logAdminActivity($currentUserId, 'set_role', $uid, 'role=' . $newRole);
            setFlash('success', 'Role set to ' . getRoleLabel($newRole) . '.');
        } catch (PDOException $e) {
            if ($e->getCode() === '42S22' || strpos($e->getMessage(), 'role') !== false) {
                try {
                    $pdo->exec('ALTER TABLE users ADD COLUMN role VARCHAR(30) DEFAULT \'user\'');
                    try { $pdo->exec('UPDATE users SET role = \'admin\' WHERE is_admin = 1'); } catch (PDOException $e1) {}
                    $pdo->prepare('UPDATE users SET role = ? WHERE id = ?')->execute([$newRole, $uid]);
                    try { $pdo->prepare('UPDATE users SET is_admin = ? WHERE id = ?')->execute([in_array($newRole, ['admin', 'superadmin'], true) ? 1 : 0, $uid]); } catch (PDOException $e1) {}
                    logAdminActivity($currentUserId, 'set_role', $uid, 'role=' . $newRole);
                    setFlash('success', 'Role set to ' . getRoleLabel($newRole) . '.');
                } catch (PDOException $e2) {
                    setFlash('error', 'Set role failed. Run sql/migrate-add-roles.sql');
                }
            } else {
                try {
                    $pdo->prepare('UPDATE users SET is_admin = ? WHERE id = ?')->execute([in_array($newRole, ['admin', 'superadmin'], true) ? 1 : 0, $uid]);
                    setFlash('success', 'Admin flag updated.');
                } catch (PDOException $e2) {}
            }
        }
        $qs = 'page=' . $page . ($search !== '' ? '&q=' . urlencode($search) : '') . ($filterVerified !== '' ? '&verified=' . $filterVerified : '') . ($orderBy !== 'id' ? '&order=' . urlencode($orderBy) . '&dir=' . $orderDir : '');
        header('Location: users.php?' . $qs);
        exit;
    }
}
// Suspend / Unsuspend
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['suspend_id'], $_POST['suspend_value'])) {
    $uid = (int) $_POST['suspend_id'];
    $val = (int) $_POST['suspend_value'];
    if ($uid > 0 && $uid !== $currentUserId && $val >= 0 && $val <= 1) {
        try {
            $pdo->prepare('UPDATE users SET suspended = ? WHERE id = ?')->execute([$val, $uid]);
            logAdminActivity($currentUserId, $val ? 'suspend' : 'unsuspend', $uid);
            setFlash('success', $val ? 'User suspended.' : 'User unsuspended.');
        } catch (PDOException $e) {
            if ($e->getCode() === '42S22' || strpos($e->getMessage(), 'suspended') !== false) {
                try {
                    $pdo->exec('ALTER TABLE users ADD COLUMN suspended TINYINT(1) DEFAULT 0');
                    $pdo->prepare('UPDATE users SET suspended = ? WHERE id = ?')->execute([$val, $uid]);
                    logAdminActivity($currentUserId, $val ? 'suspend' : 'unsuspend', $uid);
                    setFlash('success', $val ? 'User suspended.' : 'User unsuspended.');
                } catch (PDOException $e2) {
                    setFlash('error', 'Suspend failed. Run sql/migrate-add-even-more-features.sql to add suspended column.');
                }
            } else {
                setFlash('error', 'Suspend failed. ' . $e->getMessage());
            }
        }
        $qs = 'page=' . $page . ($search !== '' ? '&q=' . urlencode($search) : '') . ($filterVerified !== '' ? '&verified=' . $filterVerified : '') . ($orderBy !== 'id' ? '&order=' . urlencode($orderBy) . '&dir=' . $orderDir : '');
        header('Location: users.php?' . $qs);
        exit;
    }
}

// Export CSV
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="users-' . date('Y-m-d') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID', 'Name', 'Email', 'Verified', 'Role', 'Suspended', 'Joined', 'Last Login', 'Last IP']);
    $sql = 'SELECT * FROM users WHERE 1=1';
    $params = [];
    if ($search !== '') {
        $sql .= ' AND (name LIKE ? OR email LIKE ?)';
        $params[] = '%' . $search . '%';
        $params[] = '%' . $search . '%';
    }
    if ($filterVerified === '1') $sql .= ' AND email_verified = 1';
    if ($filterVerified === '0') $sql .= ' AND (email_verified = 0 OR email_verified IS NULL)';
    $sql .= ' ORDER BY id DESC';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($out, [
            $row['id'] ?? '',
            $row['name'] ?? '',
            $row['email'] ?? '',
            !empty($row['email_verified']) ? 'Yes' : 'No',
            isset($row['role']) ? ($row['role'] ?: 'user') : (!empty($row['is_admin']) ? 'admin' : 'user'),
            !empty($row['suspended']) ? 'Yes' : 'No',
            !empty($row['created_at']) ? $row['created_at'] : '',
            $row['last_login_at'] ?? '',
            $row['last_login_ip'] ?? ''
        ]);
    }
    fclose($out);
    exit;
}

// Build list query (SELECT * works with or without optional columns)
$where = '1=1';
$params = [];
if ($search !== '') {
    $where .= ' AND (name LIKE ? OR email LIKE ?)';
    $params[] = '%' . $search . '%';
    $params[] = '%' . $search . '%';
}
if ($filterVerified === '1') $where .= ' AND email_verified = 1';
if ($filterVerified === '0') $where .= ' AND (email_verified = 0 OR email_verified IS NULL)';
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE $where");
$countStmt->execute($params);
$total = (int) $countStmt->fetchColumn();
$totalPages = max(1, (int) ceil($total / $perPage));
$page = min($page, $totalPages);
$offset = ($page - 1) * $perPage;

$orderCol = $orderBy === 'id' ? 'id' : $orderBy;
$stmt = $pdo->prepare("SELECT * FROM users WHERE $where ORDER BY $orderCol $orderDir LIMIT $perPage OFFSET $offset");
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Mark verified (admin action)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_user_id'])) {
        $uid = (int) $_POST['verify_user_id'];
        if ($uid > 0) {
            try {
                $pdo->prepare('UPDATE users SET email_verified = 1, verification_token = NULL, token_expires_at = NULL WHERE id = ?')->execute([$uid]);
                logAdminActivity($currentUserId, 'verify_user', $uid);
            } catch (PDOException $e) { /* columns may not exist */ }
            setFlash('success', 'User marked as verified.');
        $redirect = 'users.php?page=' . $page . ($search !== '' ? '&q=' . urlencode($search) : '') . ($filterVerified !== '' ? '&verified=' . $filterVerified : '') . ($orderBy !== 'id' ? '&order=' . urlencode($orderBy) . '&dir=' . $orderDir : '');
        header('Location: ' . $redirect);
        exit;
    }
}

$success = getFlash('success');
$error = getFlash('error');

$pageTitle = 'Admin - Users';
require_once __DIR__ . '/../includes/header.php';
?>

<div class="page-content admin-content">
    <h1><i class="fas fa-users"></i> Users</h1>
    <p class="subtitle">PHP User Registration — <a href="https://rskworld.in" target="_blank">rskworld.in</a></p>

    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="admin-toolbar">
        <form method="get" action="users.php" class="search-form">
            <input type="hidden" name="order" value="<?= htmlspecialchars($orderBy) ?>">
            <input type="hidden" name="dir" value="<?= htmlspecialchars($orderDir) ?>">
            <input type="search" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="Search by name or email">
            <select name="verified" onchange="this.form.submit()">
                <option value=""<?= $filterVerified === '' ? ' selected' : '' ?>>All users</option>
                <option value="1"<?= $filterVerified === '1' ? ' selected' : '' ?>>Verified only</option>
                <option value="0"<?= $filterVerified === '0' ? ' selected' : '' ?>>Unverified only</option>
            </select>
            <button type="submit" class="btn btn-secondary btn-sm">Search</button>
        </form>
        <a href="users.php?export=csv<?= $search !== '' ? '&q=' . urlencode($search) : '' ?><?= $filterVerified !== '' ? '&verified=' . $filterVerified : '' ?>" class="btn btn-secondary btn-sm"><i class="fas fa-download"></i> Export CSV</a>
    </div>

    <div class="table-wrap">
        <?php
        $pagBase = 'users.php?page=' . $page . ($search !== '' ? '&q=' . urlencode($search) : '') . ($filterVerified !== '' ? '&verified=' . $filterVerified : '');
        $sortUrl = function ($col) use ($orderBy, $orderDir, $pagBase) {
            $dir = ($orderBy === $col && $orderDir === 'asc') ? 'desc' : 'asc';
            return $pagBase . '&order=' . urlencode($col) . '&dir=' . $dir;
        };
        ?>
        <table class="admin-table">
            <thead>
                <tr>
                    <th><a href="<?= $sortUrl('id') ?>">ID</a><?= $orderBy === 'id' ? ' ' . ($orderDir === 'asc' ? '↑' : '↓') : '' ?></th>
                    <th><a href="<?= $sortUrl('name') ?>">Name</a><?= $orderBy === 'name' ? ' ' . ($orderDir === 'asc' ? '↑' : '↓') : '' ?></th>
                    <th><a href="<?= $sortUrl('email') ?>">Email</a><?= $orderBy === 'email' ? ' ' . ($orderDir === 'asc' ? '↑' : '↓') : '' ?></th>
                    <th>Avatar</th>
                    <th>Verified</th>
                    <th>Role</th>
                    <th>Suspended</th>
                    <th><a href="<?= $sortUrl('created_at') ?>">Joined</a><?= $orderBy === 'created_at' ? ' ' . ($orderDir === 'asc' ? '↑' : '↓') : '' ?></th>
                    <th><a href="<?= $sortUrl('last_login_at') ?>">Last Login</a><?= $orderBy === 'last_login_at' ? ' ' . ($orderDir === 'asc' ? '↑' : '↓') : '' ?></th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($users as $u):
                    $uid = (int) ($u['id'] ?? 0);
                    $isSelf = ($uid === $currentUserId);
                    $userRole = !empty($u['role']) ? $u['role'] : (!empty($u['is_admin']) ? 'admin' : 'user');
                ?>
                <tr>
                    <td><?= $uid ?></td>
                    <td><?= htmlspecialchars($u['name'] ?? '') ?></td>
                    <td><?= htmlspecialchars($u['email'] ?? '') ?></td>
                    <td><?php
                        $avatar = $u['avatar_path'] ?? null;
                        if ($avatar && is_string($avatar) && $avatar !== ''):
                            $src = (strpos($avatar, '/') === 0 || strpos($avatar, 'http') === 0) ? $avatar : ($baseHref . '/' . ltrim($avatar, '/'));
                        ?><img src="<?= htmlspecialchars($src) ?>" alt="" class="avatar-thumb" width="32" height="32"><?php else: ?>—<?php endif; ?></td>
                    <td><?= !empty($u['email_verified']) ? '<span class="badge badge-success">Yes</span>' : '<span class="badge badge-warning">No</span>' ?></td>
                    <td>
                        <?php
                        $roleClass = $userRole === 'superadmin' ? 'badge-danger' : ($userRole === 'admin' ? 'badge-primary' : ($userRole === 'moderator' ? 'badge-info' : ''));
                        ?>
                        <span class="badge <?= $roleClass ?>"><?= htmlspecialchars(getRoleLabel($userRole)) ?></span>
                        <?php if (!$isSelf): ?>
                        <form method="post" class="role-form">
                            <input type="hidden" name="set_role_id" value="<?= $uid ?>">
                            <select name="set_role_value" onchange="if(confirm('Set role to ' + this.options[this.selectedIndex].text + '?')) this.form.submit()">
                                <?php foreach (getAllRoles() as $r): if (!canAssignRole($currentUserRole, $r)) continue; ?>
                                <option value="<?= htmlspecialchars($r) ?>"<?= $userRole === $r ? ' selected' : '' ?>><?= htmlspecialchars(getRoleLabel($r)) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </form>
                        <?php endif; ?>
                    </td>
                    <td><?= !empty($u['suspended']) ? '<span class="badge badge-danger">Yes</span>' : '—' ?></td>
                    <td><?= !empty($u['created_at']) ? date('M j, Y', strtotime($u['created_at'])) : '—' ?></td>
                    <td><?= !empty($u['last_login_at']) ? date('M j, g:i A', strtotime($u['last_login_at'])) : '—' ?></td>
                    <td class="actions-cell">
                        <?php if (empty($u['email_verified'])): ?>
                        <form method="post" style="display:inline;"><input type="hidden" name="verify_user_id" value="<?= $uid ?>"><button type="submit" class="btn-link">Verify</button></form>
                        <?php endif; ?>
                        <?php if (!$isSelf): ?>
                        <?php if (!empty($u['suspended'])): ?>
                        <form method="post" style="display:inline;"><input type="hidden" name="suspend_id" value="<?= $uid ?>"><input type="hidden" name="suspend_value" value="0"><button type="submit" class="btn-link">Unsuspend</button></form>
                        <?php else: ?>
                        <form method="post" style="display:inline;" onsubmit="return confirm('Suspend this user?');"><input type="hidden" name="suspend_id" value="<?= $uid ?>"><input type="hidden" name="suspend_value" value="1"><button type="submit" class="btn-link text-danger">Suspend</button></form>
                        <?php endif; ?>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="pagination">
        <?php $pagBase = 'users.php?page='; $pagQs = ($search !== '' ? '&q=' . urlencode($search) : '') . ($filterVerified !== '' ? '&verified=' . $filterVerified : '') . ($orderBy !== 'id' ? '&order=' . urlencode($orderBy) . '&dir=' . $orderDir : ''); ?>
        <?php if ($page > 1): ?>
            <a href="<?= $pagBase . ($page - 1) . $pagQs ?>">« Previous</a>
        <?php endif; ?>
        <span class="pagination-info">Page <?= $page ?> of <?= $totalPages ?> (<?= $total ?> users)</span>
        <?php if ($page < $totalPages): ?>
            <a href="<?= $pagBase . ($page + 1) . $pagQs ?>">Next »</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <p><a href="index.php" class="btn btn-secondary">Back to Admin</a></p>
</div>

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