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

if (!isset($_SESSION['promotor_authenticated']) || $_SESSION['promotor_authenticated'] !== true) {
    echo json_encode(['status' => 'error', 'message' => 'Sesi tidak valid.']);
    exit;
}

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

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

// Fungsi NDP: Cari Deposit Pertama Sukses User
function get_ndp_data($conn, $user_cuid) {
    $stmt = $conn->prepare("
        SELECT date, total, bk_pay, cuid 
        FROM tb_transaksi 
        WHERE userID = ? AND jenis = '1' AND status = '1'
        ORDER BY date ASC 
        LIMIT 1
    ");
    $stmt->bind_param("i", $user_cuid);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    return $data;
}

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

$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 Lengkap (tb_user) + Upline
    $stmt_user = $conn->prepare("
        SELECT 
            u.username, u.full_name, u.email, u.phone_number, u.join_date, u.status_kyc, u.referral_user_id,
            up.username AS upline_username, up.full_name AS upline_full_name
        FROM tb_user u
        LEFT JOIN tb_user up ON u.referral_user_id = up.cuid
        WHERE u.cuid = ?
    ");
    $stmt_user->bind_param("i", $user_id);
    $stmt_user->execute();
    $result_user = $stmt_user->get_result();
    $user = $result_user->fetch_assoc();
    $stmt_user->close();

    if (!$user) {
        $response['message'] = 'User tidak ditemukan.';
        echo json_encode($response);
        mysqli_close($conn);
        exit;
    }
    
    // 2. Ambil Detail Bank User (tb_bank)
    $stmt_bank = $conn->prepare("
        SELECT pemilik, akun, no_rek 
        FROM tb_bank 
        WHERE userID = ? AND status = 1 
        ORDER BY cuid DESC 
        LIMIT 1
    ");
    $stmt_bank->bind_param("i", $user_id);
    $stmt_bank->execute();
    $result_bank = $stmt_bank->get_result();
    $bank_data = $result_bank->fetch_assoc();
    $stmt_bank->close();
    
    $nama_rek = $bank_data ? htmlspecialchars($bank_data['pemilik']) : '<span class="text-danger">- Tidak Ditemukan -</span>';
    $jenis_rek = $bank_data ? htmlspecialchars($bank_data['akun']) : '-';
    $no_rek = $bank_data ? htmlspecialchars($bank_data['no_rek']) : '-';
    
    // 3. Ambil Data NDP
    $ndp_data = get_ndp_data($conn, $user_id);
    
    $ndp_nominal = $ndp_data ? format_rupiah($ndp_data['total']) : '<span class="text-warning">Belum NDP</span>';
    $ndp_date = $ndp_data ? date('d-m-Y H:i', strtotime($ndp_data['date'])) : '-';
    $ndp_trans_id = $ndp_data ? $ndp_data['cuid'] : 0;
    $bk_pay_status = $ndp_data ? (int)$ndp_data['bk_pay'] : 0;
    
    // Tampilkan Upline
    $upline_display = 'Tidak Ada';
    if ($user['referral_user_id'] > 0) {
        $upline_display = htmlspecialchars($user['upline_full_name'] . ' (' . $user['upline_username'] . ') ID: ' . $user['referral_user_id']);
    }
    
    // Tentukan apakah form bisa diedit
    $disabled = $is_admin_access ? '' : 'disabled';
    $input_class = $is_admin_access ? 'form-control form-control-sm bg-dark text-white' : 'form-control-plaintext text-white';

    // HTML untuk detail
    $html = '<h5 class="text-light mb-3 border-bottom border-warning pb-2">Detail Akun Member: ' . htmlspecialchars($user['full_name']) . ' (CUID: ' . $user_id . ')</h5>';
    
    // === FORM START ===
    $html .= '<form id="updateUserForm">';
    $html .= '<input type="hidden" name="cuid" value="' . $user_id . '">';
    $html .= '<div id="updateMessage" class="alert d-none small"></div>'; // Pesan feedback AJAX
    $html .= '<div class="row small">';
    
    // KOLOM KIRI: DETAIL AKUN
    $html .= '<div class="col-12 col-md-6">';
    $html .= '<table class="table table-sm table-borderless text-white">';
    $html .= '<tr><td colspan="2"><h6 class="text-info">Informasi Akun</h6></td></tr>';
    
    $html .= '<tr><td class="text-secondary">Username:</td><td>' . htmlspecialchars($user['username']) . '</td></tr>';
    $html .= '<tr><td class="text-secondary">Upline/Promotor:</td><td><span class="fw-bold text-warning">' . $upline_display . '</span></td></tr>';

    // Editable Full Name
    $html .= '<tr><td class="text-secondary">Nama Lengkap:</td><td><input type="text" name="full_name" class="' . $input_class . '" value="' . htmlspecialchars($user['full_name']) . '" ' . $disabled . '></td></tr>';
    
    // Editable Email
    $html .= '<tr><td class="text-secondary">Email:</td><td><input type="email" name="email" class="' . $input_class . '" value="' . htmlspecialchars($user['email']) . '" ' . $disabled . '></td></tr>';
    
    // Editable Phone Number
    $html .= '<tr><td class="text-secondary">Telepon:</td><td><input type="text" name="phone_number" class="' . $input_class . '" value="' . htmlspecialchars($user['phone_number']) . '" ' . $disabled . '></td></tr>';
    
    $html .= '<tr><td class="text-secondary">Tgl Gabung:</td><td>' . date('d-m-Y', strtotime($user['join_date'])) . '</td></tr>';
    $html .= '<tr><td class="text-secondary">KYC Status:</td><td>' . ($user['status_kyc'] ? '<span class="badge text-bg-success">Verified</span>' : '<span class="badge text-bg-danger">Unverified</span>') . '</td></tr>';
    $html .= '</table></div>';
    
    // KOLOM KANAN: DETAIL BANK & NDP
    $html .= '<div class="col-12 col-md-6">';
    $html .= '<table class="table table-sm table-borderless text-white">';
    
    // Sub-section Detail Bank
    $html .= '<tr><td colspan="2"><h6 class="text-info">Detail Bank Member</h6></td></tr>';
    $html .= '<tr><td class="text-secondary">Nama Rekening:</td><td><span class="fw-bold text-warning">' . $nama_rek . '</span></td></tr>';
    $html .= '<tr><td class="text-secondary">Jenis Akun:</td><td>' . $jenis_rek . '</td></tr>';
    $html .= '<tr><td class="text-secondary">Nomor Rekening:</td><td><span class="fw-bold">' . $no_rek . '</span></td></tr>';
    
    // Sub-section NDP
    $html .= '<tr><td colspan="2"><h6 class="text-info mt-3">NDP (Deposit Pertama Sukses)</h6></td></tr>';
    $html .= '<tr><td class="text-secondary">Nominal:</td><td class="fw-bold">' . $ndp_nominal . '</td></tr>';
    $html .= '<tr><td class="text-secondary">Tanggal:</td><td>' . $ndp_date . '</td></tr>';
    
    // Logika Tombol Aksi Payout (Hanya Admin)
    if ($ndp_data) {
        $payout_text = $bk_pay_status === 1 ? 'Selesai' : 'Onprogress';
        $payout_color = $bk_pay_status === 1 ? 'primary' : 'secondary';
        $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-success' : 'btn-secondary';

        $html .= '<tr><td class="text-secondary">Status Payout:</td><td><span id="status-text-' . $ndp_trans_id . '" class="badge text-bg-' . $payout_color . ' me-2">' . $payout_text . '</span></td></tr>';
        
        if ($is_admin_access) {
            $html .= '<tr><td class="text-secondary">Aksi Payout NDP:</td><td>';
            $html .= '<button type="button" data-trans-id="' . $ndp_trans_id . '" data-status="' . $next_status . '" class="btn btn-sm ' . $btn_class . ' update-payout-btn" style="font-size: 0.8rem;">' . $action_text . '</button>';
            $html .= '</td></tr>';
        }
    } else {
         $html .= '<tr><td class="text-secondary">Status Payout:</td><td>N/A</td></tr>';
    }
    
    $html .= '</table></div></div>';
    
    // Tombol Simpan Form (Hanya Admin)
    if ($is_admin_access) {
        $html .= '<div class="text-end border-top border-secondary pt-3">';
        $html .= '<button type="submit" class="btn btn-sm btn-action"><i class="fas fa-save me-1"></i> Simpan Perubahan User</button>';
        $html .= '</div>';
    }
    
    $html .= '</form>';
    // === FORM END ===
    
    $response['status'] = 'success';
    $response['html'] = $html;
}

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