<?php
require_once '../config.php';
require_once '../../includes/Auth.php';

$auth = new Auth();
$user = $auth->requireAuth();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['success' => false, 'message' => 'Method not allowed'], 405);
}

$input = json_decode(file_get_contents('php://input'), true);

try {
    $updateData = [];
    if (isset($input['name'])) $updateData['name'] = $input['name'];
    if (isset($input['phone'])) $updateData['phone'] = $input['phone'];
    if (isset($input['avatar'])) $updateData['avatar'] = $input['avatar'];

    if (isset($input['new_password']) && !empty($input['new_password'])) {
        $updateData['password'] = $input['new_password'];
    }

    if (empty($updateData)) {
        throw new Exception("No data provided for update.");
    }

    $updatedUser = $auth->updateUser($user['id'], $updateData);
    jsonResponse(['success' => true, 'message' => 'Profile updated successfully', 'user' => $updatedUser]);

} catch (Exception $e) {
    jsonResponse(['success' => false, 'message' => $e->getMessage()], 400);
}
?>