<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, 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);
$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') {
        // Get unread counts per friendship
        $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' => []]);
        }

        $unreadCounts = [];
        foreach ($friendships as $f) {
            $friendId = $f['requester_id'] === $userId ? $f['addressee_id'] : $f['requester_id'];
            $unread = $sdb->get('friend_messages', [
                'friendship_id' => 'eq.' . $f['id'],
                'sender_id' => 'eq.' . $friendId,
                'read_at' => 'is.null',
                'select' => 'id'
            ]);
            $count = (is_array($unread) && !isset($unread['error'])) ? count($unread) : 0;
            if ($count > 0) {
                $unreadCounts[$friendId] = $count;
            }
        }

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

    if ($action === 'recent') {
        // Get recent conversations (last message per friend)
        $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' => []]);
        }

        $conversations = [];
        foreach ($friendships as $f) {
            $friendId = $f['requester_id'] === $userId ? $f['addressee_id'] : $f['requester_id'];
            $lastMsg = $sdb->get('friend_messages', [
                'friendship_id' => 'eq.' . $f['id'],
                'select' => 'id,sender_id,content,message_type,created_at,read_at',
                'order' => 'created_at.desc',
                'limit' => 1
            ]);
            if (is_array($lastMsg) && !isset($lastMsg['error']) && !empty($lastMsg)) {
                $conversations[] = [
                    'friend_id' => $friendId,
                    'friendship_id' => $f['id'],
                    'last_message' => $lastMsg[0]
                ];
            }
        }

        // Sort by most recent message
        usort($conversations, fn($a, $b) => strcmp($b['last_message']['created_at'], $a['last_message']['created_at']));

        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;
}
