<?php
/**
 * Kode referral terkunci saat calon member buka link ?reff=...
 * Berlaku untuk link promotor maupun member (sama: referral_code di tb_user).
 */

if (!defined('REFERRAL_LOCK_COOKIE')) {
    define('REFERRAL_LOCK_COOKIE', 'locked_reff');
    define('REFERRAL_LOCK_TTL', 2592000); // 30 hari
}

if (!function_exists('referral_lock_sanitize')) {
    function referral_lock_sanitize($code)
    {
        $code = trim((string) $code);
        $code = preg_replace('/[^a-zA-Z0-9_-]/', '', $code);
        return substr($code, 0, 50);
    }
}

if (!function_exists('referral_lock_validate')) {
    function referral_lock_validate($conn, $code)
    {
        $code = referral_lock_sanitize($code);
        if ($code === '') {
            return false;
        }
        $esc = mysqli_real_escape_string($conn, $code);
        $q = mysqli_query($conn, "SELECT cuid, username, full_name, level FROM tb_user WHERE referral_code = '$esc' AND status = 1 LIMIT 1");
        return ($q && mysqli_num_rows($q) > 0) ? mysqli_fetch_assoc($q) : false;
    }
}

if (!function_exists('referral_lock_set')) {
    function referral_lock_set($conn, $code)
    {
        $upline = referral_lock_validate($conn, $code);
        if (!$upline) {
            return false;
        }
        $code = referral_lock_sanitize($code);
        $_SESSION['locked_reff'] = $code;
        $_SESSION['locked_reff_upline'] = (int) $upline['cuid'];
        $_SESSION['locked_reff_name'] = $upline['full_name'] ?: $upline['username'];

        $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
        setcookie(REFERRAL_LOCK_COOKIE, $code, time() + REFERRAL_LOCK_TTL, '/', '', $secure, true);

        return true;
    }
}

if (!function_exists('referral_lock_init')) {
    /**
     * Panggil setelah session_start() + $conn tersedia.
     * - URL ?reff= valid → simpan / timpa lock
     * - Tanpa URL → pulihkan dari session/cookie
     */
    function referral_lock_init($conn)
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            return;
        }

        if (!empty($_GET['reff'])) {
            referral_lock_set($conn, $_GET['reff']);
            return;
        }

        if (!empty($_SESSION['locked_reff'])) {
            return;
        }

        if (!empty($_COOKIE[REFERRAL_LOCK_COOKIE])) {
            $fromCookie = referral_lock_sanitize($_COOKIE[REFERRAL_LOCK_COOKIE]);
            if ($fromCookie) {
                referral_lock_set($conn, $fromCookie);
            }
        }
    }
}

if (!function_exists('referral_lock_get')) {
    function referral_lock_get()
    {
        if (!empty($_SESSION['locked_reff'])) {
            return referral_lock_sanitize($_SESSION['locked_reff']);
        }
        if (!empty($_COOKIE[REFERRAL_LOCK_COOKIE])) {
            return referral_lock_sanitize($_COOKIE[REFERRAL_LOCK_COOKIE]);
        }
        return '';
    }
}

if (!function_exists('referral_lock_is_active')) {
    function referral_lock_is_active()
    {
        return referral_lock_get() !== '';
    }
}

if (!function_exists('referral_lock_get_upline_name')) {
    function referral_lock_get_upline_name()
    {
        return $_SESSION['locked_reff_name'] ?? '';
    }
}

if (!function_exists('referral_lock_clear')) {
    function referral_lock_clear()
    {
        unset($_SESSION['locked_reff'], $_SESSION['locked_reff_upline'], $_SESSION['locked_reff_name']);
        $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
        setcookie(REFERRAL_LOCK_COOKIE, '', time() - 3600, '/', '', $secure, true);
    }
}
