<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
include '../connection.php';

$action = $_POST['action'] ?? '';
$response = [];

switch ($action) {
    case 'generate_code':
        $userId = intval($_POST['user_id'] ?? 0);
        $response = generateReferralCode($conn, $userId);
        break;
        
    case 'add_referral_info':
        $userId = intval($_POST['user_id'] ?? 0);
        $response = addReferralReward($conn, $userId);
        break;
        
    case 'get_referral_info':
        $userId = intval($_POST['user_id'] ?? 0);
        $response = getReferralInfo($conn, $userId);
        break;
        
    case 'apply_referral':
        $referralCode = $_POST['referral_code'] ?? '';
        $newUserId = intval($_POST['new_user_id'] ?? 0);
        $response = applyReferralCode($conn, $referralCode, $newUserId);
        break;
        
    case 'get_rewards':
        $userId = intval($_POST['user_id'] ?? 0);
        $response = getRewardInfo($conn, $userId);
        break;
        
    default:
        $response = ['success' => false, 'message' => 'Invalid action'];
}

echo json_encode($response);

function generateReferralCode($conn, $userId) {
    // Check if user already has a referral code
    $checkSql = "SELECT referral_code FROM tblcred WHERE userid = ?";
    $stmt = $conn->prepare($checkSql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        if (!empty($row['referral_code'])) {
            return ['success' => true, 'referral_code' => $row['referral_code']];
        }
    }
    
    // Generate a new unique referral code
    $code = generateRandomString(8);
    
    // Update user record with the new referral code
    $updateSql = "UPDATE tblcred SET referral_code = ? WHERE userid = ?";
    $stmt = $conn->prepare($updateSql);
    $stmt->bind_param("si", $code, $userId);
    
    if ($stmt->execute()) {
        // Initialize rewards account if not exists
        initializeRewardsAccount($conn, $userId);
        return ['success' => true, 'referral_code' => $code];
    } else {
        return ['success' => false, 'message' => 'Failed to generate referral code'];
    }
}



function getReferralInfo($conn, $userId) {
    // Get user's referral code
    $codeSql = "SELECT referral_code FROM tblcred WHERE userid = ?";
    $stmt = $conn->prepare($codeSql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        return ['success' => false, 'message' => 'User not found'];
    }
    
    $row = $result->fetch_assoc();
    $referralCode = $row['referral_code'] ?? '';
    
    // If no referral code exists, generate one
    if (empty($referralCode)) {
        $generated = generateReferralCode($conn, $userId);
        if ($generated['success']) {
            $referralCode = $generated['referral_code'];
        } else {
            return ['success' => false, 'message' => 'Failed to generate referral code'];
        }
    }

    //Ensure rewards account is initialized
    initializeRewardsAccount($conn, $userId);

    // Count number of referrals
    $countSql = "SELECT COUNT(*) as referral_count 
                 FROM tbl_referrals 
                 WHERE referrer_id = ? AND is_used = 1";
    $stmt = $conn->prepare($countSql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $countResult = $stmt->get_result();
    $countRow = $countResult->fetch_assoc();
    $referralCount = $countRow['referral_count'] ?? 0;

    //Fetch updated rewards
    $rewardsSql = "SELECT total_earned, available_balance 
                   FROM tbl_referral_rewards 
                   WHERE user_id = ?";
    $stmt = $conn->prepare($rewardsSql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $rewardsResult = $stmt->get_result();
    $rewardsRow = $rewardsResult->fetch_assoc();

    return [
        'success' => true,
        'referral_code' => $referralCode,
        'referral_count' => $referralCount,
        'total_earned' => $rewardsRow['total_earned'] ?? 0,
        'available_balance' => $rewardsRow['available_balance'] ?? 0,
        'referral_link' => "https://www.cloudsoftonline.com/api_wavoo_rest/user/signup?ref=$referralCode"
    ];
}

function applyReferralCode($conn, $referralCode, $newUserId) {
    // Find the referrer
    $findSql = "SELECT userid FROM tblcred WHERE referral_code = ?";
    $stmt = $conn->prepare($findSql);
    $stmt->bind_param("s", $referralCode);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        return ['success' => false, 'message' => 'Invalid referral code'];
    }
    
    $row = $result->fetch_assoc();
    $referrerId = $row['userid'];
    
    // Record the referral
    $insertSql = "INSERT INTO tbl_referrals (referrer_id, referred_id, referral_code) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($insertSql);
    $stmt->bind_param("iis", $referrerId, $newUserId, $referralCode);
    
    if ($stmt->execute()) {
        return ['success' => true, 'message' => 'Referral applied successfully'];
    } else {
        return ['success' => false, 'message' => 'Failed to apply referral'];
    }
}

function getRewardInfo($conn, $userId) {
    $sql = "SELECT * FROM tbl_referral_rewards WHERE user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        return ['success' => false, 'message' => 'No rewards account found'];
    }
    
    $row = $result->fetch_assoc();
    
    // Get referral history
    $historySql = "SELECT r.*, u.fname, u.lname 
                  FROM tbl_referrals r 
                  JOIN tblcred u ON r.referred_id = u.userid 
                  WHERE r.referrer_id = ? 
                  ORDER BY r.referral_date DESC";
    $stmt = $conn->prepare($historySql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $historyResult = $stmt->get_result();
    $history = [];
    
    while ($historyRow = $historyResult->fetch_assoc()) {
        $history[] = $historyRow;
    }
    
    return [
        'success' => true,
        'total_earned' => $row['total_earned'],
        'available_balance' => $row['available_balance'],
        'withdrawn_balance' => $row['withdrawn_balance'],
        'referral_history' => $history
    ];
}

function initializeRewardsAccount($conn, $userId) {
    // Check if already exists
    $checkSql = "SELECT id FROM tbl_referral_rewards WHERE user_id = ?";
    $stmt = $conn->prepare($checkSql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        $insertSql = "INSERT INTO tbl_referral_rewards (user_id) VALUES (?)";
        $stmt = $conn->prepare($insertSql);
        $stmt->bind_param("i", $userId);
        $stmt->execute();
    }
}

function generateRandomString($length = 8) {
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    
    return $randomString;
}

// Function to add reward when referred user makes a purchase


function addReferralReward($conn, $userId) {
    // find all referrals where this user is referrer and not rewarded yet
    $referralSql = "SELECT id, referred_id, referrer_id 
                    FROM tbl_referrals 
                    WHERE referrer_id = ?";
    $stmt = $conn->prepare($referralSql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $referrerId = $row['referrer_id'];
            $referredId = $row['referred_id'];

            // check completed orders of this referred user
            $sqlORDERCHK = "SELECT SUM(total_amount) as ttl_amount 
                            FROM tbl_order 
                            WHERE user_id = ? AND status = 'Submitted' AND referral_status = 0";
            $rORDERCHK = $conn->prepare($sqlORDERCHK);
            $rORDERCHK->bind_param("i", $referredId);
            $rORDERCHK->execute();
            $resORDERCHK = $rORDERCHK->get_result();
            $orderAmount = 0;
            if ($resORDERCHK->num_rows > 0) {
                $rowORDERCHK = $resORDERCHK->fetch_assoc();
                $orderAmount = $rowORDERCHK['ttl_amount'] ?? 0;
            }

            if ($orderAmount > 0) {
                $rewardAmount = $orderAmount * 0.05;

                // mark referral as rewarded
                $updateSql = "UPDATE tbl_referrals 
                              SET is_used = 1, reward_earned = ? 
                              WHERE referred_id = ?";
                $stmt2 = $conn->prepare($updateSql);
                $stmt2->bind_param("di", $rewardAmount, $referredId);
                $stmt2->execute();

                // update reward balance
                $rewardSql = "UPDATE tbl_referral_rewards 
                              SET total_earned = total_earned + ?, 
                                  available_balance = available_balance + ? 
                              WHERE user_id = ?";
                $stmt3 = $conn->prepare($rewardSql);
                $stmt3->bind_param("ddi", $rewardAmount, $rewardAmount, $referrerId);
                $stmt3->execute();
                
                // update referral_status in order table
                $sqlUPDT = "update tbl_order set referral_status = 1 where user_id = ?";
                $stmt4 = $conn->prepare($sqlUPDT);
                $stmt4->bind_param("i", $referredId);
                $stmt4->execute();
            }
            
        }
        
        return ['success'=>true,'message'=>'Referral rewards updated'];
    }
    return ['success'=>false,'message'=>'No pending referrals'];
}

?>