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

if (!isset($_SESSION['promotor_authenticated']) || $_SESSION['promotor_authenticated'] !== true) {
    echo json_encode(['status' => 'error', 'html' => '<div class="alert alert-danger">Sesi tidak valid.</div>']);
    exit;
}

$is_admin_access = (isset($_SESSION['user_level']) && $_SESSION['user_level'] === 'admin');

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

// Fungsi helper
function format_rupiah($nominal) {
    return 'Rp ' . number_format($nominal, 0, ',', '.');
}

function translateJenis($code) {
    $map = ['1' => 'Deposit', '2' => 'Withdraw', '3' => 'Refferal', '4' => 'Rabate', '5' => 'Transfer', '6' => 'TransferBack', '7' => 'Promosi'];
    return $map[$code] ?? $code;
}

function translateStatus($code) {
    $map = [0 => 'Pending', 1 => 'Sukses', 2 => 'Batal/Gagal'];
    return $map[$code] ?? $code;
}

// Fungsi Payout yang diperbarui untuk tombol
function get_payout_action_content($trans_id, $bk_pay_status, $is_admin) {
    $payout_text = $bk_pay_status === 1 ? 'Selesai' : 'Onprogress';
    $payout_color = $bk_pay_status === 1 ? 'primary' : 'secondary';

    $html = '<span id="status-text-trans-' . $trans_id . '" class="badge text-bg-' . $payout_color . ' me-2">' . $payout_text . '</span>';
    
    if ($is_admin) {
        $next_status = $bk_pay_status === 1 ? 0 : 1;
        $action_text = $bk_pay_status === 1 ? 'Set Onprogress' : 'Set Selesai';
        $btn_class = $bk_pay_status === 1 ? 'btn-danger' : 'btn-success'; // Warna tombol dibedakan

        $html .= '<button data-trans-id="' . $trans_id . '" data-status="' . $next_status . '" class="btn btn-xs ' . $btn_class . ' update-payout-btn-all" style="font-size: 0.7rem;">' . $action_text . '</button>';
    }
    return $html;
}


$response = ['status' => 'error', 'message' => 'Invalid request.', 'html' => ''];

if (isset($_POST['user_id']) && is_numeric($_POST['user_id'])) {
    $user_id = (int)$_POST['user_id'];
    
    // 1. Ambil Data User (untuk judul)
    $stmt_user = $conn->prepare("SELECT full_name, username FROM tb_user WHERE cuid = ?");
    $stmt_user->bind_param("i", $user_id);
    $stmt_user->execute();
    $user = $stmt_user->get_result()->fetch_assoc();
    $stmt_user->close();
    
    if (!$user) {
        $response['message'] = 'User tidak ditemukan.';
        echo json_encode($response);
        mysqli_close($conn);
        exit;
    }

    // 2. Ambil Transaksi
    $stmt_trans = $conn->prepare("
        SELECT cuid, kd_transaksi, date, transaksi, total, jenis, status, bk_pay 
        FROM tb_transaksi 
        WHERE userID = ?
        ORDER BY date DESC
    ");
    $stmt_trans->bind_param("i", $user_id);
    $stmt_trans->execute();
    $result_trans = $stmt_trans->get_result();
    $total_trans = mysqli_num_rows($result_trans);
    $stmt_trans->close();

    $html = '<h5 class="text-light mb-4 border-bottom border-primary pb-2">Semua Transaksi: ' . htmlspecialchars($user['full_name']) . '</h5>';

    if ($total_trans > 0) {
        $html .= '<div class="alert alert-primary text-center fw-bold small py-2">Total ' . $total_trans . ' transaksi ditemukan.</div>';
        $html .= '<div class="table-responsive">';
        
        // Tambahkan ID unik untuk Datatables
        $html .= '<table id="transactionTableAll" class="table table-dark table-striped table-hover table-bordered border-primary align-middle small w-100">';
        $html .= '<thead class="table-primary">';
        // Tambahkan header Payout/Aksi
        $header_payout = $is_admin_access ? 'Status Payout | Aksi' : 'Status Payout';
        $html .= '<tr><th>Kode Transaksi</th><th>Tanggal</th><th>Jenis</th><th>Nominal</th><th>Status Transaksi</th><th>' . $header_payout . '</th></tr>';
        $html .= '</thead><tbody>';
        
        while($row = mysqli_fetch_assoc($result_trans)) {
            $date_formatted = date('d/m/Y H:i', strtotime($row['date']));
            $jenis_text = translateJenis($row['jenis']);
            $status_text = translateStatus($row['status']);
            $total_formatted = format_rupiah($row['total']);
            
            // Dapatkan konten Payout & Tombol
            $payout_content = get_payout_action_content($row['cuid'], (int)$row['bk_pay'], $is_admin_access);
            
            $html .= '<tr id="trans-row-all-' . $row['cuid'] . '">';
            $html .= '<td>' . htmlspecialchars($row['kd_transaksi']) . '</td>';
            $html .= '<td>' . $date_formatted . '</td>';
            $html .= '<td>' . $jenis_text . '</td>';
            $html .= '<td class="fw-bold text-success">' . $total_formatted . '</td>';
            $html .= '<td>' . $status_text . '</td>';
            $html .= '<td id="payout-cell-all-' . $row['cuid'] . '">' . $payout_content . '</td>'; // Cell ID
            $html .= '</tr>';
        }
        
        $html .= '</tbody></table></div>';
    } else {
        $html .= '<div class="alert alert-warning text-center">Tidak ada transaksi ditemukan.</div>';
    }

    $response['status'] = 'success';
    $response['html'] = $html;
}

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