<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$token = requireAuth();
$userId = getUserId($token);
if (!$userId) jsonError('Invalid user', 401);

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $targetId = $_GET['id'] ?? $userId;
    $db = supabase($token);
    $profiles = $db->get('profiles', ['id' => 'eq.' . $targetId, 'select' => '*', 'limit' => 1]);

    if (!is_array($profiles) || isset($profiles['error']) || empty($profiles)) {
        jsonError('Profile not found', 404);
    }

    $profile = $profiles[0];
    $ratings = $db->get('player_game_ratings', ['player_id' => 'eq.' . $targetId, 'select' => 'game_key,time_control,rating,games_played,wins,losses,draws']);

    $profile['ratings'] = is_array($ratings) && !isset($ratings['error']) ? $ratings : [];

    jsonResponse($profile);
}

if ($method === 'PATCH') {
    $input = getInput();
    $allowed = ['display_name', 'display_name_ar', 'avatar_url', 'frame_id', 'border_color', 'country_code'];
    $data = array_intersect_key($input, array_flip($allowed));

    if (empty($data)) jsonError('No valid fields to update');

    $db = supabase($token);
    $result = $db->update('profiles', $data, ['id' => 'eq.' . $userId]);

    if (isset($result['error'])) {
        jsonError($result['error']);
    }

    jsonResponse($result[0] ?? ['success' => true]);
}

jsonError('Method not allowed', 405);
