<?php
session_start();
include __DIR__ . '/auth.php'; // Admin-only enforced here

// Only admins can access this page
if ($_SESSION['role'] !== 'admin') {
    die("<h1>Access Denied</h1><p>User Management is for administrators only.</p>");
}

include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';

/* ============================================================
   SECURE PATH — JSON IN AUTHENTICATION DIRECTORY
   ============================================================ */
$usersFile = "C:/inetpub/Authentication/OldiesAndMore/users.json";

$action = $_GET['action'] ?? null;
$message = "";
$error = "";

/* ============================================================
   LOAD USERS (FROM JSON)
   ============================================================ */
$users = [];
if (file_exists($usersFile)) {
    $json = file_get_contents($usersFile);
    $decoded = json_decode($json, true);
    if (is_array($decoded)) {
        $users = $decoded;
    }
}

/* ============================================================
   SAVE USER (ADD OR EDIT)
   ============================================================ */
if ($action === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {

    $username    = trim($_POST['username']);
    $password    = trim($_POST['password']);
    $role        = $_POST['role'] ?? 'view';
    $permissions = isset($_POST['permissions']) ? implode(',', $_POST['permissions']) : '';

    if ($username === '') {
        $error = "Username is required.";
    } else {

        // MasterDev protection
        if ($username === 'MasterDev') {
            $role = 'admin';
            $permissions = 'all';
        }

        // If editing and password left blank → keep existing password
        if (isset($users[$username]) && $password === '') {
            $finalPassword = $users[$username]['password'];

        } else {
            // New user or password changed
            if ($password === '') {
                $error = "Password is required for new users.";
            } else {
                // Store plain text — login.php will hash it on first login
                $finalPassword = $password;
            }
        }

        if ($error === '') {
            $users[$username] = [
                'password'    => $finalPassword,
                'role'        => $role,
                'permissions' => $permissions
            ];

            file_put_contents($usersFile, json_encode($users, JSON_PRETTY_PRINT));
            $message = "User saved successfully.";
        }
    }
}

/* ============================================================
   DELETE USER
   ============================================================ */
if ($action === 'delete') {
    $username = $_GET['user'] ?? '';

    if ($username === 'MasterDev') {
        $error = "MasterDev cannot be deleted.";
    } else {
        unset($users[$username]);
        file_put_contents($usersFile, json_encode($users, JSON_PRETTY_PRINT));
        $message = "User deleted.";
    }
}

/* ============================================================
   EDIT USER (LOAD DATA)
   ============================================================ */
$editUser = null;
if ($action === 'edit') {
    $username = $_GET['user'] ?? '';
    if (isset($users[$username])) {
        $editUser = [
            'username'    => $username,
            'role'        => $users[$username]['role'],
            'permissions' => explode(',', $users[$username]['permissions'] ?? '')
        ];
    }
}

/* ============================================================
   PERMISSION LIST
   ============================================================ */
$availablePages = [
    'comments'     => 'Comments',
    'poll'         => 'Poll',
    'schedule'     => 'Schedule',
    'djs'          => 'DJs',
    'friends'      => 'Friends',
    'requests'     => 'Requests',
    'applications' => 'Applications',
    'contact'      => 'Contact',
    'news'         => 'News',
    'about'        => 'About',
    'radiostats'   => 'Radio Stats',
    'hostingtools' => 'Hosting Tools'
];
?>

<div class="main-wrap">
    <div class="content-panel">

        <h1 class="section-title center-text">👥 User Management</h1>

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

        <?php if ($error): ?>
            <div class="msg error"><?= $error ?></div>
        <?php endif; ?>

        <!-- ADD / EDIT USER FORM -->
        <div class="content-box">
            <h3 class="section-title"><?= $editUser ? "✏️ Edit User" : "➕ Add User" ?></h3>

            <form method="POST" action="users.php?action=save">

                <label>Username:</label>
                <input type="text" name="username" class="input-field"
                       value="<?= $editUser['username'] ?? '' ?>"
                       <?= ($editUser && $editUser['username'] === 'MasterDev') ? 'readonly' : '' ?>
                       required>

                <label>Password:</label>
                <input type="text" name="password" class="input-field"
                       value=""
                       placeholder="<?= $editUser ? 'Leave blank to keep current password' : '' ?>">

                <label>Role:</label>
                <select name="role" class="input-field"
                    <?= ($editUser && $editUser['username'] === 'MasterDev') ? 'disabled' : '' ?>>
                    <option value="admin" <?= ($editUser && $editUser['role'] === 'admin') ? 'selected' : '' ?>>Admin</option>
                    <option value="view" <?= ($editUser && $editUser['role'] === 'view') ? 'selected' : '' ?>>View Only</option>
                </select>

                <label>Permissions (for View Only):</label>

                <?php foreach ($availablePages as $key => $label): ?>
                    <div>
                        <input type="checkbox" name="permissions[]"
                               value="<?= $key ?>"
                               <?= ($editUser && in_array($key, $editUser['permissions'])) ? 'checked' : '' ?>
                               <?= ($editUser && $editUser['username'] === 'MasterDev') ? 'disabled' : '' ?>>
                        <?= $label ?>
                    </div>
                <?php endforeach; ?>

                <button type="submit" class="button" style="margin-top:20px;">Save User</button>
            </form>
        </div>

        <!-- USER LIST -->
        <div class="content-box" style="margin-top:30px;">
            <h3 class="section-title">Existing Users</h3>

            <?php foreach ($users as $u => $info): ?>
                <p>
                    <strong><?= htmlspecialchars($u) ?></strong>
                    (<?= htmlspecialchars($info['role']) ?>)

                    <a href="users.php?action=edit&user=<?= urlencode($u) ?>" class="button small">Edit</a>

                    <?php if ($u !== 'MasterDev'): ?>
                        <a href="users.php?action=delete&user=<?= urlencode($u) ?>"
                           class="button small" style="background:#900;color:#fff;"
                           onclick="return confirm('Delete this user?')">Delete</a>
                    <?php endif; ?>
                </p>
            <?php endforeach; ?>
        </div>

    </div>
</div>

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