<?php

/**
 * Parche: polyfill para ext-intl en Number::format()
 *
 * Este script parchea vendor/laravel/framework/src/Illuminate/Support/Number.php
 * para usar number_format() cuando ext-intl no está disponible.
 *
 * Re-ejecutar después de: composer update laravel/framework
 *
 * Uso: php patches/apply-intl-polyfill.php
 */

$file = __DIR__ . '/../vendor/laravel/framework/src/Illuminate/Support/Number.php';

if (!file_exists($file)) {
    echo "ERROR: No se encontró $file\n";
    exit(1);
}

$content = file_get_contents($file);

// Parche 1: format() con fallback a number_format
$old1 = <<<'PHP'
    public static function format(int|float $number, ?int $precision = null, ?int $maxPrecision = null, ?string $locale = null)
    {
        static::ensureIntlExtensionIsInstalled();

        $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::DECIMAL);
PHP;

$new1 = <<<'PHP'
    public static function format(int|float $number, ?int $precision = null, ?int $maxPrecision = null, ?string $locale = null)
    {
        // intl polyfill: use number_format() when ext-intl is not available
        if (! extension_loaded('intl')) {
            $decimals = $precision ?? ($maxPrecision ?? 2);
            return number_format($number, $decimals, '.', ',');
        }

        $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::DECIMAL);
PHP;

// Parche 2: ensureIntlExtensionIsInstalled() sin throw
$old2 = <<<'PHP'
    protected static function ensureIntlExtensionIsInstalled()
    {
        if (! extension_loaded('intl')) {
            $method = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'];

            throw new RuntimeException('The "intl" PHP extension is required to use the ['.$method.'] method.');
        }
    }
PHP;

$new2 = <<<'PHP'
    protected static function ensureIntlExtensionIsInstalled()
    {
        // intl polyfill: format() handles missing intl gracefully
        if (! extension_loaded('intl')) {
            return;
        }
    }
PHP;

if (str_contains($content, 'intl polyfill')) {
    echo "El parche ya está aplicado.\n";
    exit(0);
}

$content = str_replace($old1, $new1, $content);
$content = str_replace($old2, $new2, $content);

file_put_contents($file, $content);
echo "Parche aplicado exitosamente.\n";
