<?php
// DB connection
$host = 'localhost';
$db   = 'crypto36_crypto36';
$user = 'crypto36_crypto36';
$pass = 'crypto36_crypto36';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}


function generateReferralTrxId() {
    $prefix = 'REF';
    $randomDigits = str_pad(mt_rand(0, 9999999), 7, '0', STR_PAD_LEFT);
    return $prefix . $randomDigits;
}

// Example usage:
$trxId = generateReferralTrxId();
echo $trxId; // e.g., REF1234567



// Input values
$depositUserId   = 91;              // User who deposited
$depositAmount   = 100;             // Deposit amount
$trxId           = generateReferralTrxId();  // Transaction ID from deposit
$commissionRate  = 5;               // 5% referral commission

// 1. Get depositor
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$depositUserId]);
$user = $stmt->fetch();

if (!$user) {
    die("Depositing user not found.");
}

// 2. Get referrer
$referrerId = $user['ref_by'];
if (!$referrerId) {
    die("No referrer found.");
}

$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$referrerId]);
$referrer = $stmt->fetch();

if (!$referrer) {
    die("Referrer not found.");
}

// 3. Calculate commission
$commissionAmount = ($depositAmount * $commissionRate) / 100;
$newInterestWallet = $referrer['interest_wallet'] + $commissionAmount;

// 4. Update referrer's interest wallet
$stmt = $pdo->prepare("UPDATE users SET interest_wallet = ? WHERE id = ?");
$stmt->execute([$newInterestWallet, $referrerId]);

// 5. Log the transaction in `transactions` table
$stmt = $pdo->prepare("
    INSERT INTO transactions (
        user_id, amount, post_balance, charge, trx_type, details, trx, wallet_type, remark, created_at
    ) VALUES (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()
    )
");

$stmt->execute([
    $referrerId,
    $commissionAmount,
    $newInterestWallet,
    0, // no charge
    '+',
    'Referral commission from user ID ' . $depositUserId,
    $trxId,
    'interest_wallet',
    'referral_commission'
]);

echo "✅ Commission of $commissionAmount added to referrer (User ID $referrerId) in interest wallet.";
