<?php
// Aktifkan error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Sertakan koneksi database
include 'koneksi.php';

$responseLog = []; // ← simpan log progres di sini

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

function curl_request($url, $method = 'GET', $data = [], $headers = [])
{
    $ch = curl_init();

    if (strtoupper($method) === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        $headers[] = 'Content-Type: application/json';
    } elseif (strtoupper($method) === 'GET' && !empty($data)) {
        $url .= '?' . http_build_query($data);
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        throw new Exception('cURL Error: ' . curl_error($ch));
    }

    curl_close($ch);
    return $response;
}

try {
    $walletAddress = $_POST['from_wallet'];
    $stmt = $pdo->prepare("SELECT id, private_key FROM users WHERE wallet_address = ?");
    $stmt->execute([$walletAddress]);
    $userData = $stmt->fetch();

    if (!$userData || empty($userData['id']) || empty($userData['private_key'])) {
        $responseLog[] = 'User tidak ditemukan.';
        echo json_encode(['error' => 'User tidak ditemukan', 'log' => $responseLog]);
        exit;
    }
    $userId = $userData['id'];
    $privateKey = $userData['private_key'];

    $to = $_POST['to_wallet'] ?? null;
    $amount = $_POST['amount'] ?? null;
    $type = $_POST['type'] ?? null;
    $keterangan = "Deposit";

    if (!$to || !$amount || !$type) {
        $responseLog[] = 'Field wajib belum lengkap.';
        echo json_encode(['error' => 'Field wajib belum lengkap', 'log' => $responseLog]);
        exit;
    }

    $contractAddress = match ($type) {
        'saldo' => 'ebc_1e0b995b44819d162a523762ae313571fba442ab670e62cb7504567c3539a364',
        'point' => 'ebc_11360f89b68eacad1bfbf391d44531a5cf17cd39aca3ba3220d53b541c2a018f',
        default => null
    };

    if (!$contractAddress) {
        $responseLog[] = 'Tipe token tidak valid.';
        echo json_encode(['error' => 'Tipe token tidak valid', 'log' => $responseLog]);
        exit;
    }

    $decryptedPrivateKey = openssl_decrypt(
        $privateKey,
        'AES-256-CBC',
        'YOUR_VERY_STRONG_KEY',
        0,
        'a_random_iv'
    );

    if (!$decryptedPrivateKey) {
        $responseLog[] = 'Gagal mendekripsi private key.';
        echo json_encode(['error' => 'Gagal dekripsi', 'log' => $responseLog]);
        exit;
    }

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

    $responseLog[] = 'Respon API diterima.';

    $responseData = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        $responseLog[] = 'JSON API tidak valid.';
        throw new Exception('JSON decode error: ' . json_last_error_msg());
    }

    if (!isset($responseData['txHash'])) {
        $responseLog[] = 'txHash tidak ditemukan di respon API.';
        throw new Exception('txHash tidak ditemukan');
    }

    $transactionHash = $responseData['txHash'];
    $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 (?, ?, ?, ?, ?, ?, ?, ?)");
    $insertSuccess = $stmt->execute([
        $userId,
        $to,
        $amount,
        $type,
        $contractAddress,
        $transactionHash,
        $status,
        $keterangan
    ]);
    if ($insertSuccess) {
        // Redirect ke halaman transaksi
        $_SESSION['success'] = "Deposit berhasil dikirim!";
        header("Location: deposit");
        exit();
    } else {
        $_SESSION['error'] = "Deposit gagal dikirim!";
        header("Location: deposit");
        exit();
    }
} catch (PDOException $e) {
    $responseLog[] = 'Kesalahan database: ' . $e->getMessage();
    echo json_encode(['error' => 'Database error', 'log' => $responseLog]);
} catch (Exception $e) {
    $responseLog[] = 'Error: ' . $e->getMessage();
    echo json_encode(['error' => 'Unexpected error', 'log' => $responseLog]);
}
