<?php
header('Content-Type: application/json');
include '../connection.php';

$fname = $_POST['fname'] ?? '';
$lname = $_POST['lname'] ?? '';
$conno = $_POST['conno'] ?? '';
$email = strtolower($_POST['uemail']) ?? '';
$pass = md5($_POST['pass'] ?? '');
$otp  = $_POST['otp'] ?? '';
$is_verified = isset($_POST['is_verified']) ? intval($_POST['is_verified']) : 0;
$referral_code = $_POST['referral_code'] ?? '';

// First insert the user
$sql = "INSERT INTO tblcred (fname, lname, conno, email, pass, otp_code, is_verified)
        VALUES ('$fname', '$lname', '$conno', '$email', '$pass', '$otp', $is_verified)";

if ($conn->query($sql) === TRUE) {
    $newUserId = $conn->insert_id;
    
    // If referral code was provided, apply it
    if (!empty($referral_code)) {
        $applySql = "INSERT INTO tbl_referrals (referrer_id, referred_id, referral_code) 
                    SELECT userid, $newUserId, '$referral_code' 
                    FROM tblcred 
                    WHERE referral_code = '$referral_code'";
        $conn->query($applySql);
    }
    
    // Generate a referral code for the new user
    $userReferralCode = generateRandomString(8);
    $updateSql = "UPDATE tblcred SET referral_code = '$userReferralCode' WHERE userid = $newUserId";
    $conn->query($updateSql);
    
    // Initialize rewards account
    $rewardSql = "INSERT INTO tbl_referral_rewards (user_id) VALUES ($newUserId)";
    $conn->query($rewardSql);
    
    echo json_encode(array("success" => true));
} else {
    echo json_encode(array("success" => false, "error" => $conn->error));
}

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