<?php
/**
 * سودانا — SmartLimits v1
 * Dynamic per-user limits based on KYC level + history
 * DEBIT_ONLY: no credit extension
 */
class SmartLimits {

    // Base limits by KYC level (SDG)
    const LIMITS = [
        0 => ['daily'=>2000,  'single'=>500,   'monthly'=>10000],   // email only
        1 => ['daily'=>10000, 'single'=>5000,  'monthly'=>50000],   // phone verified
        2 => ['daily'=>50000, 'single'=>25000, 'monthly'=>200000],  // ID verified
        3 => ['daily'=>200000,'single'=>100000,'monthly'=>1000000], // full KYC
    ];

    /**
     * Check if a transaction is within user limits
     */
    public static function check(int $userId, float $amount): array {
        $traceId = uniqid('sl_', true);
        try {
            // Get KYC level
            $kycQ = db()->prepare("SELECT kyc_level FROM wallet WHERE user_id=?");
            $kycQ->execute([$userId]);
            $kycLevel = (int)($kycQ->fetchColumn() ?: 0);

            $limits = self::LIMITS[$kycLevel] ?? self::LIMITS[0];

            // Single transaction limit
            if ($amount > $limits['single']) {
                return self::block($userId, $amount, $kycLevel, $limits, 'single_limit_exceeded', $traceId);
            }

            // Daily spent today
            $dailyQ = db()->prepare(
                "SELECT COALESCE(SUM(amount_sdg),0) FROM wallet_transactions
                 WHERE user_id=? AND type='debit'
                   AND DATE(created_at)=CURDATE()"
            );
            $dailyQ->execute([$userId]);
            $dailySpent = (float)$dailyQ->fetchColumn();

            if ($dailySpent + $amount > $limits['daily']) {
                return self::block($userId, $amount, $kycLevel, $limits, 'daily_limit_exceeded', $traceId,
                    ['daily_spent'=>$dailySpent, 'daily_remaining'=>max(0,$limits['daily']-$dailySpent)]);
            }

            // Monthly spent
            $monthQ = db()->prepare(
                "SELECT COALESCE(SUM(amount_sdg),0) FROM wallet_transactions
                 WHERE user_id=? AND type='debit'
                   AND YEAR(created_at)=YEAR(CURDATE())
                   AND MONTH(created_at)=MONTH(CURDATE())"
            );
            $monthQ->execute([$userId]);
            $monthSpent = (float)$monthQ->fetchColumn();

            if ($monthSpent + $amount > $limits['monthly']) {
                return self::block($userId, $amount, $kycLevel, $limits, 'monthly_limit_exceeded', $traceId);
            }

            return [
                'allowed'         => true,
                'action'          => 'allow',
                'kyc_level'       => $kycLevel,
                'amount'          => $amount,
                'limits'          => $limits,
                'daily_remaining' => round($limits['daily'] - $dailySpent, 2),
                'trace_id'        => $traceId,
            ];

        } catch (Throwable $e) {
            error_log("[SmartLimits] " . $e->getMessage());
            return ['allowed'=>true, 'action'=>'allow', 'trace_id'=>$traceId];
        }
    }

    private static function block(int $userId, float $amount, int $kyc,
            array $limits, string $reason, string $traceId, array $extra=[]): array {
        return array_merge([
            'allowed'    => false,
            'action'     => 'block',
            'reason'     => $reason,
            'kyc_level'  => $kyc,
            'amount'     => $amount,
            'limits'     => $limits,
            'upgrade_message' => "رفع مستوى التحقق KYC لزيادة الحدود",
            'trace_id'   => $traceId,
        ], $extra);
    }
}
