<?php
require_once 'config.php';

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

if ($method === 'POST') {
    if (!isset($input['apple_id']) || !isset($input['email'])) {
        jsonResponse(['success' => false, 'error' => 'Missing required fields'], 400);
    }

    $pdo = getDB();
    
    $stmt = $pdo->prepare("SELECT * FROM users WHERE apple_id = ?");
    $stmt->execute([$input['apple_id']]);
    $user = $stmt->fetch();

    if ($user) {
        if (isset($input['onesignal_player_id'])) {
            $stmt = $pdo->prepare("UPDATE users SET onesignal_player_id = ? WHERE id = ?");
            $stmt->execute([$input['onesignal_player_id'], $user['id']]);
        }
        jsonResponse(['success' => true, 'user' => $user, 'is_new' => false]);
    } else {
        $username = isset($input['username']) ? $input['username'] : 'user_' . uniqid();
        
        $stmt = $pdo->prepare("INSERT INTO users (apple_id, email, username, onesignal_player_id, language) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $input['apple_id'],
            $input['email'],
            $username,
            $input['onesignal_player_id'] ?? null,
            $input['language'] ?? 'en'
        ]);
        
        $userId = $pdo->lastInsertId();
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $newUser = $stmt->fetch();
        
        jsonResponse(['success' => true, 'user' => $newUser, 'is_new' => true], 201);
    }
}
?>