<?php
require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

if ($method === 'GET') {
    if (!isset($_GET['user_id'])) {
        jsonResponse(['error' => 'User ID required'], 400);
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$_GET['user_id']]);
    $user = $stmt->fetch();
    
    if ($user) {
        jsonResponse(['success' => true, 'user' => $user]);
    } else {
        jsonResponse(['error' => 'User not found'], 404);
    }
}

if ($method === 'PUT') {
    if (!isset($input['user_id'])) {
        jsonResponse(['error' => 'User ID required'], 400);
    }
    
    $pdo = getDB();
    $fields = [];
    $values = [];
    
    if (isset($input['first_name'])) {
        $fields[] = 'first_name = ?';
        $values[] = $input['first_name'];
    }
    if (isset($input['last_name'])) {
        $fields[] = 'last_name = ?';
        $values[] = $input['last_name'];
    }
    if (isset($input['username'])) {
        $fields[] = 'username = ?';
        $values[] = $input['username'];
    }
    if (isset($input['tennis_experience'])) {
        $fields[] = 'tennis_experience = ?';
        $values[] = $input['tennis_experience'];
    }
    if (isset($input['hours_per_week'])) {
        $fields[] = 'hours_per_week = ?';
        $values[] = $input['hours_per_week'];
    }
    if (isset($input['profile_photo'])) {
        $fields[] = 'profile_photo = ?';
        $values[] = $input['profile_photo'];
    }
    if (isset($input['language'])) {
        $fields[] = 'language = ?';
        $values[] = $input['language'];
    }
    
    if (empty($fields)) {
        jsonResponse(['error' => 'No fields to update'], 400);
    }
    
    $values[] = $input['user_id'];
    $sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($values);
    
    jsonResponse(['success' => true, 'message' => 'Profile updated']);
}
?>