<?php
require_once __DIR__ . '/../config/cors.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../utils/helpers.php';

$token = getAuthToken();
$user = getUserFromToken($token);

if (!$user) {
    errorResponse('Unauthorized', 401);
}

$userId = $user['id'];
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    try {
        $stmt = $pdo->prepare("
            SELECT t.*, 
                   s.email as sender_email, s.wallet_address as sender_address,
                   r.email as receiver_email, r.wallet_address as receiver_address
            FROM transactions t
            LEFT JOIN users s ON t.sender_id = s.id
            LEFT JOIN users r ON t.receiver_id = r.id
            WHERE t.sender_id = ? OR t.receiver_id = ?
            ORDER BY t.created_at DESC
            LIMIT 50
        ");
        $stmt->execute([$userId, $userId]);
        $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Format for frontend
        $formatted = array_map(function($tx) use ($userId) {
            $isSender = $tx['sender_id'] == $userId;
            $type = $isSender ? 'send' : 'receive';
            
            // Determine 'counterparty' address for display
            $otherAddress = $isSender ? $tx['receiver_address'] : $tx['sender_address'];
            $otherEmail = $isSender ? $tx['receiver_email'] : $tx['sender_email'];

            return [
                'id' => $tx['id'],
                'type' => $type,
                'asset' => $tx['symbol'],
                'amount' => $tx['amount'],
                'counterparty' => $otherAddress ?? $otherEmail ?? 'Unknown',
                'date' => $tx['created_at'], // Frontend can format relative time
                'status' => $tx['status'],
                'tx_hash' => $tx['tx_hash'],
                'exchange' => $tx['exchange'] ?? 'Unknown'
            ];
        }, $transactions);

        jsonResponse(['transactions' => $formatted]);
    } catch (PDOException $e) {
        errorResponse('Database error: ' . $e->getMessage());
    }
} else {
    errorResponse('Method not allowed', 405);
}
?>
