<?php
// history.php

header("Content-Type: application/json; charset=UTF-8");

require 'security.php'; // Validasi token, session, dll
require 'logger.php';   // Fungsi log_activity()
require 'db.php';       // Koneksi PDO $pdo

// Hanya izinkan POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on history.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Ambil token dari header Authorization
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    $authorizationHeader = $headers['Authorization'];
    $token = str_replace("Bearer ", "", $authorizationHeader);
} else {
    http_response_code(401);
    echo json_encode(['error' => 'Authorization header missing']);
    log_activity("Authorization header missing in history.php");
    exit;
}

try {
    // Validasi token
    $stmt = $pdo->prepare("SELECT user_id FROM tokens WHERE token = ? AND expires_at >= NOW()");
    $stmt->execute([$token]);
    $tokenData = $stmt->fetch();

    if (!$tokenData) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        log_activity("Invalid or expired token in history.php");
        exit;
    }

    $userId = $tokenData['user_id'];

    // Ambil wallet user
    $stmt = $pdo->prepare("SELECT wallet_address, name FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $userData = $stmt->fetch();

    if (!$userData || empty($userData['wallet_address'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Wallet not found']);
        log_activity("Wallet not found for user ID '$userId'");
        exit;
    }

    $userWalletAddress = strtolower(trim($userData['wallet_address']));
    $userName = $userData['name'];

    // Ambil transaksi sebagai pengirim atau penerima
    $stmt = $pdo->prepare("
        SELECT 
            t.*,
            u.name AS sender_name,
            u.wallet_address AS sender_wallet
        FROM transactions t
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.user_id = :user_id OR LOWER(t.to_address) = :wallet_address
        ORDER BY t.created_at DESC
    ");
    $stmt->execute([
        ':user_id' => $userId,
        ':wallet_address' => $userWalletAddress,
    ]);

    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$transactions) {
        http_response_code(404);
        echo json_encode([
            'status' => 'empty',
            'user_id' => $userId,
            'wallet' => $userWalletAddress,
            'message' => 'No transactions found'
        ]);
        log_activity("No transactions found for user ID '$userId'");
        exit;
    }

    // Kategorikan debit/kredit
    $history = [];
    foreach ($transactions as $tx) {
        $isIncoming = (strtolower($tx['to_address']) === $userWalletAddress);
        $isOwnTx = ($tx['user_id'] == $userId);

        if ($isIncoming && !$isOwnTx) {
            $transactionType = 'debit'; // Dana masuk
        } elseif (!$isIncoming && $isOwnTx) {
            $transactionType = 'credit'; // Dana keluar
        } else {
            $transactionType = 'self'; // Transfer ke diri sendiri
        }

        $history[] = [
            'transaction_type' => $transactionType,
            'type' => $tx['type'],
            'amount' => $tx['amount'],
            'from_address' => $tx['sender_wallet'],
            'to_address' => $tx['to_address'],
            'contract_address' => $tx['contract_address'],
            'transaction_hash' => $tx['transaction_hash'],
            'status' => $tx['status'],
            'created_at' => $tx['created_at'],
            'sender_name' => $tx['sender_name'],
        ];
    }

    echo json_encode([
        'status' => 'success',
        'user_id' => $userId,
        'wallet' => $userWalletAddress,
        'data' => $history,
    ]);
    log_activity("Transaction history sent for user ID '$userId'");

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("history.php error: " . $e->getMessage());
    exit;
}
?>
