<?php
// Join gift settings service.
// Controls how many diamonds a brand-new user receives on first membership/start.

if(!function_exists('bot_join_gift_setting_path')){
    function bot_join_gift_setting_path(){
        return 'lib/kodam/join_gift_diamonds.txt';
    }
}

if(!function_exists('bot_join_gift_normalize_number')){
    function bot_join_gift_normalize_number($value){
        $value = trim((string)$value);
        if(function_exists('bot_normalize_number_digits')){
            $value = bot_normalize_number_digits($value);
        }else{
            $fa = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹','٠','١','٢','٣','٤','٥','٦','٧','٨','٩'];
            $en = ['0','1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6','7','8','9'];
            $value = str_replace($fa, $en, $value);
        }
        return preg_replace('/[^0-9\-]/', '', $value);
    }
}

if(!function_exists('bot_join_gift_amount')){
    function bot_join_gift_amount(){
        $default = 10;
        $raw = $default;
        if(function_exists('bot_data_get_text')){
            $raw = bot_data_get_text(bot_join_gift_setting_path(), (string)$default);
        }else{
            $path = bot_join_gift_setting_path();
            $raw = is_file($path) ? (string)@file_get_contents($path) : (string)$default;
        }
        $raw = bot_join_gift_normalize_number($raw);
        if($raw === '' || !preg_match('/^-?\d+$/', $raw)) return $default;
        return max(0, (int)$raw);
    }
}

if(!function_exists('bot_join_gift_save_amount')){
    function bot_join_gift_save_amount($amount){
        $amount = bot_join_gift_normalize_number($amount);
        $amount = ($amount === '' || !preg_match('/^-?\d+$/', $amount)) ? 0 : max(0, (int)$amount);
        if(function_exists('bot_data_put_text')) return bot_data_put_text(bot_join_gift_setting_path(), (string)$amount);
        if(function_exists('Save')){ Save(bot_join_gift_setting_path(), (string)$amount); return true; }
        $path = bot_join_gift_setting_path();
        $dir = dirname($path);
        if($dir && $dir !== '.' && !is_dir($dir)) @mkdir($dir, 0775, true);
        return @file_put_contents($path, (string)$amount, LOCK_EX) !== false;
    }
}
