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

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.'];

// Mengambil member_cuid dan promotor_cuid
if (isset($_POST['member_cuid']) && is_numeric($_POST['member_cuid']) && isset($_POST['promotor_cuid']) && is_numeric($_POST['promotor_cuid']) && isset($_SESSION['user_id'])) {
    
    $member_cuid = (int)$_POST['member_cuid'];
    $promotor_cuid = (int)$_POST['promotor_cuid'];
    $admin_cuid = (int)$_SESSION['user_id']; 

    // 1. Verifikasi Member (harus tanpa referral_user_id)
    $stmt_member = $conn->prepare("SELECT username FROM tb_user WHERE cuid = ? AND (referral_user_id IS NULL OR referral_user_id = 0)");
    $stmt_member->bind_param("i", $member_cuid);
    $stmt_member->execute();
    $member_result = $stmt_member->get_result();
    $member = $member_result->fetch_assoc();
    $stmt_member->close();

    if (!$member) {
        $response['message'] = 'Member tidak ditemukan atau sudah memiliki referral.';
        echo json_encode($response);
        mysqli_close($conn);
        exit;
    }
    
    $username = $member['username'];

    // 2. Lakukan Penautan dan Update Referral Count Promotor
    $conn->begin_transaction();
    
    // Tautkan Member
    $update_user = $conn->prepare("UPDATE tb_user SET referral_user_id = ?, referral_linked_by_admin = ? WHERE cuid = ?");
    $update_user->bind_param("iii", $promotor_cuid, $admin_cuid, $member_cuid);
    
    // Update Referral Count Promotor
    $update_promotor_count = $conn->prepare("UPDATE tb_user SET referral_count = referral_count + 1 WHERE cuid = ?");
    $update_promotor_count->bind_param("i", $promotor_cuid);
    
    if (!$update_user->execute() || !$update_promotor_count->execute()) {
        $conn->rollback();
        $response['message'] = 'Gagal menautkan member atau memperbarui hitungan promotor: ' . $conn->error;
        echo json_encode($response);
        mysqli_close($conn);
        exit;
    }

    $conn->commit();

    $response['status'] = 'success';
    $response['message'] = 'Member ' . htmlspecialchars($username) . ' berhasil ditautkan.';

} else {
    $response['message'] = 'Data input tidak lengkap atau Anda bukan Admin.';
}

echo json_encode($response);
?>