<?php
// Commission helper — applies commission based on user's package
//
// For topup/intl:   commission = recharge_amount × rate%
// For drive:        commission = cashback_amount × rate%   (cashback_amount = API commission from ECARE/ST)
// For card/pin:     commission = card's own commission × rate%

function applyCommission($db, $userId, $txnType, $amount, $reference, $baseAmount = null) {
    try {
        // Get user's package
        $stmt = $db->prepare("
            SELECT p.* FROM users u 
            LEFT JOIN user_packages p ON COALESCE(u.package_id,1)=p.id 
            WHERE u.id=?
        ");
        $stmt->execute([$userId]);
        $pkg = $stmt->fetch();

        if (!$pkg) {
            $pkg = $db->query("SELECT * FROM user_packages WHERE is_default=1 OR id=1 LIMIT 1")->fetch();
        }
        if (!$pkg) return 0;

        // Commission rate from package
        $rateMap = [
            'topup'         => floatval($pkg['topup_commission'] ?? 0),
            'international' => floatval($pkg['intl_commission']  ?? 0),
            'pin'           => floatval($pkg['pin_commission']   ?? 0),
            'gift'          => floatval($pkg['gift_commission']  ?? 0),
            'card'          => floatval($pkg['card_commission']  ?? 0),
            'drive'         => floatval($pkg['drive_commission'] ?? 0),
        ];

        $rate = $rateMap[$txnType] ?? 0;
        if ($rate <= 0) return 0;

        // Base amount to calculate commission from:
        // - drive/card/pin: use $baseAmount (cashback_amount or card's own commission)
        // - topup/intl: use $amount (recharge amount)
        $calcBase = ($baseAmount !== null && $baseAmount > 0) ? $baseAmount : $amount;

        $commission = round($calcBase * $rate / 100, 2);
        if ($commission <= 0) return 0;

        // Add to user balance
        $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$commission, $userId]);

        $newBal = $db->prepare("SELECT balance FROM users WHERE id=?");
        $newBal->execute([$userId]);
        $bal = $newBal->fetchColumn();

        // Record
        $ref = 'COM'.strtoupper(substr(uniqid(),7));
        $baseNote = ($baseAmount !== null && $baseAmount > 0) ? ' (base: ৳'.$baseAmount.')' : '';
        $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
           ->execute([
               $userId, 'commission', $commission, $commission,
               $bal - $commission, $bal,
               $ref, 'success',
               ucfirst($txnType).' commission ('.$rate.'%)'.$baseNote.' on Ref: '.$reference.' — Package: '.($pkg['name']??'Basic')
           ]);

        // Notification
        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
           ->execute([$userId, '💸 Commission Earned!',
               '৳'.number_format($commission,2).' '.ucfirst($txnType).' commission ('.$rate.'%) added.']);

        return $commission;

    } catch(Exception $e) {
        return 0;
    }
}
