<?php
/**
 * Update User Endpoint
 * POST /v1/users/update
 */

use App\Core\Database;
use App\Core\AuditLogger;
use App\Middleware\RoleMiddleware;

$decoded = RoleMiddleware::require(['super_admin', 'admin']);

$data = input();
$id = $data['id'] ?? null;
if (!$id) json_error('معرّف المستخدم مطلوب', 422);

$db = Database::getInstance();
$tenantId = $decoded['tenant_id'];
$role = $decoded['role'];

// Verify access
$query = $role === 'super_admin'
    ? "SELECT * FROM users WHERE id = ?"
    : "SELECT * FROM users WHERE id = ? AND tenant_id = ?";
$params = $role === 'super_admin' ? [$id] : [$id, $tenantId];
$stmt = $db->prepare($query);
$stmt->execute($params);
$user = $stmt->fetch();

if (!$user) json_error('المستخدم غير موجود', 404);

$fields = [];
$values = [];

if (isset($data['name'])) {
    $fields[] = 'name = ?';
    $values[] = $data['name'];
}
if (isset($data['email'])) {
    $fields[] = 'email = ?';
    $values[] = $data['email'];
}
if (isset($data['role'])) {
    // Only super_admin can change roles
    if ($role !== 'super_admin' && $data['role'] === 'super_admin') {
        json_error('لا يمكنك منح صلاحية مدير النظام', 403);
    }
    $fields[] = 'role = ?';
    $values[] = $data['role'];
}
if (isset($data['phone'])) {
    $fields[] = 'phone = ?';
    $values[] = $data['phone'];
}
if (isset($data['is_active'])) {
    $fields[] = 'is_active = ?';
    $values[] = (int) $data['is_active'];
}

if (empty($fields)) json_error('لا توجد بيانات للتحديث', 422);

$fields[] = 'updated_at = NOW()';
$values[] = $id;

$sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?";
$db->prepare($sql)->execute($values);

AuditLogger::log('user.updated', 'user', $id, null, ['fields' => array_keys($data)], $decoded);

json_success(null, 'تم تحديث بيانات المستخدم بنجاح');
