<?php
require_once __DIR__ . '/../config/database.php';

$allowedIps = ['127.0.0.1', '::1'];

if (!in_array($_SERVER['REMOTE_ADDR'] ?? '', $allowedIps, true)) {
    http_response_code(403);
    exit('Forbidden');
}

$db = Database::getInstance();

$users = $db->getAll("SELECT id, username, email, status FROM users ORDER BY id ASC");

$message = null;
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $newPassword = (string)($_POST['new_password'] ?? '');
    $role = trim($_POST['role'] ?? '');
    $confirm = isset($_POST['confirm']);

    $allowedRoles = ['super_admin', 'admin', 'regional_admin', 'instructor', 'student'];

    try {
        if (!$confirm) {
            throw new Exception('Please confirm before updating');
        }
        if ($username === '') {
            throw new Exception('Username is required');
        }
        if ($newPassword === '') {
            throw new Exception('New password is required');
        }
        if ($role !== '' && !in_array($role, $allowedRoles, true)) {
            throw new Exception('Invalid role');
        }

        $user = $db->get("SELECT id FROM users WHERE username = ?", [$username]);
        if (!$user) {
            throw new Exception('User not found');
        }

        $hashed = hashPassword($newPassword);

        $db->update(
            'users',
            ['password' => $hashed, 'status' => 'active', 'email_verified' => 1, 'updated_at' => formatDate()],
            'id = ?',
            [$user['id']]
        );

        if ($role !== '') {
            $existingRole = $db->get("SELECT id FROM user_roles WHERE user_id = ?", [$user['id']]);
            if ($existingRole) {
                $db->update(
                    'user_roles',
                    ['role' => $role, 'is_active' => 1, 'assigned_at' => formatDate()],
                    'user_id = ?',
                    [$user['id']]
                );
            } else {
                $db->insert('user_roles', [
                    'user_id' => $user['id'],
                    'role' => $role,
                    'permissions' => null,
                    'assigned_at' => formatDate(),
                    'assigned_by' => null,
                    'expires_at' => null,
                    'is_active' => 1
                ]);
            }
        }

        $message = 'Updated successfully for ' . htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
        $users = $db->getAll("SELECT id, username, email, status FROM users ORDER BY id ASC");
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dev Reset Users</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-4">
    <div class="alert alert-warning">
        <div class="fw-bold">One-time dev tool</div>
        Delete this file after use: <code>lms/dev_reset_users.php</code>
    </div>

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

    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?></div>
    <?php endif; ?>

    <div class="card mb-4">
        <div class="card-header fw-semibold">Update Password / Role</div>
        <div class="card-body">
            <form method="post" autocomplete="off">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">Username</label>
                        <input class="form-control" name="username" placeholder="admin" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">New Password</label>
                        <input class="form-control" name="new_password" type="text" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Role (optional)</label>
                        <select class="form-select" name="role">
                            <option value="">(no change)</option>
                            <option value="admin">admin</option>
                            <option value="super_admin">super_admin</option>
                            <option value="regional_admin">regional_admin</option>
                            <option value="instructor">instructor</option>
                            <option value="student">student</option>
                        </select>
                    </div>
                </div>
                <div class="form-check mt-3">
                    <input class="form-check-input" type="checkbox" name="confirm" id="confirm" required>
                    <label class="form-check-label" for="confirm">I understand this will change the selected user account</label>
                </div>
                <div class="mt-3">
                    <button class="btn btn-primary" type="submit">Update</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-header fw-semibold">Existing Users</div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped mb-0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Username</th>
                            <th>Email</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $u): ?>
                            <tr>
                                <td><?php echo (int)$u['id']; ?></td>
                                <td><?php echo htmlspecialchars($u['username'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td><?php echo htmlspecialchars($u['email'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td><?php echo htmlspecialchars($u['status'], ENT_QUOTES, 'UTF-8'); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>
