<?php

namespace App\Core;

class PaymentParser
{
    /**
     * Extract reference number from raw SMS text
     */
    public static function extractReference(string $text): ?string
    {
        $text = trim($text);
        if (empty($text)) return null;

        // If it's already a single word (likely just the ref number), return it
        if (!str_contains($text, ' ') && strlen($text) > 5) {
            return strtoupper($text);
        }

        // 1. Orange Money / Jordanian Arabic format: بالرقم المرجعي JIBA... or OJM...
        if (preg_match('/بالرقم المرجعي\s+([A-Z0-9\-]+)/i', $text, $matches)) {
            return strtoupper($matches[1]);
        }

        // 2. English "Ref" format: Ref CS260210...
        if (preg_match('/Ref\s+([A-Z0-9]+)/i', $text, $matches)) {
            return strtoupper($matches[1]);
        }

        // 3. Generic "Reference" or "رقم الحوالة"
        if (preg_match('/(?:Reference|المرجع|رقم الحوالة|رقم العملية)[:\s]+([A-Z0-9\-]+)/iu', $text, $matches)) {
            return strtoupper($matches[1]);
        }

        // 4. Try to find any long alphanumeric string that looks like a ref (8+ chars)
        // This is a fallback and might be risky, but useful for copy-pasting just the ref.
        if (preg_match('/([A-Z]{1,4}[0-9]{5,})/i', $text, $matches)) {
            return strtoupper($matches[0]);
        }

        return null;
    }

    /**
     * Extract amount from raw SMS text
     */
    public static function extractAmount(string $text): float
    {
        // بمبلغ 61.25 دينار
        if (preg_match('/بمبلغ\s+([\d\.]+)/u', $text, $matches)) {
            return (float)$matches[1];
        }

        // JOD 28.550
        if (preg_match('/JOD\s+([\d\.]+)/i', $text, $matches)) {
            return (float)$matches[1];
        }

        // 1.5 دينار اردني
        if (preg_match('/([\d\.]+)\s+دينار/u', $text, $matches)) {
            return (float)$matches[1];
        }

        return 0.0;
    }
}
