<?php
require_once 'includes/header.php';

$pdo = db();

if (isset($_POST['delete_user'])) {
    $id = $_POST['user_id'];
    if ($id != $_SESSION['user_id']) {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$id]);
        echo "<div style='padding: 1rem; background: #f44336; color: white;'>User Deleted</div>";
    }
}

// Handle Add User
if (isset($_POST['add_user'])) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = $_POST['role'];
    
    // Check if exists
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
    $stmt->execute([$username, $email]);
    if ($stmt->fetch()) {
        echo "<div style='padding: 1rem; background: #f44336; color: white;'>User already exists</div>";
    } else {
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, ?)");
        $stmt->execute([$username, $email, $password, $role]);
        echo "<div style='padding: 1rem; background: #4caf50; color: white;'>User Added Successfully</div>";
    }
}

if (isset($_POST['update_role'])) {
    $id = $_POST['user_id'];
    $role = $_POST['role'];
    if ($id != $_SESSION['user_id']) { // Prevent changing own role to something lower accidentally
        $stmt = $pdo->prepare("UPDATE users SET role = ? WHERE id = ?");
        $stmt->execute([$role, $id]);
        echo "<div style='padding: 1rem; background: #4caf50; color: white;'>User Role Updated</div>";
    }
}

$stmt = $pdo->query("SELECT * FROM users ORDER BY created_at DESC");
$users = $stmt->fetchAll();
?>

<div class="page-header">
    <h1>User Management</h1>
    <button onclick="document.getElementById('addUserModal').style.display='block'" class="btn-sm btn-primary">Add New User</button>
</div>

<div style="overflow-x: auto;">
    <table class="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Role</th>
                <th>Joined</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $user): ?>
            <tr>
                <td>#<?php echo $user['id']; ?></td>
                <td>
                    <?php echo htmlspecialchars($user['username']); ?><br>
                    <small style="color:var(--text-secondary);"><?php echo htmlspecialchars($user['email'] ?? ''); ?></small>
                </td>
                <td>
                    <?php if ($user['id'] == $_SESSION['user_id']): ?>
                        <span class="badge badge-admin"><?php echo htmlspecialchars($user['role']); ?></span>
                    <?php else: ?>
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                            <select name="role" onchange="this.form.submit()" style="padding:0.2rem; border-radius:4px; background:var(--bg-color); color:var(--text-primary); border:1px solid var(--border-color);">
                                <?php
                                $roles = ['Guest','Customer','Dealer','Employee','Manager','Admin','Super Admin'];
                                foreach ($roles as $r) {
                                    $selected = ($user['role'] === $r) ? 'selected' : '';
                                    echo "<option value='$r' $selected>$r</option>";
                                }
                                ?>
                            </select>
                            <input type="hidden" name="update_role" value="1">
                        </form>
                    <?php endif; ?>
                </td>
                <td><?php echo date('M j, Y', strtotime($user['created_at'])); ?></td>
                <td>
                    <?php if ($user['id'] != $_SESSION['user_id']): ?>
                    <form method="POST" onsubmit="return confirm('Are you sure?');" style="display: inline;">
                        <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                        <button type="submit" name="delete_user" class="btn-sm btn-danger">Delete</button>
                    </form>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

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

<!-- Add User Modal -->
<div id="addUserModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); z-index:1000;">
    <div style="background:var(--card-bg); width:400px; margin: 100px auto; padding:2rem; border-radius:8px; border:1px solid var(--border-color);">
        <h2 style="margin-bottom:1rem; color:var(--text-primary);">Add User</h2>
        <form method="POST">
            <div style="margin-bottom:1rem;">
                <label style="display:block; color:var(--text-secondary); margin-bottom:0.5rem;">Username</label>
                <input type="text" name="username" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:var(--text-primary);">
            </div>
            <div style="margin-bottom:1rem;">
                <label style="display:block; color:var(--text-secondary); margin-bottom:0.5rem;">Email</label>
                <input type="email" name="email" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:var(--text-primary);">
            </div>
            <div style="margin-bottom:1rem;">
                <label style="display:block; color:var(--text-secondary); margin-bottom:0.5rem;">Password</label>
                <input type="password" name="password" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:var(--text-primary);">
            </div>
            <div style="margin-bottom:1rem;">
                <label style="display:block; color:var(--text-secondary); margin-bottom:0.5rem;">Role</label>
                <select name="role" style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:var(--text-primary);">
                    <option value="Customer">Customer</option>
                    <option value="Dealer">Dealer</option>
                    <option value="Manager">Manager</option>
                    <option value="Admin">Admin</option>
                </select>
            </div>
            <button type="submit" name="add_user" class="btn-sm btn-primary" style="width:100%;">Create User</button>
            <button type="button" onclick="document.getElementById('addUserModal').style.display='none'" class="btn-sm" style="width:100%; margin-top:0.5rem; background:transparent; border:1px solid var(--border-color);">Cancel</button>
        </form>
    </div>
</div>

<script>
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('action') === 'add') {
        document.getElementById('addUserModal').style.display = 'block';
    }
</script>
