<?php
require 'db.php';
require 'functions.php';
requireRole(['admin']);

$action = cleanInput($_POST['action'] ?? $_GET['action'] ?? '');

try {
    if ($action === 'list') {
        $rows = $pdo->query("SELECT id, name, username, phone, isactive FROM rnduser WHERE isdeleted = 0 ORDER BY name")->fetchAll();
        jsonOut(true, '', $rows);
    }

    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $name = cleanInput($_POST['name'] ?? '');
        $username = cleanInput($_POST['username'] ?? '');
        $phone = cleanInput($_POST['phone'] ?? '');
        $password = cleanInput($_POST['password'] ?? '');

        if ($name === '' || $username === '' || $phone === '') {
            jsonOut(false, 'All fields are required');
        }

        if ($id > 0) {
            if ($password !== '') {
                $stmt = $pdo->prepare("UPDATE rnduser SET name=?, username=?, phone=?, password=? WHERE id=?");
                $stmt->execute([$name, $username, $phone, hashPassword($password), $id]);
            } else {
                $stmt = $pdo->prepare("UPDATE rnduser SET name=?, username=?, phone=? WHERE id=?");
                $stmt->execute([$name, $username, $phone, $id]);
            }
            logActivity($pdo, 'rnduser', $id, 'update', 'admin', currentUserId(), 'RND user updated');
            jsonOut(true, 'RND user updated successfully');
        } else {
            if ($password === '') {
                jsonOut(false, 'Password is required for a new user');
            }
            $stmt = $pdo->prepare("INSERT INTO rnduser (name, username, phone, password) VALUES (?,?,?,?)");
            $stmt->execute([$name, $username, $phone, hashPassword($password)]);
            $newid = $pdo->lastInsertId();
            logActivity($pdo, 'rnduser', $newid, 'create', 'admin', currentUserId(), 'RND user created');
            jsonOut(true, 'RND user added successfully');
        }
    }

    if ($action === 'togglestatus') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $pdo->prepare("UPDATE rnduser SET isactive = 1 - isactive WHERE id = ?");
        $stmt->execute([$id]);
        logActivity($pdo, 'rnduser', $id, 'togglestatus', 'admin', currentUserId(), 'RND user status toggled');
        jsonOut(true, 'Status updated successfully');
    }

    jsonOut(false, 'Invalid action');
} catch (PDOException $e) {
    logDebug('[ajax_admin_rnduser] ' . $e->getMessage());
    if ($e->getCode() == 23000) {
        jsonOut(false, 'Username already exists');
    }
    jsonOut(false, 'Something went wrong. Please try again.');
}
