<?php
// api/get_transaction.php

// Include file koneksi database
require_once 'db.php'; // Sesuaikan path sesuai struktur folder Anda

// Set header untuk response JSON
header('Content-Type: application/json');

// Daftar IP yang diizinkan (whitelist)
$whitelist_ips = [
    '84.247.149.65'
];

// Ambil IP client
$client_ip = $_SERVER['REMOTE_ADDR'];

// Cek apakah IP client ada di whitelist
if (!in_array($client_ip, $whitelist_ips)) {
    http_response_code(403);
    echo json_encode([
        'status' => 'error',
        'message' => 'Access denied: Your IP is not whitelisted'
    ]);
    exit;
}

try {
    // Query untuk mengambil satu transaksi dengan statusserver = 0
    $stmt = $pdo->prepare("SELECT * FROM transactions WHERE statusserver = 0 LIMIT 1");
    $stmt->execute();
    $transaction = $stmt->fetch();

    if (!$transaction) {
        http_response_code(404);
        echo json_encode([
            'status' => 'error',
            'message' => 'No unprocessed transactions found'
        ]);
        exit;
    }

    // Update statusserver menjadi 1 untuk transaksi yang diambil
    $update_stmt = $pdo->prepare("UPDATE transactions SET statusserver = 1 WHERE id = ?");
    $update_stmt->execute([$transaction['id']]);

    // Kirim response sukses
    http_response_code(200);
    echo json_encode([
        'status' => 'success',
        'data' => $transaction,
        'message' => 'Transaction retrieved and status updated successfully'
    ]);

} catch (Exception $e) {
    // Tangani error
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Server error: ' . $e->getMessage()
    ]);
}
?>