<?php

if (!function_exists('member_referral_generate_code')) {
    function member_referral_generate_code()
    {
        return substr(str_shuffle('abcdefghijklmnopqrstuvwxyz0123456789'), 0, 8);
    }
}

if (!function_exists('member_referral_ensure_code')) {
    function member_referral_ensure_code($conn, &$u)
    {
        if (!empty($u['referral_code'])) {
            return $u['referral_code'];
        }
        $code = member_referral_generate_code();
        $cuid = (int) $u['cuid'];
        $codeEsc = mysqli_real_escape_string($conn, $code);
        mysqli_query($conn, "UPDATE tb_user SET referral_code = '$codeEsc' WHERE cuid = $cuid");
        $u['referral_code'] = $code;
        return $code;
    }
}

if (!function_exists('member_referral_is_member')) {
    function member_referral_is_member($u)
    {
        $level = isset($u['level']) ? $u['level'] : '';
        return $level === 'user' || $level === '' || $level === false;
    }
}

if (!function_exists('member_referral_kyc_verified')) {
    function member_referral_kyc_verified($u)
    {
        return (int) ($u['status_kyc'] ?? 0) === 1;
    }
}

if (!function_exists('member_referral_kyc_pending')) {
    function member_referral_kyc_pending($conn, $fullName)
    {
        $name = mysqli_real_escape_string($conn, $fullName);
        $q = mysqli_query($conn, "SELECT id FROM tb_kyc WHERE name = '$name' LIMIT 1");
        return $q && mysqli_num_rows($q) > 0;
    }
}

if (!function_exists('member_referral_invite_url')) {
    function member_referral_invite_url($code)
    {
        if (!function_exists('site_url')) {
            include dirname(__DIR__, 2) . '/config/url_helper.php';
        }
        return site_url('m/register/?reff=' . urlencode($code));
    }
}

if (!function_exists('member_referral_format_rp')) {
    function member_referral_format_rp($amount)
    {
        return 'Rp ' . number_format((float) $amount, 0, ',', '.');
    }
}

if (!function_exists('member_referral_downline_stats')) {
    function member_referral_downline_stats($conn, $userId)
    {
        $userId = (int) $userId;
        $total = 0;
        $belumDeposit = 0;
        $pernahDeposit = 0;

        $sql = "SELECT u.cuid,
            (SELECT COUNT(*) FROM tb_transaksi t WHERE t.userID = u.cuid AND t.jenis = 1 AND t.status = 1) AS dep_count
            FROM tb_user u WHERE u.referral_user_id = '$userId'";
        $q = mysqli_query($conn, $sql);
        if ($q) {
            while ($row = mysqli_fetch_assoc($q)) {
                $total++;
                if ((int) $row['dep_count'] === 0) {
                    $belumDeposit++;
                } else {
                    $pernahDeposit++;
                }
            }
        }

        return [
            'total' => $total,
            'belum_deposit' => $belumDeposit,
            'pernah_deposit' => $pernahDeposit,
        ];
    }
}

if (!function_exists('member_referral_fetch_downline')) {
    function member_referral_fetch_downline($conn, $userId)
    {
        $userId = (int) $userId;
        $list = [];
        $sql = "SELECT u.cuid, u.username, u.full_name, u.join_date, u.status_kyc,
            IFNULL(SUM(CASE WHEN t.jenis = 1 AND t.status = 1 THEN t.total ELSE 0 END), 0) AS total_deposit,
            MIN(CASE WHEN t.jenis = 1 AND t.status = 1 THEN t.date END) AS first_dep,
            MAX(CASE WHEN t.status = 1 THEN t.date END) AS last_tx
            FROM tb_user u
            LEFT JOIN tb_transaksi t ON t.userID = u.cuid
            WHERE u.referral_user_id = '$userId'
            GROUP BY u.cuid
            ORDER BY u.join_date DESC";
        $q = mysqli_query($conn, $sql);
        if ($q) {
            while ($row = mysqli_fetch_assoc($q)) {
                $list[] = $row;
            }
        }
        return $list;
    }
}

if (!function_exists('member_referral_prepare')) {
    function member_referral_prepare($conn, $u)
    {
        member_referral_ensure_code($conn, $u);
        $kycVerified = member_referral_kyc_verified($u);
        $kycPending = !$kycVerified && member_referral_kyc_pending($conn, $u['full_name'] ?? '');
        $canShare = $kycVerified && member_referral_is_member($u);

        return [
            'code' => $u['referral_code'],
            'invite_url' => member_referral_invite_url($u['referral_code']),
            'kyc_verified' => $kycVerified,
            'kyc_pending' => $kycPending,
            'can_share' => $canShare,
            'is_member' => member_referral_is_member($u),
            'stats' => member_referral_downline_stats($conn, $u['cuid']),
            'downline' => member_referral_fetch_downline($conn, $u['cuid']),
        ];
    }
}
