<?php
// Reward, cooldown, and channel reward policy service.

function bale_order_clean_list($value){
    if(!is_array($value)) return [];
    $out = [];
    foreach($value as $item){
        $item = trim((string)$item);
        if($item !== '' && !in_array($item, $out, true)) $out[] = $item;
    }
    return $out;
}

function bale_order_count_clean($value){
    return count(bale_order_clean_list($value));
}

function bale_order_channel_key($order){
    $id = isset($order['channel_id']) ? trim((string)$order['channel_id']) : '';
    if($id !== '') return 'id:'.$id;
    $ch = isset($order['channel']) ? strtolower(normalize_bale_channel_username($order['channel'])) : '';
    return $ch !== '' ? 'u:'.$ch : '';
}

function bale_channel_reward_history_file(){
    return 'lib/kodam/channel_reward_users.json';
}

function bale_load_channel_reward_history(){
    $file = bale_channel_reward_history_file();
    if(!file_exists($file)) return [];
    $data = bot_data_get_json($file);
    return is_array($data) ? $data : [];
}

function bale_save_channel_reward_history($data){
    bot_data_put_json(bale_channel_reward_history_file(), $data);
}

function bale_reward_cooldown_file(){
    return 'lib/kodam/reward_cooldown.json';
}

function bale_load_reward_cooldown_config(){
    $file = bale_reward_cooldown_file();
    if(!file_exists($file)) bot_data_put_json($file, ['days'=>3]);
    $data = bot_data_get_json($file);
    if(!is_array($data)) $data = [];
    $days = isset($data['days']) ? (int)$data['days'] : 3;
    if($days < 0) $days = 0;
    if($days > 3650) $days = 3650;
    return ['days'=>$days];
}

function bale_save_reward_cooldown_days($days){
    $days = (int)$days;
    if($days < 0) $days = 0;
    if($days > 3650) $days = 3650;
    bot_data_put_json(bale_reward_cooldown_file(), ['days'=>$days, 'updated_at'=>time()]);
    return $days;
}

function bale_reward_cooldown_days(){
    $cfg = bale_load_reward_cooldown_config();
    return (int)$cfg['days'];
}

function bale_reward_cooldown_seconds(){
    return bale_reward_cooldown_days() * 86400;
}


function bale_self_reward_config_file(){
    return 'lib/kodam/self_reward.json';
}

function bale_load_self_reward_config(){
    $file = bale_self_reward_config_file();
    if(!file_exists($file)) bot_data_put_json($file, ['enabled'=>false, 'days'=>3]);
    $data = bot_data_get_json($file);
    if(!is_array($data)) $data = [];
    $enabled = !empty($data['enabled']) && $data['enabled'] !== 'false' && $data['enabled'] !== '0';
    $days = isset($data['days']) ? (int)$data['days'] : 3;
    if($days < 0) $days = 0;
    if($days > 3650) $days = 3650;
    return ['enabled'=>$enabled, 'days'=>$days];
}

function bale_save_self_reward_config($enabled = null, $days = null){
    $cfg = bale_load_self_reward_config();
    if($enabled !== null) $cfg['enabled'] = (bool)$enabled;
    if($days !== null){
        $days = (int)$days;
        if($days < 0) $days = 0;
        if($days > 3650) $days = 3650;
        $cfg['days'] = $days;
    }
    $cfg['updated_at'] = time();
    bot_data_put_json(bale_self_reward_config_file(), $cfg);
    return $cfg;
}

function bale_self_reward_enabled(){
    $cfg = bale_load_self_reward_config();
    return !empty($cfg['enabled']);
}

function bale_self_reward_cooldown_days(){
    $cfg = bale_load_self_reward_config();
    return (int)$cfg['days'];
}

function bale_self_reward_toggle(){
    $cfg = bale_load_self_reward_config();
    return bale_save_self_reward_config(empty($cfg['enabled']), null);
}

function bale_self_reward_status_text(){
    $cfg = bale_load_self_reward_config();
    return (!empty($cfg['enabled']) ? '✅ فعال' : '❌ غیرفعال') . ' / هر ' . (int)$cfg['days'] . ' روز';
}

function bale_is_order_owner($userId, $order){
    return (string)$userId === (string)($order['admin'] ?? '');
}

function bale_format_remaining_time_fa($seconds){
    $seconds = max(0, (int)$seconds);
    $days = intdiv($seconds, 86400);
    $seconds %= 86400;
    $hours = intdiv($seconds, 3600);
    $seconds %= 3600;
    $minutes = intdiv($seconds, 60);
    $parts = [];
    if($days > 0) $parts[] = $days.' روز';
    if($hours > 0) $parts[] = $hours.' ساعت';
    if($minutes > 0 || empty($parts)) $parts[] = $minutes.' دقیقه';
    return implode(' و ', $parts);
}

function bale_channel_reward_cooldown_info($userId, $order, $overrideDays = null){
    $key = bale_order_channel_key($order);
    if($overrideDays !== null){
        $days = (int)$overrideDays;
        if($days < 0) $days = 0;
        if($days > 3650) $days = 3650;
        $cooldownSeconds = $days * 86400;
    }else{
        $cooldownSeconds = bale_reward_cooldown_seconds();
        $days = bale_reward_cooldown_days();
    }
    if($key === '' || $cooldownSeconds <= 0){
        return ['allowed'=>true, 'days'=>$days, 'remaining'=>0, 'last_time'=>0, 'key'=>$key];
    }
    $history = bale_load_channel_reward_history();
    if(!isset($history[$key][(string)$userId])){
        return ['allowed'=>true, 'days'=>$days, 'remaining'=>0, 'last_time'=>0, 'key'=>$key];
    }
    $record = $history[$key][(string)$userId];
    $lastTime = 0;
    if(is_array($record) && isset($record['time'])) $lastTime = (int)$record['time'];
    elseif(is_numeric($record)) $lastTime = (int)$record;
    if($lastTime <= 0){
        return ['allowed'=>true, 'days'=>$days, 'remaining'=>0, 'last_time'=>0, 'key'=>$key];
    }
    $elapsed = time() - $lastTime;
    if($elapsed >= $cooldownSeconds){
        return ['allowed'=>true, 'days'=>$days, 'remaining'=>0, 'last_time'=>$lastTime, 'key'=>$key];
    }
    return ['allowed'=>false, 'days'=>$days, 'remaining'=>($cooldownSeconds - $elapsed), 'last_time'=>$lastTime, 'key'=>$key];
}

function bale_user_rewarded_for_channel_before($userId, $order){
    $info = bale_channel_reward_cooldown_info($userId, $order);
    return empty($info['allowed']);
}

function bale_mark_user_rewarded_for_channel($userId, $orderId, $order){
    $key = bale_order_channel_key($order);
    if($key === '') return;
    $history = bale_load_channel_reward_history();
    if(!isset($history[$key]) || !is_array($history[$key])) $history[$key] = [];
    $history[$key][(string)$userId] = [
        'order_id' => (string)$orderId,
        'channel' => isset($order['channel']) ? normalize_bale_channel_username($order['channel']) : '',
        'channel_id' => isset($order['channel_id']) ? (string)$order['channel_id'] : '',
        'time' => time(),
    ];
    bale_save_channel_reward_history($history);
}
