/** * Distributes referral commission up to 5 levels. * * @param PDO $pdo The database connection object. * @param int $newUserId The ID of the user who made the purchase. * @param float $packageBasePrice The base price of the package (before GST). */ function distributeReferralCommission($pdo, $newUserId, $packageBasePrice) { // --- Purchaser Details --- $stmtNewUser = $pdo->prepare("SELECT name FROM users WHERE id = ?"); $stmtNewUser->execute([$newUserId]); $newUserName = $stmtNewUser->fetchColumn(); $purchaserIdentifier = htmlspecialchars($newUserName ?: "User #{$newUserId}"); // --- Direct Referrer --- $stmtRef = $pdo->prepare("SELECT referrer_id FROM users WHERE id = ?"); $stmtRef->execute([$newUserId]); $directReferrer = $stmtRef->fetchColumn(); if (!$directReferrer) { return; // कोई referrer नहीं है } // --- Check Direct Referrer Role (employee / user) --- $stmtRole = $pdo->prepare("SELECT role FROM users WHERE id = ?"); $stmtRole->execute([$directReferrer]); $directRole = $stmtRole->fetchColumn(); // --- Commission Settings Fetch --- $stmtSettings = $pdo->query(" SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'referral_level_%_commission' OR setting_key LIKE 'employee_referral_level_%_commission' "); $commissions_config = $stmtSettings->fetchAll(PDO::FETCH_KEY_PAIR); // --- Referral Chain (max 5 levels) --- $allReferrers = []; $currentUserId = $newUserId; for ($i = 0; $i < 5; $i++) { $stmt = $pdo->prepare("SELECT referrer_id, role FROM users WHERE id = ?"); $stmt->execute([$currentUserId]); $ref = $stmt->fetch(PDO::FETCH_ASSOC); if ($ref && $ref['referrer_id'] !== null) { $allReferrers[] = [ 'id' => $ref['referrer_id'], 'role' => $ref['role'] ]; $currentUserId = $ref['referrer_id']; } else { break; } } // --- Commission Distribute --- $level = 1; foreach ($allReferrers as $ref) { if ($directRole === 'employee') { // अगर पहला referrer employee है → पूरी chain employee rates पे $commission_key = 'employee_referral_level_' . $level . '_commission'; } else { // Normal user → normal rates $commission_key = 'referral_level_' . $level . '_commission'; } if (!isset($commissions_config[$commission_key])) { break; } $commissionRate = (float)$commissions_config[$commission_key]; $commissionAmount = ($packageBasePrice * $commissionRate) / 100; if ($commissionAmount > 0) { // Wallet update $updateStmt = $pdo->prepare("UPDATE users SET wallet_balance = wallet_balance + ? WHERE id = ?"); $updateStmt->execute([$commissionAmount, $ref['id']]); // Log transaction $logStmt = $pdo->prepare( "INSERT INTO wallet_transactions (user_id, amount, type, description) VALUES (?, ?, 'credit', ?)" ); $description = ucfirst($directRole) . " Level {$level} referral commission from " . $purchaserIdentifier; $logStmt->execute([$ref['id'], $commissionAmount, $description]); } $level++; } } Register - Stars Flock Content Creator
← Back to Home

Create Your Account

Join our flock of stars network.

Already have an account? Log in