<?php
// send.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 send.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 send.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 send.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();

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

    // 3) Ambil input dari POST request
    $input = json_decode(file_get_contents('php://input'), true);

    if (!isset($input['to']) || !isset($input['amount']) || !isset($input['type'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        log_activity("Missing required fields in send.php");
        exit;
    }

    $to = $input['to'];
    $amount = $input['amount'];
    $type = $input['type'];
    $keterangan = isset($input['keterangan']) ? $input['keterangan'] : '';

    // 4) Tentukan contractAddress berdasarkan type (saldo atau point)
    $contractAddress = '';
    if ($type === 'saldo') {
        $contractAddress = 'ebc_1e0b995b44819d162a523762ae313571fba442ab670e62cb7504567c3539a364';
    } elseif ($type === 'point') {
        $contractAddress = 'ebc_11360f89b68eacad1bfbf391d44531a5cf17cd39aca3ba3220d53b541c2a018f';
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid type']);
        log_activity("Invalid type in send.php");
        exit;
    }

    // 5) Dekripsi private key (gunakan metode yang sesuai dengan enkripsi di wallet.php)
    $decryptedPrivateKey = openssl_decrypt($userData['private_key'], 'AES-256-CBC', 'YOUR_VERY_STRONG_KEY', 0, 'a_random_iv'); // Contoh: AES-256-CBC

    if (!$decryptedPrivateKey) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to decrypt private key']);
        log_activity("Failed to decrypt private key for user ID '$userId'");
        exit;
    }

    // 6) Kirim request ke API blockchain
    $response = curl_request('https://blockchain.sisiteknis.com/sendToken', 'POST', [
        'privateKey' => $decryptedPrivateKey,
        'to' => $to,
        'amount' => $amount,
        'contractAddress' => $contractAddress,
    ]);

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

    $responseData = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        $error_message = 'Invalid JSON response from sendToken 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;
    }

    // 7) Ambil transaction hash (txHash) dari respons API
    if (!isset($responseData['txHash'])) {
        http_response_code(500);
        echo json_encode(['error' => 'Transaction hash not found in API response']);
        log_activity("Transaction hash not found in API response for user ID '$userId'");
        exit;
    }

    $transactionHash = $responseData['txHash'];

    // 8) Simpan transaksi ke database
    $status = isset($responseData['status']) && $responseData['status'] === 'success' ? 'success' : 'failed';

    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, to_address, amount, type, contract_address, transaction_hash, status, keterangan) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$userId, $to, $amount, $type, $contractAddress, $transactionHash, $status, $keterangan]);

    // 9) Response berdasarkan hasil dari API blockchain
    if ($status === 'success') {
        http_response_code(200);
        echo json_encode($responseData);
        log_activity("Token sent successfully for user ID '$userId'. Transaction hash: $transactionHash");
    } else {
        http_response_code(400);
        echo json_encode($responseData);
        log_activity("Failed to send token for user ID '$userId': " . $responseData['message']);
    }

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