<?php
// promotorBK/ajax/update_bk_pay.php
session_start();
header('Content-Type: application/json');

// Pastikan user sudah terotentikasi DAN memiliki level admin
if (!isset($_SESSION['promotor_authenticated']) || $_SESSION['promotor_authenticated'] !== true || $_SESSION['user_level'] !== 'admin') {
    echo json_encode(['status' => 'error', 'message' => 'Akses ditolak. Hanya Admin yang dapat melakukan update.']);
    exit;
}

include '../../config/koneksi.php'; 

$response = ['status' => 'error', 'message' => 'Permintaan tidak valid.'];

if (isset($_POST['trans_id']) && is_numeric($_POST['trans_id']) && isset($_POST['new_status']) && is_numeric($_POST['new_status'])) {
    
    $trans_id = (int)$_POST['trans_id'];
    $new_status = (int)$_POST['new_status'];
    
    if ($new_status !== 0 && $new_status !== 1) {
         $response['message'] = 'Status tidak valid.';
         echo json_encode($response);
         mysqli_close($conn);
         exit;
    }

    $stmt = $conn->prepare("UPDATE tb_transaksi SET bk_pay = ? WHERE cuid = ?");
    $stmt->bind_param("ii", $new_status, $trans_id);

    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            $response['status'] = 'success';
            $response['message'] = 'Status Payout berhasil diperbarui.';
            $response['new_status_code'] = $new_status; // Kirim status baru untuk update UI
        } else {
            $response['message'] = 'Gagal memperbarui status. ID transaksi tidak ditemukan atau status sudah sama.';
        }
    } else {
        $response['message'] = 'Kesalahan database saat eksekusi.';
    }

    $stmt->close();
}

mysqli_close($conn);
echo json_encode($response);