<?php
/**
 * نظام الحدود الذكي - الدالة الرئيسية
 * check_and_consume_limit()
 */

declare(strict_types=1);

require_once __DIR__ . '/limits.php';

/**
 * الدالة الرئيسية: التحقق من الحدود والاستهلاك
 * 
 * @param PDO $db
 * @param string $bot_label
 * @param int $user_id
 * @param int $account_id
 * @param string $account_name
 * @return array ['allowed' => bool, 'message' => string|null, 'warning' => string|null, 'event' => string]
 */
function check_and_consume_limit(
    PDO $db,
    string $bot_label,
    int $user_id,
    int $account_id,
    string $account_name
): array
{
    // 1. التحقق من الحظر (خاص بهذا البوت)
    $ban = check_ban($db, $user_id, $account_id, $bot_label);
    if ($ban) {
        $banned_until = date('d/m/Y H:i', strtotime($ban['banned_until']));
        $days_remaining = ceil((strtotime($ban['banned_until']) - time()) / 86400);
        $message = get_limit_message($db, 'on_banned', [
            'account' => $account_name,
            'banned_until' => $banned_until,
            'ban_days' => $days_remaining
        ]);
        
        return [
            'allowed' => false,
            'message' => $message,
            'warning' => null,
            'event' => 'banned'
        ];
    }
    
    // 2. جلب الحدود المطبقة (مع user_id لدعم limits_user)
    $limits = get_effective_limits($db, $bot_label, $account_id, $user_id);
    
    // 3. جلب/إنشاء العدادات (مع bot_label لجعلها مستقلة لكل بوت)
    $counter = get_or_create_counter($db, $user_id, $account_id, $bot_label);
    
    // 4. إعادة تعيين العدادات منتهية الصلاحية
    reset_expired_counters($counter, $limits['mode']);
    
    // 5. تحديث قاعدة البيانات إذا تم إعادة التعيين
    if ($counter['was_reset'] ?? false) {
        $stmt = $db->prepare("
            UPDATE limit_counters
            SET day_used = ?, week_used = ?, month_used = ?,
                day_reset_at = ?, week_reset_at = ?, month_reset_at = ?
            WHERE id = ?
        ");
        $stmt->execute([
            $counter['day_used'],
            $counter['week_used'],
            $counter['month_used'],
            $counter['day_reset_at'],
            $counter['week_reset_at'],
            $counter['month_reset_at'],
            $counter['id']
        ]);
    }
    
    // 6. استخراج القيم
    $mode = $limits['mode'];
    $per_day = $limits['per_day'];
    $day_used = (int)$counter['day_used'];
    $week_used = (int)$counter['week_used'];
    $month_used = (int)$counter['month_used'];
    
    // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    // الوضع اليومي (Daily)
    // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    
    if ($mode === 'daily') {
        // تجاوز الحد اليومي
        if ($day_used >= $per_day) {
            $reset_time = date('H:i', strtotime($counter['day_reset_at']));
            $message = get_limit_message($db, 'on_limit_hit', [
                'account' => $account_name,
                'day_used' => $day_used,
                'per_day' => $per_day,
                'reset_time' => $reset_time
            ]);
            
            return [
                'allowed' => false,
                'message' => $message,
                'warning' => null,
                'event' => 'daily_limit'
            ];
        }
        
        // تنبيه عند الاقتراب من الحد (80%)
        $warning = null;
        if ($day_used >= floor($per_day * 0.8) && $day_used < $per_day) {
            $remaining = $per_day - $day_used;
            $reset_time = date('H:i', strtotime($counter['day_reset_at']));
            $warning = get_limit_message($db, 'on_daily_near', [
                'account' => $account_name,
                'day_used' => $day_used,
                'per_day' => $per_day,
                'remaining' => $remaining,
                'reset_time' => $reset_time
            ]);
        }
        
        // السماح وزيادة العدادات
        increment_counters($db, (int)$counter['id'], $mode);
        
        return [
            'allowed' => true,
            'message' => null,
            'warning' => $warning,
            'event' => 'allowed'
        ];
    }
    
    // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    // الوضع الأسبوعي (Weekly)
    // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    
    if ($mode === 'weekly') {
        $weekly_cap = $limits['weekly_cap'];
        $ban_days = $limits['ban_days'] ?? 7;
        
        // تجاوز الحد الأسبوعي → حظر
        if ($week_used >= $weekly_cap) {
            apply_ban($db, $user_id, $account_id, $bot_label, $ban_days, 'weekly_exceeded');
            
            $banned_until = date('d/m/Y H:i', strtotime("+{$ban_days} days"));
            $message = get_limit_message($db, 'on_banned', [
                'account' => $account_name,
                'ban_days' => $ban_days,
                'banned_until' => $banned_until
            ]);
            
            return [
                'allowed' => false,
                'message' => $message,
                'warning' => null,
                'event' => 'weekly_exceeded'
            ];
        }
        
        // تجاوز الحد اليومي → رفض
        if ($day_used >= $per_day) {
            $reset_time = date('H:i', strtotime($counter['day_reset_at']));
            $message = get_limit_message($db, 'on_limit_hit', [
                'account' => $account_name,
                'day_used' => $day_used,
                'per_day' => $per_day,
                'reset_time' => $reset_time
            ]);
            
            return [
                'allowed' => false,
                'message' => $message,
                'warning' => null,
                'event' => 'daily_limit'
            ];
        }
        
        // تنبيه مشاركة الحساب (الكود الرابع)
        $warning = null;
        if ($week_used == 3) {
            $warning = get_limit_message($db, 'on_share_warning', [
                'account' => $account_name,
                'weekly_cap' => $weekly_cap
            ]);
        }
        
        // السماح وزيادة العدادات
        increment_counters($db, (int)$counter['id'], $mode);
        
        return [
            'allowed' => true,
            'message' => null,
            'warning' => $warning,
            'event' => 'allowed'
        ];
    }
    
    // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    // الوضع الشهري (Monthly)
    // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    
    if ($mode === 'monthly') {
        $monthly_cap = $limits['monthly_cap'];
        $ban_days = $limits['ban_days'] ?? 30;
        
        // تجاوز الحد الشهري → حظر
        if ($month_used >= $monthly_cap) {
            apply_ban($db, $user_id, $account_id, $bot_label, $ban_days, 'monthly_exceeded');
            
            $banned_until = date('d/m/Y H:i', strtotime("+{$ban_days} days"));
            $message = get_limit_message($db, 'on_banned', [
                'account' => $account_name,
                'ban_days' => $ban_days,
                'banned_until' => $banned_until
            ]);
            
            return [
                'allowed' => false,
                'message' => $message,
                'warning' => null,
                'event' => 'monthly_exceeded'
            ];
        }
        
        // تجاوز الحد اليومي → رفض
        if ($day_used >= $per_day) {
            $reset_time = date('H:i', strtotime($counter['day_reset_at']));
            $message = get_limit_message($db, 'on_limit_hit', [
                'account' => $account_name,
                'day_used' => $day_used,
                'per_day' => $per_day,
                'reset_time' => $reset_time
            ]);
            
            return [
                'allowed' => false,
                'message' => $message,
                'warning' => null,
                'event' => 'daily_limit'
            ];
        }
        
        // تنبيه عند الاقتراب من الحد الشهري (80%)
        $warning = null;
        if ($month_used >= floor($monthly_cap * 0.8)) {
            $remaining = $monthly_cap - $month_used;
            $warning = get_limit_message($db, 'on_daily_near', [
                'account' => $account_name,
                'day_used' => $month_used,
                'per_day' => $monthly_cap,
                'remaining' => $remaining,
                'reset_time' => date('d/m', strtotime($counter['month_reset_at']))
            ]);
        }
        
        // السماح وزيادة العدادات
        increment_counters($db, (int)$counter['id'], $mode);
        
        return [
            'allowed' => true,
            'message' => null,
            'warning' => $warning,
            'event' => 'allowed'
        ];
    }
    
    // افتراضي (لا ينفذ عادةً)
    return [
        'allowed' => true,
        'message' => null,
        'warning' => null,
        'event' => 'allowed'
    ];
}
