<?php

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/helpers.php';
require_once __DIR__ . '/../../middleware/auth.php';

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

global $pdo;
$user = requireAuth();
$input = getJsonInput();

$name = trim($input['name'] ?? $user['name'] ?? '');
$phone = trim($input['phone'] ?? $user['phone'] ?? '');
$avatar = trim($input['avatar'] ?? $user['avatar'] ?? '');
$country = trim($input['country'] ?? $user['country'] ?? '');

if ($name === '') {
    jsonResponse(false, 'Name is required', null, 422);
}

$stmt = $pdo->prepare('UPDATE users SET name = :name, phone = :phone, avatar = :avatar, country = :country, agent = :agent, ip = :ip, updated_at = NOW() WHERE id = :id');
$stmt->execute([
    'name' => $name,
    'phone' => $phone !== '' ? $phone : null,
    'avatar' => $avatar !== '' ? $avatar : null,
    'country' => $country !== '' ? $country : null,
    'agent' => getUserAgent(),
    'ip' => getClientIp(),
    'id' => $user['id'],
]);

$fetch = $pdo->prepare('SELECT * FROM users WHERE id = :id LIMIT 1');
$fetch->execute(['id' => $user['id']]);
$updatedUser = $fetch->fetch();

jsonResponse(true, 'Profile updated successfully', sanitizeUser($updatedUser));
