<?php

namespace App\Helpers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;

class TenantHelper
{
    /**
     * Convert any stored image value to the correct public storage URL for the
     * current environment.
     *
     * Accepts:
     *  - A full URL from any host:  http://old-host/storage/products/foo.jpg
     *  - A root-relative path:      /storage/products/foo.jpg
     *  - A plain storage-relative:  products/foo.jpg
     *
     * Always returns the URL built from the current APP_URL via the 'public'
     * storage disk, so images stay correct after domain or environment changes.
     */
    public static function storagePublicUrl(?string $stored): ?string
    {
        if (!$stored) {
            return null;
        }

        // Full URL or root-relative path containing /storage/ separator
        if (str_contains($stored, '/storage/')) {
            $path = substr($stored, strpos($stored, '/storage/') + strlen('/storage/'));
        } else {
            // Already a plain relative path (e.g. products/foo.jpg)
            $path = ltrim($stored, '/');
        }

        return Storage::disk('public')->url($path);
    }


    public static function setSchema($schema)
    {
        Config::set('database.connections.pgsql_country.search_path', $schema);

        DB::purge('pgsql_country');
        DB::reconnect('pgsql_country');
    }

    /**
     * Returns the real client IP, respecting common reverse-proxy headers.
     * Falls back to the direct remote address.
     */
    public static function getClientIp(\Illuminate\Http\Request $request): string
    {
        foreach ([
            'HTTP_CF_CONNECTING_IP', // Cloudflare
            'HTTP_X_REAL_IP',
            'HTTP_X_FORWARDED_FOR',
        ] as $header) {
            $value = $request->server($header);
            if ($value) {
                // X-Forwarded-For may contain a comma-separated list; take the first
                return trim(explode(',', $value)[0]);
            }
        }

        return $request->ip() ?? '0.0.0.0';
    }
}
