<?php

header('Content-Type: application/json');
require_once __DIR__ . '/../includes/cors.php';

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);
$method = $_SERVER['REQUEST_METHOD'];
$sdb = supabaseService();

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

    if ($action === 'history') {
        $friendId = $_GET['friend_id'] ?? '';
        if (!$friendId) jsonError('friend_id required');

        // Find the friendship between these two users
        $friendship = findFriendship($sdb, $userId, $friendId);
        if (!$friendship) jsonError('Not friends');

        $before = $_GET['before'] ?? null;
        $limit = min(intval($_GET['limit'] ?? 50), 100);

        $params = [
            'friendship_id' => 'eq.' . $friendship['id'],
            'select' => 'id,sender_id,content,message_type,metadata,created_at,read_at',
            'order' => 'created_at.desc',
            'limit' => $limit
        ];
        if ($before) {
            $params['created_at'] = 'lt.' . $before;
        }

        $messages = $sdb->get('friend_messages', $params);
        if (!is_array($messages) || isset($messages['error'])) {
            jsonResponse(['messages' => []]);
        }

        // Mark unread messages from friend as read
        $sdb->update('friend_messages', ['read_at' => gmdate('c')], [
            'friendship_id' => 'eq.' . $friendship['id'],
            'sender_id' => 'eq.' . $friendId,
            'read_at' => 'is.null'
        ]);

        jsonResponse(['messages' => array_reverse($messages), 'friendship_id' => $friendship['id']]);
    }

    if ($action === 'unread') {
        $friendships = $sdb->get('friendships', [
            'or' => "(requester_id.eq.{$userId},addressee_id.eq.{$userId})",
            'status' => 'eq.accepted',
            'select' => 'id,requester_id,addressee_id'
        ]);

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

        $fIds = array_column($friendships, 'id');
        $allUnread = $sdb->get('friend_messages', [
            'friendship_id' => 'in.(' . implode(',', $fIds) . ')',
            'sender_id' => 'neq.' . $userId,
            'read_at' => 'is.null',
            'select' => 'friendship_id,sender_id'
        ]);

        $unreadCounts = [];
        if (is_array($allUnread) && !isset($allUnread['error'])) {
            foreach ($allUnread as $msg) {
                $sid = $msg['sender_id'];
                $unreadCounts[$sid] = ($unreadCounts[$sid] ?? 0) + 1;
            }
        }

        jsonResponse(['unread' => $unreadCounts]);
    }

    if ($action === 'recent') {
        $friendships = $sdb->get('friendships', [
            'or' => "(requester_id.eq.{$userId},addressee_id.eq.{$userId})",
            'status' => 'eq.accepted',
            'select' => 'id,requester_id,addressee_id'
        ]);

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

        $fIds = array_column($friendships, 'id');
        $fMap = [];
        foreach ($friendships as $f) {
            $fMap[$f['id']] = $f['requester_id'] === $userId ? $f['addressee_id'] : $f['requester_id'];
        }

        $allMessages = $sdb->get('friend_messages', [
            'friendship_id' => 'in.(' . implode(',', $fIds) . ')',
            'select' => 'id,friendship_id,sender_id,content,message_type,created_at,read_at',
            'order' => 'created_at.desc',
            'limit' => count($fIds) * 2
        ]);

        $conversations = [];
        $seen = [];
        if (is_array($allMessages) && !isset($allMessages['error'])) {
            foreach ($allMessages as $msg) {
                $fid = $msg['friendship_id'];
                if (isset($seen[$fid])) continue;
                $seen[$fid] = true;
                $conversations[] = [
                    'friend_id' => $fMap[$fid] ?? '',
                    'friendship_id' => $fid,
                    'last_message' => $msg
                ];
            }
        }

        jsonResponse(['conversations' => $conversations]);
    }

    jsonError('Invalid action');
}

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

    if ($action === 'send') {
        $friendId = $input['friend_id'] ?? '';
        $content = trim($input['content'] ?? '');
        $messageType = $input['message_type'] ?? 'text';
        $metadata = $input['metadata'] ?? [];

        if (!$friendId) jsonError('friend_id required');
        if (!$content) jsonError('content required');
        if (mb_strlen($content) > 500) jsonError('Message too long (max 500 chars)');

        // Check blocks in both directions
        $blocks = $sdb->get('player_blocks', [
            'or' => "(and(player_id.eq.{$userId},blocked_id.eq.{$friendId}),and(player_id.eq.{$friendId},blocked_id.eq.{$userId}))",
            'type' => 'eq.block',
            'limit' => 1
        ]);
        if (is_array($blocks) && !isset($blocks['error']) && !empty($blocks)) {
            jsonError('Cannot send message to this player');
        }

        $friendship = findFriendship($sdb, $userId, $friendId);
        if (!$friendship) jsonError('Not friends');

        $msg = $sdb->insert('friend_messages', [
            'friendship_id' => $friendship['id'],
            'sender_id' => $userId,
            'content' => $content,
            'message_type' => $messageType,
            'metadata' => !empty($metadata) ? $metadata : new \stdClass()
        ]);

        if (isset($msg['error'])) jsonError($msg['error']);

        jsonResponse(['message' => $msg[0] ?? $msg, 'success' => true]);
    }

    if ($action === 'mark-read') {
        $friendId = $input['friend_id'] ?? '';
        if (!$friendId) jsonError('friend_id required');

        $friendship = findFriendship($sdb, $userId, $friendId);
        if (!$friendship) jsonError('Not friends');

        $sdb->update('friend_messages', ['read_at' => gmdate('c')], [
            'friendship_id' => 'eq.' . $friendship['id'],
            'sender_id' => 'eq.' . $friendId,
            'read_at' => 'is.null'
        ]);

        jsonResponse(['success' => true]);
    }

    jsonError('Invalid action');
}

jsonError('Method not allowed', 405);

function findFriendship($sdb, string $userId, string $friendId): ?array {
    $rows = $sdb->get('friendships', [
        'or' => "(and(requester_id.eq.{$userId},addressee_id.eq.{$friendId}),and(requester_id.eq.{$friendId},addressee_id.eq.{$userId}))",
        'status' => 'eq.accepted',
        'select' => 'id,requester_id,addressee_id',
        'limit' => 1
    ]);
    if (is_array($rows) && !isset($rows['error']) && !empty($rows)) {
        return $rows[0];
    }
    return null;
}
