<?php
/**
 * نظام الحدود الذكي (Static Limit System) - الجزء 1
 * الدوال الأساسية
 * 
 * ترتيب أولويات الحدود (من الأعلى للأقل):
 * 1. override_account - حد خاص بحساب Steam محدد
 * 2. limits_user      - حد خاص بمستخدم تيليجرام محدد
 * 3. limits_bot       - حد خاص ببوت محدد
 * 4. limits_global    - حد عام لجميع البوتات
 */

declare(strict_types=1);

// جلب الحدود المطبقة (بالأولوية)
function get_effective_limits(PDO $db, string $bot_label, int $account_id, int $user_id = 0): array
{
    // الأولوية 1: تجاوز الحساب (override_account)
    $stmt = $db->prepare("SELECT mode, per_day, cap, ban_days FROM limits_override WHERE account_id = ?");
    $stmt->execute([$account_id]);
    $override = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($override) {
        return [
            'mode' => $override['mode'],
            'per_day' => (int)$override['per_day'],
            'weekly_cap' => $override['mode'] === 'weekly' ? (int)$override['cap'] : null,
            'monthly_cap' => $override['mode'] === 'monthly' ? (int)$override['cap'] : null,
            'ban_days' => $override['ban_days'] ? (int)$override['ban_days'] : null,
            'source' => 'override'
        ];
    }
    
    // الأولوية 2: حدود المستخدم (limits_user)
    if ($user_id > 0) {
        // التحقق من وجود الجدول أولاً
        $table_check = $db->query("SHOW TABLES LIKE 'limits_user'")->fetch();
        
        if ($table_check) {
            // محاولة الحصول على حد خاص بالبوت أولاً
            $stmt = $db->prepare("SELECT mode, per_day, weekly_cap, monthly_cap, ban_days FROM limits_user WHERE user_id = ? AND bot_label = ?");
            $stmt->execute([$user_id, $bot_label]);
            $user_limits = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // إذا لم يوجد، جرب الحد العام للمستخدم (bot_label = NULL)
            if (!$user_limits) {
                $stmt = $db->prepare("SELECT mode, per_day, weekly_cap, monthly_cap, ban_days FROM limits_user WHERE user_id = ? AND bot_label IS NULL");
                $stmt->execute([$user_id]);
                $user_limits = $stmt->fetch(PDO::FETCH_ASSOC);
            }
            
            if ($user_limits) {
                return [
                    'mode' => $user_limits['mode'],
                    'per_day' => (int)$user_limits['per_day'],
                    'weekly_cap' => $user_limits['weekly_cap'] ? (int)$user_limits['weekly_cap'] : null,
                    'monthly_cap' => $user_limits['monthly_cap'] ? (int)$user_limits['monthly_cap'] : null,
                    'ban_days' => $user_limits['ban_days'] ? (int)$user_limits['ban_days'] : null,
                    'source' => 'user'
                ];
            }
        }
    }
    
    // الأولوية 3: حدود البوت (limits_bot)
    $stmt = $db->prepare("SELECT mode, per_day, weekly_cap, monthly_cap, ban_days FROM limits_bot WHERE bot_label = ?");
    $stmt->execute([$bot_label]);
    $bot_limits = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($bot_limits) {
        return [
            'mode' => $bot_limits['mode'],
            'per_day' => (int)$bot_limits['per_day'],
            'weekly_cap' => $bot_limits['weekly_cap'] ? (int)$bot_limits['weekly_cap'] : null,
            'monthly_cap' => $bot_limits['monthly_cap'] ? (int)$bot_limits['monthly_cap'] : null,
            'ban_days' => $bot_limits['ban_days'] ? (int)$bot_limits['ban_days'] : null,
            'source' => 'bot'
        ];
    }
    
    // الأولوية 4: الحدود العامة (limits_global)
    $stmt = $db->query("SELECT mode, per_day, weekly_cap, monthly_cap, ban_days FROM limits_global LIMIT 1");
    $global = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($global) {
        return [
            'mode' => $global['mode'],
            'per_day' => (int)$global['per_day'],
            'weekly_cap' => $global['weekly_cap'] ? (int)$global['weekly_cap'] : null,
            'monthly_cap' => $global['monthly_cap'] ? (int)$global['monthly_cap'] : null,
            'ban_days' => $global['ban_days'] ? (int)$global['ban_days'] : null,
            'source' => 'global'
        ];
    }
    
    // افتراضي
    return ['mode' => 'daily', 'per_day' => 2, 'weekly_cap' => null, 'monthly_cap' => null, 'ban_days' => null, 'source' => 'default'];
}

// جلب/إنشاء العدادات
function get_or_create_counter(PDO $db, int $user_id, int $account_id, string $bot_label): array
{
    $stmt = $db->prepare("SELECT * FROM limit_counters WHERE user_id = ? AND account_id = ? AND bot_label = ?");
    $stmt->execute([$user_id, $account_id, $bot_label]);
    $counter = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($counter) {
        return $counter;
    }
    
    $tomorrow = date('Y-m-d 00:00:00', strtotime('+1 day'));
    $next_monday = date('Y-m-d 00:00:00', strtotime('next monday'));
    $next_month = date('Y-m-01 00:00:00', strtotime('first day of next month'));
    
    $stmt = $db->prepare("INSERT INTO limit_counters (user_id, account_id, bot_label, day_used, week_used, month_used, day_reset_at, week_reset_at, month_reset_at) VALUES (?, ?, ?, 0, 0, 0, ?, ?, ?)");
    $stmt->execute([$user_id, $account_id, $bot_label, $tomorrow, $next_monday, $next_month]);
    
    $stmt = $db->prepare("SELECT * FROM limit_counters WHERE user_id = ? AND account_id = ? AND bot_label = ?");
    $stmt->execute([$user_id, $account_id, $bot_label]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// إعادة تعيين العدادات منتهية الصلاحية
function reset_expired_counters(array &$counter, string $mode): void
{
    $now = time();
    $updated = false;
    
    if ($counter['day_reset_at'] && strtotime($counter['day_reset_at']) < $now) {
        $counter['day_used'] = 0;
        $counter['day_reset_at'] = date('Y-m-d 00:00:00', strtotime('tomorrow'));
        $updated = true;
    }
    
    if ($mode === 'weekly' && $counter['week_reset_at'] && strtotime($counter['week_reset_at']) < $now) {
        $counter['week_used'] = 0;
        $counter['week_reset_at'] = date('Y-m-d 00:00:00', strtotime('next monday'));
        $updated = true;
    }
    
    if ($mode === 'monthly' && $counter['month_reset_at'] && strtotime($counter['month_reset_at']) < $now) {
        $counter['month_used'] = 0;
        $counter['month_reset_at'] = date('Y-m-01 00:00:00', strtotime('first day of next month'));
        $updated = true;
    }
    
    $counter['was_reset'] = $updated;
}

// التحقق من الحظر
function check_ban(PDO $db, int $user_id, int $account_id, string $bot_label): ?array
{
    $stmt = $db->prepare("SELECT banned_until, reason FROM limit_bans WHERE user_id = ? AND account_id = ? AND bot_label = ? AND banned_until > NOW()");
    $stmt->execute([$user_id, $account_id, $bot_label]);
    $ban = $stmt->fetch(PDO::FETCH_ASSOC);
    return $ban ?: null;
}

// تطبيق الحظر
function apply_ban(PDO $db, int $user_id, int $account_id, string $bot_label, int $days, string $reason = 'limit_exceeded'): void
{
    $banned_until = date('Y-m-d H:i:s', strtotime("+{$days} days"));
    $stmt = $db->prepare("INSERT INTO limit_bans (user_id, account_id, bot_label, banned_until, reason) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE banned_until = VALUES(banned_until), reason = VALUES(reason), created_at = NOW()");
    $stmt->execute([$user_id, $account_id, $bot_label, $banned_until, $reason]);
}

// إلغاء الحظر
function unban(PDO $db, int $user_id, int $account_id, ?string $bot_label = null): bool
{
    if ($bot_label) {
        $stmt = $db->prepare("DELETE FROM limit_bans WHERE user_id = ? AND account_id = ? AND bot_label = ?");
        return $stmt->execute([$user_id, $account_id, $bot_label]);
    } else {
        // حذف من جميع البوتات
        $stmt = $db->prepare("DELETE FROM limit_bans WHERE user_id = ? AND account_id = ?");
        return $stmt->execute([$user_id, $account_id]);
    }
}

// جلب رسالة حدث
function get_limit_message(PDO $db, string $event, array $vars = []): string
{
    $stmt = $db->prepare("SELECT text FROM limit_messages WHERE event = ?");
    $stmt->execute([$event]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$row) {
        return "⚠️ رسالة الحدث غير متوفرة: {$event}";
    }
    
    $text = $row['text'];
    foreach ($vars as $key => $value) {
        $text = str_replace("{{$key}}", (string)$value, $text);
    }
    
    return $text;
}

// زيادة العدادات
function increment_counters(PDO $db, int $counter_id, string $mode): void
{
    if ($mode === 'daily') {
        $stmt = $db->prepare("UPDATE limit_counters SET day_used = day_used + 1 WHERE id = ?");
        $stmt->execute([$counter_id]);
    } elseif ($mode === 'weekly') {
        $stmt = $db->prepare("UPDATE limit_counters SET day_used = day_used + 1, week_used = week_used + 1 WHERE id = ?");
        $stmt->execute([$counter_id]);
    } elseif ($mode === 'monthly') {
        $stmt = $db->prepare("UPDATE limit_counters SET day_used = day_used + 1, month_used = month_used + 1 WHERE id = ?");
        $stmt->execute([$counter_id]);
    }
}

// إعادة تعيين عدادات مستخدم
function reset_user_counters(PDO $db, int $user_id, ?int $account_id = null, ?string $bot_label = null): int
{
    if ($account_id && $bot_label) {
        $stmt = $db->prepare("UPDATE limit_counters SET day_used = 0, week_used = 0, month_used = 0 WHERE user_id = ? AND account_id = ? AND bot_label = ?");
        $stmt->execute([$user_id, $account_id, $bot_label]);
    } elseif ($account_id) {
        $stmt = $db->prepare("UPDATE limit_counters SET day_used = 0, week_used = 0, month_used = 0 WHERE user_id = ? AND account_id = ?");
        $stmt->execute([$user_id, $account_id]);
    } elseif ($bot_label) {
        $stmt = $db->prepare("UPDATE limit_counters SET day_used = 0, week_used = 0, month_used = 0 WHERE user_id = ? AND bot_label = ?");
        $stmt->execute([$user_id, $bot_label]);
    } else {
        $stmt = $db->prepare("UPDATE limit_counters SET day_used = 0, week_used = 0, month_used = 0 WHERE user_id = ?");
        $stmt->execute([$user_id]);
    }
    return $stmt->rowCount();
}
