<?php

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../config/helpers.php';
require_once __DIR__ . '/../../../middleware/admin.php';
require_once __DIR__ . '/UserRepository.php';

if (!in_array(getMethod(), ['PUT', 'PATCH'], true)) {
    jsonResponse(false, 'Method not allowed', null, 405);
}

global $pdo;
requireAdmin();
$repo = new UserRepository($pdo);
$route = getApiRouteSegments();
$id = isset($route[2]) ? (int) $route[2] : 0;
$input = getJsonInput();

if ($id <= 0) {
    jsonResponse(false, 'Invalid user id', null, 422);
}

$current = $repo->findById($id);
if (!$current) {
    jsonResponse(false, 'User not found', null, 404);
}

$name = trim($input['name'] ?? $current['name']);
$email = strtolower(trim($input['email'] ?? $current['email']));
$phone = trim($input['phone'] ?? ($current['phone'] ?? ''));
$avatar = trim($input['avatar'] ?? ($current['avatar'] ?? ''));
$country = trim($input['country'] ?? ($current['country'] ?? ''));
$role = trim($input['role'] ?? $current['role']);
$isActive = isset($input['is_active']) ? (int) (bool) $input['is_active'] : (int) $current['is_active'];
$newPassword = (string) ($input['password'] ?? '');

$existingByEmail = $repo->findByEmail($email);
if ($existingByEmail && (int) $existingByEmail['id'] !== $id) {
    jsonResponse(false, 'Email already exists', null, 409);
}

$repo->update($id, [
    'name' => $name,
    'email' => $email,
    'phone' => $phone !== '' ? $phone : null,
    'avatar' => $avatar !== '' ? $avatar : null,
    'country' => $country !== '' ? $country : null,
    'agent' => getUserAgent(),
    'ip' => getClientIp(),
    'is_active' => $isActive,
    'role' => in_array($role, ['admin', 'user'], true) ? $role : 'user',
    'password' => $newPassword !== '' ? password_hash($newPassword, PASSWORD_DEFAULT) : null,
]);

jsonResponse(true, 'User updated successfully', $repo->findById($id));
