<?php

namespace App\Http\Middleware;

use App\Models\Currency;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\QueryException;
use PDOException;
use Symfony\Component\HttpFoundation\Response;

class ShareCurrency
{
    public function handle(Request $request, Closure $next): Response
    {
        $currency = null;
        
        try {
            // Skip if currencies table doesn't exist (during installation)
            if (!Schema::hasTable('currencies')) {
                $currency = $this->getDefaultCurrency();
            } else {
                $currency = Currency::getDefault() ?? $this->getDefaultCurrency();
            }
        } catch (QueryException $e) {
            // Database doesn't exist or connection failed (during installation)
            $currency = $this->getDefaultCurrency();
        } catch (PDOException $e) {
            // PDO connection failed (during installation)
            $currency = $this->getDefaultCurrency();
        } catch (\Exception $e) {
            // Any other database-related error
            $currency = $this->getDefaultCurrency();
        }

        view()->share('activeCurrency', $currency);

        return $next($request);
    }
    
    /**
     * Get default currency object
     */
    private function getDefaultCurrency(): Currency
    {
        return new Currency([
            'code' => 'USD',
            'name' => 'US Dollar',
            'symbol' => '$',
            'symbol_position' => 'left',
            'exchange_rate' => 1.000000,
        ]);
    }
}
