<?php
// referral_functions.php

class ReferralSystem {
    private $conn;
    
    public function __construct($connection) {
        $this->conn = $connection;
    }
    
    // Generate unique referral code
    public function generateReferralCode($user_id) {
        $code = strtoupper(substr(md5($user_id . time()), 0, 8));
        
        // Check if code exists
        $check_sql = "SELECT id FROM users WHERE referral_code = '$code'";
        $result = mysqli_query($this->conn, $check_sql);
        
        if (mysqli_num_rows($result) > 0) {
            return $this->generateReferralCode($user_id); // Recursive if duplicate
        }
        
        return $code;
    }
    
    // Process referral when new user signs up
    public function processReferralSignup($referred_user_id, $referral_code) {
        // Get referrer user
        $sql = "SELECT id, referral_balance, total_referrals FROM users WHERE referral_code = '$referral_code'";
        $result = mysqli_query($this->conn, $sql);
        
        if (mysqli_num_rows($result) > 0) {
            $referrer = mysqli_fetch_assoc($result);
            $referrer_id = $referrer['id'];
            
            // Get referral settings
            $settings = $this->getReferralSettings();
            
            // Update referred user with referrer info and give signup bonus
            $update_referred_sql = "UPDATE users SET referred_by = '$referrer_id', referral_balance = referral_balance + {$settings['signup_bonus_referred']} WHERE id = '$referred_user_id'";
            mysqli_query($this->conn, $update_referred_sql);
            
            // Update referrer with bonus and increment referral count
            $update_referrer_sql = "UPDATE users SET 
                referral_balance = referral_balance + {$settings['signup_bonus_referrer']},
                total_referrals = total_referrals + 1,
                referral_interest_discount = LEAST(referral_interest_discount + {$settings['discount_per_referral']}, {$settings['max_referral_discount']})
                WHERE id = '$referrer_id'";
            mysqli_query($this->conn, $update_referrer_sql);
            
            // Record transactions
            $this->recordTransaction($referrer_id, $referred_user_id, 'signup_bonus', $settings['signup_bonus_referrer'], "Referral signup bonus for {$settings['signup_bonus_referred']}");
            $this->recordTransaction($referred_user_id, $referred_user_id, 'signup_bonus', $settings['signup_bonus_referred'], "Welcome bonus for using referral code");
            
            return true;
        }
        
        return false;
    }
    
    // Process bonus when referred user gets loan approved
    public function processLoanApprovalBonus($user_id) {
        $sql = "SELECT referred_by FROM users WHERE id = '$user_id' AND referred_by IS NOT NULL";
        $result = mysqli_query($this->conn, $sql);
        
        if (mysqli_num_rows($result) > 0) {
            $user = mysqli_fetch_assoc($result);
            $referrer_id = $user['referred_by'];
            
            $settings = $this->getReferralSettings();
            
            // Give loan approval bonus to referrer
            $update_sql = "UPDATE users SET referral_balance = referral_balance + {$settings['loan_approval_bonus']} WHERE id = '$referrer_id'";
            mysqli_query($this->conn, $update_sql);
            
            // Record transaction
            $this->recordTransaction($referrer_id, $user_id, 'loan_approval_bonus', $settings['loan_approval_bonus'], "Loan approval bonus for referred user");
            
            return true;
        }
        
        return false;
    }
    
    // Get user's referral discount for loan calculation
    public function getUserReferralDiscount($user_id) {
        $sql = "SELECT referral_interest_discount FROM users WHERE id = '$user_id'";
        $result = mysqli_query($this->conn, $sql);
        
        if (mysqli_num_rows($result) > 0) {
            $user = mysqli_fetch_assoc($result);
            return $user['referral_interest_discount'];
        }
        
        return 0;
    }
    
    // Get referral statistics for user
    public function getUserReferralStats($user_id) {
        $sql = "SELECT 
                u.referral_code,
                u.referral_balance,
                u.total_referrals,
                u.referral_interest_discount,
                COUNT(rt.id) as successful_referrals,
                COALESCE(SUM(CASE WHEN rt.transaction_type = 'loan_approval_bonus' THEN rt.amount ELSE 0 END), 0) as total_loan_bonus
                FROM users u
                LEFT JOIN referral_transactions rt ON u.id = rt.referrer_id
                WHERE u.id = '$user_id'";
        
        $result = mysqli_query($this->conn, $sql);
        return mysqli_fetch_assoc($result);
    }
    
    // Get referral history
    public function getReferralHistory($user_id) {
        $sql = "SELECT 
                rt.*,
                u.username as referred_username,
                u.email as referred_email
                FROM referral_transactions rt
                JOIN users u ON rt.referred_id = u.id
                WHERE rt.referrer_id = '$user_id'
                ORDER BY rt.created_at DESC
                LIMIT 10";
        
        $result = mysqli_query($this->conn, $sql);
        $history = [];
        
        while ($row = mysqli_fetch_assoc($result)) {
            $history[] = $row;
        }
        
        return $history;
    }
    
    public function getReferralSettings() {
        $sql = "SELECT * FROM referral_settings WHERE is_active = 1 ORDER BY id DESC LIMIT 1";
        $result = mysqli_query($this->conn, $sql);
        
        if (mysqli_num_rows($result) > 0) {
            return mysqli_fetch_assoc($result);
        }
        
        // Return default settings if none found
        return [
            'signup_bonus_referrer' => 100.00,
            'signup_bonus_referred' => 50.00,
            'loan_approval_bonus' => 200.00,
            'max_referral_discount' => 1.00,
            'discount_per_referral' => 0.10
        ];
    }
    
    public function recordTransaction($referrer_id, $referred_id, $type, $amount, $description) {
        $sql = "INSERT INTO referral_transactions (referrer_id, referred_id, transaction_type, amount, description) 
                VALUES ('$referrer_id', '$referred_id', '$type', '$amount', '$description')";
        return mysqli_query($this->conn, $sql);
    }
}
?>