<?php
// wallet.php

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

require 'security.php'; // Pastikan file ini ada dan berfungsi
require 'logger.php'; // Pastikan file ini ada dan berfungsi
require 'db.php';       // Pastikan koneksi database di db.php berhasil

// Fungsi untuk melakukan cURL request (diperbaiki)
function curl_request($url, $method, $data = null) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

    if ($data) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($ch);
    $info = curl_getinfo($ch);

    if (curl_errno($ch)) {
        $error_message = "cURL error: " . curl_error($ch) . " - Info: " . print_r($info, true);
        log_activity($error_message);
        curl_close($ch);
        return null;
    }

    if ($info['http_code'] != 200) {
        $error_message = "API request failed with HTTP code: " . $info['http_code'] . " - Response: " . $response;
        log_activity($error_message);
        curl_close($ch);
        return null;
    }

    curl_close($ch);
    return $response;
}

// Pengecekan method dan authorization header
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on wallet.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

$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 wallet.php");
    exit;
}

try {
    // 1) Cari user_id berdasarkan 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 wallet.php");
        exit;
    }

    $userId = $tokenData['user_id'];

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

    // 3) Jika wallet_address dan private_key belum ada, buat wallet baru
    if (!$userData || empty($userData['wallet_address']) || empty($userData['private_key'])) {
        $response = curl_request('https://blockchain.sisiteknis.com/createWallet', 'POST');

        log_activity("createWallet response: " . $response);

        $walletData = json_decode($response, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            $error_message = 'Invalid JSON response from createWallet API: ' . json_last_error_msg() . " - Response: " . $response;
            http_response_code(500);
            echo json_encode(['error' => 'Invalid JSON response from API']);
            log_activity($error_message);
            exit;
        }

        if (!$walletData || !isset($walletData['address']) || !isset($walletData['privateKey'])) {
            $error_message = "Failed to create wallet. Invalid data: " . print_r($walletData, true) . " - Response: " . $response;
            http_response_code(500);
            echo json_encode(['error' => 'Failed to create wallet']);
            log_activity($error_message);
            exit;
        }

        // Enkripsi private key (gunakan metode yang lebih aman dari AES-128-ECB)
        $encryptedPrivateKey = openssl_encrypt($walletData['privateKey'], 'AES-256-CBC', 'YOUR_VERY_STRONG_KEY', 0, 'a_random_iv'); // Contoh: AES-256-CBC

        // Simpan wallet_address dan private_key ke database
        $stmt = $pdo->prepare("UPDATE users SET wallet_address = ?, private_key = ? WHERE id = ?");
        $stmt->execute([$walletData['address'], $encryptedPrivateKey, $userId]);

        $userData['wallet_address'] = $walletData['address'];
        $userData['private_key'] = $encryptedPrivateKey;
    }

    // 4) Ambil balance dari API eksternal
    $balanceResponse = curl_request('https://blockchain.sisiteknis.com/getBalance', 'POST', ['address' => $userData['wallet_address']]);

    log_activity("getBalance response: " . $balanceResponse);

    $balanceData = json_decode($balanceResponse, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        $error_message = 'Invalid JSON response from getBalance API: ' . json_last_error_msg() . " - Response: " . $balanceResponse;
        http_response_code(500);
        echo json_encode(['error' => 'Invalid JSON response from API']);
        log_activity($error_message);
        exit;
    }

    if (!$balanceData || !isset($balanceData['balance'])) {
        $error_message = "Failed to get balance. Invalid data: " . print_r($balanceData, true) . " - Response: " . $balanceResponse;
        http_response_code(500);
        echo json_encode(['error' => 'Failed to get balance']);
        log_activity($error_message);
        exit;
    }

    // 5) Response data wallet
    http_response_code(200);
    echo json_encode([
        'wallet_address' => $userData['wallet_address'],
        'balance' => $balanceData['balance'],
        'tokens' => $balanceData['tokens'] ?? [],
    ]);
    log_activity("Wallet info retrieved for user ID '$userId'.");

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

?>