<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, 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);
$db = supabase($token);

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? ($_POST['action'] ?? '');

if ($method === 'GET') {
    $action = $_GET['action'] ?? 'list';
    if ($action === 'list') {
        $friends = $db->get('friendships', [
            'or' => "(requester_id.eq.{$userId},addressee_id.eq.{$userId})",
            'status' => 'eq.accepted',
            'select' => 'id,requester_id,addressee_id'
        ]);

        if (!is_array($friends) || isset($friends['error'])) {
            jsonResponse(['friends' => []]);
        }

        $friendIds = [];
        foreach ($friends as $f) {
            $friendIds[] = $f['requester_id'] === $userId ? $f['addressee_id'] : $f['requester_id'];
        }

        if (empty($friendIds)) {
            jsonResponse(['friends' => []]);
        }

        $idList = implode(',', $friendIds);
        $profiles = $db->get('profiles', [
            'id' => "in.({$idList})",
            'select' => 'id,username,display_name,avatar_url,is_online,level'
        ]);

        jsonResponse(['friends' => $profiles ?: []]);
    }

    if ($action === 'pending') {
        $pending = $db->get('friendships', [
            'addressee_id' => 'eq.' . $userId,
            'status' => 'eq.pending',
            'select' => 'id,requester_id'
        ]);
        jsonResponse(['pending' => $pending ?: []]);
    }

    if ($action === 'search') {
        $query = $_GET['query'] ?? '';
        if (strlen($query) < 2) jsonError('Query too short');

        $results = $db->get('profiles', [
            'username' => 'ilike.*' . $query . '*',
            'id' => 'neq.' . $userId,
            'select' => 'id,username,display_name,avatar_url,level,is_online',
            'limit' => 10
        ]);

        jsonResponse(['players' => is_array($results) && !isset($results['error']) ? $results : []]);
    }
}

if ($method === 'POST') {
    $input = getInput();
    $action = $input['action'] ?? '';

    if ($action === 'request') {
        $targetId = $input['target_id'] ?? '';
        if (!$targetId) jsonError('target_id required');

        $result = $db->insert('friendships', [
            'requester_id' => $userId,
            'addressee_id' => $targetId,
            'status' => 'pending'
        ]);
        if (isset($result['error'])) jsonError($result['error']);
        jsonResponse(['success' => true]);
    }

    if ($action === 'accept') {
        $friendshipId = $input['friendship_id'] ?? '';
        if (!$friendshipId) jsonError('friendship_id required');

        $result = $db->update('friendships', ['status' => 'accepted'], [
            'id' => 'eq.' . $friendshipId,
            'addressee_id' => 'eq.' . $userId
        ]);
        jsonResponse(['success' => true]);
    }
}

if ($method === 'DELETE') {
    $input = getInput();
    $targetId = $input['target_id'] ?? '';
    if (!$targetId) jsonError('target_id required');

    $db->delete('friendships', [
        'or' => "(and(requester_id.eq.{$userId},addressee_id.eq.{$targetId}),and(requester_id.eq.{$targetId},addressee_id.eq.{$userId}))"
    ]);
    jsonResponse(['success' => true]);
}

jsonError('Invalid request', 400);
