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

// Memastikan hanya Admin yang dapat mengakses skrip ini
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 penghapusan.']);
    exit;
}

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

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

if (isset($_POST['member_cuid']) && is_numeric($_POST['member_cuid']) && isset($_POST['promotor_cuid']) && is_numeric($_POST['promotor_cuid'])) {
    
    $member_cuid = (int)$_POST['member_cuid'];
    $promotor_cuid = (int)$_POST['promotor_cuid']; // ID Promotor lama (untuk mengurangi referral_count)

    // Memulai transaksi database
    $conn->begin_transaction();
    
    // 1. Hapus tautan referral dari member (Set referral_user_id dan referral_linked_by_admin ke NULL/0)
    $update_member = $conn->prepare("UPDATE tb_user SET referral_user_id = 0, referral_linked_by_admin = NULL WHERE cuid = ? AND referral_user_id = ?");
    $update_member->bind_param("ii", $member_cuid, $promotor_cuid);
    
    if (!$update_member->execute()) {
        $conn->rollback();
        $response['message'] = 'Gagal menghapus tautan member: ' . $conn->error;
        echo json_encode($response);
        mysqli_close($conn);
        exit;
    }
    
    // 2. Kurangi hitungan referral (referral_count) dari promotor lama
    if ($update_member->affected_rows > 0) {
        $update_promotor_count = $conn->prepare("UPDATE tb_user SET referral_count = referral_count - 1 WHERE cuid = ? AND referral_count > 0");
        $update_promotor_count->bind_param("i", $promotor_cuid);

        if (!$update_promotor_count->execute()) {
            $conn->rollback();
            $response['message'] = 'Gagal memperbarui hitungan promotor: ' . $conn->error;
            echo json_encode($response);
            mysqli_close($conn);
            exit;
        }
    }

    $conn->commit();

    $response['status'] = 'success';
    $response['message'] = 'Rujukan berhasil dihapus. Member sekarang tanpa Upline.';

} else {
    $response['message'] = 'Data penghapusan tidak lengkap.';
}

echo json_encode($response);
?>