<?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' => 'unauthorized']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $action = $_GET['action'] ?? 'list';

    switch ($action) {
        case 'list':
            $res = supabase_rest('GET', 'friends?select=*,friend:profiles!friend_id(id,username,display_name,elo_blitz,is_online)&status=eq.accepted', [], $token);
            $friends = [];
            if ($res['status'] === 200 && is_array($res['data'])) {
                foreach ($res['data'] as $row) {
                    if (isset($row['friend'])) {
                        $friends[] = $row['friend'];
                    }
                }
            }
            echo json_encode(['friends' => $friends]);
            break;

        case 'requests':
            $res = supabase_rest('GET', 'friends?select=*,sender:profiles!user_id(id,username,display_name)&status=eq.pending', [], $token);
            $requests = [];
            if ($res['status'] === 200 && is_array($res['data'])) {
                foreach ($res['data'] as $row) {
                    if (isset($row['sender'])) {
                        $requests[] = array_merge($row['sender'], ['id' => $row['id']]);
                    }
                }
            }
            echo json_encode(['requests' => $requests]);
            break;

        case 'search':
            $q = $_GET['q'] ?? '';
            if (strlen($q) < 2) {
                echo json_encode(['players' => []]);
                break;
            }
            $res = supabase_rest('GET', 'profiles?select=id,username,display_name,elo_blitz&or=(username.ilike.*' . urlencode($q) . '*,display_name.ilike.*' . urlencode($q) . '*)&limit=10', [], $token);
            echo json_encode(['players' => $res['data'] ?? []]);
            break;
    }
} elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';

    // Get current user info for notifications
    $currentUser = supabase_auth('user', [], $token, 'GET');
    $currentUserId = $currentUser['data']['id'] ?? null;

    switch ($action) {
        case 'add':
            $userId = $input['user_id'] ?? '';
            $res = supabase_rest('POST', 'friends', [
                'friend_id' => $userId,
                'status' => 'pending'
            ], $token);

            // Send notification to the recipient
            if ($currentUserId) {
                $profileRes = supabase_rest('GET', "profiles?id=eq.{$currentUserId}&select=display_name,username", [], SUPABASE_SERVICE_KEY);
                $senderName = $profileRes['data'][0]['display_name'] ?? $profileRes['data'][0]['username'] ?? 'لاعب';
                supabase_rest('POST', 'notifications', [
                    'user_id' => $userId,
                    'type' => 'friend_request',
                    'title' => 'طلب صداقة',
                    'title_ar' => 'طلب صداقة',
                    'body' => "{$senderName} أرسل لك طلب صداقة",
                    'body_ar' => "{$senderName} أرسل لك طلب صداقة",
                    'data' => json_encode(['requester_id' => $currentUserId]),
                ], SUPABASE_SERVICE_KEY);
            }

            echo json_encode(['ok' => true]);
            break;

        case 'accept':
            $requestId = $input['request_id'] ?? '';

            // Get the friend request to find the original sender
            $friendReq = supabase_rest('GET', "friends?id=eq.{$requestId}&select=user_id", [], SUPABASE_SERVICE_KEY);
            $requesterId = $friendReq['data'][0]['user_id'] ?? null;

            supabase_rest('PATCH', "friends?id=eq.{$requestId}", [
                'status' => 'accepted',
                'accepted_at' => date('c')
            ], $token);

            // Notify the original requester that the request was accepted
            if ($requesterId && $currentUserId) {
                $profileRes = supabase_rest('GET', "profiles?id=eq.{$currentUserId}&select=display_name,username", [], SUPABASE_SERVICE_KEY);
                $acceptorName = $profileRes['data'][0]['display_name'] ?? $profileRes['data'][0]['username'] ?? 'لاعب';
                supabase_rest('POST', 'notifications', [
                    'user_id' => $requesterId,
                    'type' => 'friend_accepted',
                    'title' => 'تم قبول طلب الصداقة',
                    'title_ar' => 'تم قبول طلب الصداقة',
                    'body' => "{$acceptorName} قبل طلب صداقتك",
                    'body_ar' => "{$acceptorName} قبل طلب صداقتك",
                    'data' => json_encode(['friend_id' => $currentUserId]),
                ], SUPABASE_SERVICE_KEY);
            }

            echo json_encode(['ok' => true]);
            break;

        case 'reject':
            $requestId = $input['request_id'] ?? '';
            supabase_rest('DELETE', "friends?id=eq.{$requestId}", [], $token);
            echo json_encode(['ok' => true]);
            break;

        case 'remove':
            $friendId = $input['friend_id'] ?? '';
            supabase_rest('DELETE', "friends?friend_id=eq.{$friendId}", [], $token);
            echo json_encode(['ok' => true]);
            break;

        default:
            echo json_encode(['error' => 'invalid action']);
    }
}
