<?php
// POST /api/auth/update_user.php
// Admin-only: update user details, role, status, and optionally reset password
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$currentUser = requireRole([1]); // Admin only
$db          = getDB();

$id       = (int)post('id', 0);
$fullName = trim(post('full_name', ''));
$username = trim(post('username', ''));
$email    = trim(post('email', ''));
$roleId   = (int)post('role_id', 2);
$isActive = (int)post('is_active', 1);
$password = post('password', '');

if (!$id)       apiError('User ID required.', 422);
if (!$fullName) apiError('Full name required.', 422);
if (!$username) apiError('Username required.', 422);
if (!$email)    apiError('Email required.', 422);

// Prevent admin from deactivating themselves
if ($id === (int)$currentUser['id'] && !$isActive) {
    apiError('You cannot deactivate your own account.', 422);
}

// Check uniqueness (exclude current user)
$check = $db->prepare("SELECT COUNT(*) FROM users WHERE (username = ? OR email = ?) AND id != ?");
$check->execute([$username, $email, $id]);
if ((int)$check->fetchColumn() > 0) apiError('Username or email already in use.', 409);

// Update core fields
$db->prepare("UPDATE users SET full_name=?, username=?, email=?, role_id=?, is_active=? WHERE id=?")
   ->execute([$fullName, $username, $email, $roleId, $isActive, $id]);

// Optional password reset
if ($password) {
    if (strlen($password) < 8) apiError('Password must be at least 8 characters.', 422);
    $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
    $db->prepare("UPDATE users SET password_hash=? WHERE id=?")->execute([$hash, $id]);
}

apiSuccess(['id' => $id], 'User updated.');