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

    if ($action === 'togglestatus') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id === currentUserId()) {
            jsonOut(false, 'You cannot deactivate your own account');
        }
        $stmt = $pdo->prepare("UPDATE adminuser SET isactive = 1 - isactive WHERE id = ?");
        $stmt->execute([$id]);
        logActivity($pdo, 'adminuser', $id, 'togglestatus', 'admin', currentUserId(), 'Admin user status toggled');
        jsonOut(true, 'Status updated successfully');
    }

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