<?php

require_once __DIR__ . '/../config/database.php';

header('Content-Type: application/json');

$token = get_auth_token();

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'غير مصرح']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $userRes = supabase_auth('user', [], $token, 'GET');

    if ($userRes['status'] !== 200 || !isset($userRes['data']['id'])) {
        http_response_code(401);
        echo json_encode(['error' => 'جلسة غير صالحة']);
        exit;
    }

    $userId = $userRes['data']['id'];

    $profileRes = supabase_rest('GET', 'profiles?id=eq.' . $userId . '&select=*', [], $token);

    if ($profileRes['status'] === 200 && !empty($profileRes['data'])) {
        echo json_encode(['profile' => $profileRes['data'][0]]);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'الملف الشخصي غير موجود']);
    }

} elseif ($method === 'PATCH') {
    $input = json_decode(file_get_contents('php://input'), true);

    $userRes = supabase_auth('user', [], $token, 'GET');
    if ($userRes['status'] !== 200) {
        http_response_code(401);
        echo json_encode(['error' => 'غير مصرح']);
        exit;
    }

    $userId = $userRes['data']['id'];
    $allowed = ['display_name', 'display_name_ar', 'bio', 'bio_ar', 'avatar_url', 'country_code', 'city'];
    $update = array_intersect_key($input, array_flip($allowed));

    if (empty($update)) {
        http_response_code(400);
        echo json_encode(['error' => 'لا حقول للتحديث']);
        exit;
    }

    $result = supabase_rest('PATCH', 'profiles?id=eq.' . $userId, $update, $token);
    echo json_encode(['success' => true]);

} else {
    http_response_code(405);
    echo json_encode(['error' => 'method not allowed']);
}
