<?php
/**
 * سودانا — FraudGraph v1
 * Network fraud detection
 * Detects: shared devices, recycled proofs, coordinated abuse
 */
class FraudGraph {

    /**
     * Check for fraud signals around a payment attempt
     */
    public static function check(int $userId, float $amount, array $meta = []): array {
        $signals  = [];
        $score    = 0;
        $traceId  = uniqid('frg_', true);

        try {
            $ip = $meta['ip'] ?? null;

            // 1. Same IP used by multiple accounts in last hour
            if ($ip) {
                $ipQ = db()->prepare(
                    "SELECT COUNT(DISTINCT user_id) FROM audit_logs
                     WHERE data LIKE ? AND created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)"
                );
                $ipQ->execute(["%\"ip\":\"$ip\"%"]);
                $ipUsers = (int)$ipQ->fetchColumn();
                if ($ipUsers > 3) {
                    $score += 40;
                    $signals[] = "shared_ip: $ip used by $ipUsers accounts";
                }
            }

            // 2. Duplicate proof image hash (same image used for multiple invoices)
            if (!empty($meta['file_hash'])) {
                $hashQ = db()->prepare(
                    "SELECT COUNT(*) FROM payment_proofs WHERE file_hash=?"
                );
                $hashQ->execute([$meta['file_hash']]);
                $hashCount = (int)$hashQ->fetchColumn();
                if ($hashCount > 0) {
                    $score += 60;
                    $signals[] = "duplicate_proof_image: hash already used";
                }
            }

            // 3. Same reference_code attempted across users
            if (!empty($meta['reference_code'])) {
                $refQ = db()->prepare(
                    "SELECT COUNT(DISTINCT user_id) FROM invoices
                     WHERE reference_code=?"
                );
                $refQ->execute([$meta['reference_code']]);
                $refUsers = (int)$refQ->fetchColumn();
                if ($refUsers > 1) {
                    $score += 50;
                    $signals[] = "ref_code_sharing: {$meta['reference_code']} used by $refUsers users";
                }
            }

            // 4. Rapid invoice creation burst
            $burstQ = db()->prepare(
                "SELECT COUNT(*) FROM invoices
                 WHERE user_id=? AND created_at > DATE_SUB(NOW(), INTERVAL 10 MINUTE)"
            );
            $burstQ->execute([$userId]);
            $burst = (int)$burstQ->fetchColumn();
            if ($burst > 5) {
                $score += 30;
                $signals[] = "invoice_burst: $burst invoices in 10 minutes";
            }

            $isFraud = $score >= 50;
            $action  = $isFraud ? 'block' : ($score >= 30 ? 'review' : 'allow');

            return [
                'is_fraud'   => $isFraud,
                'fraud_score'=> $score,
                'action'     => $action,
                'signals'    => $signals,
                'user_id'    => $userId,
                'trace_id'   => $traceId,
                'checked_at' => date('Y-m-d H:i:s'),
            ];

        } catch (Throwable $e) {
            error_log("[FraudGraph] " . $e->getMessage());
            return [
                'is_fraud'  => false,
                'action'    => 'allow',
                'signals'   => ['check_failed'],
                'trace_id'  => $traceId,
            ];
        }
    }
}
