<?php

namespace App\Http\Controllers;

use App\Models\ExchangeRate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ExchangeRateController extends Controller
{
    /**
     * Get all active exchange rates (public)
     */
    public function index()
    {
        $rates = ExchangeRate::active()->get();

        return response()->json([
            'success' => true,
            'rates' => $rates
        ]);
    }

    /**
     * Get specific currency rate (public)
     */
    public function show($currencyCode)
    {
        $rate = ExchangeRate::where('currency_code', strtoupper($currencyCode))
            ->where('is_active', true)
            ->first();

        if (!$rate) {
            return response()->json([
                'success' => false,
                'error' => 'Currency rate not found'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'rate' => $rate
        ]);
    }

    /**
     * Get USD rate specifically (public convenience endpoint)
     */
    public function usdRate()
    {
        $rate = ExchangeRate::getRate('USD');

        if (!$rate) {
            return response()->json([
                'success' => false,
                'error' => 'USD rate not configured'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'currency_code' => 'USD',
            'rate' => $rate
        ]);
    }

    // ==================== ADMIN ENDPOINTS ====================

    /**
     * Admin: Get all rates including inactive
     */
    public function adminIndex()
    {
        $rates = ExchangeRate::with('updatedByUser')->get();

        return response()->json([
            'success' => true,
            'rates' => $rates
        ]);
    }

    /**
     * Admin: Create new currency rate
     */
    public function store(Request $request)
    {
        $request->validate([
            'currency_code' => 'required|string|max:10|unique:exchange_rates',
            'currency_name' => 'required|string|max:100',
            'rate' => 'required|numeric|min:0',
            'is_active' => 'boolean',
        ]);

        $rate = ExchangeRate::create([
            'currency_code' => strtoupper($request->currency_code),
            'currency_name' => $request->currency_name,
            'rate' => $request->rate,
            'is_active' => $request->is_active ?? true,
            'updated_by' => Auth::id(),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Exchange rate created successfully',
            'rate' => $rate
        ], 201);
    }

    /**
     * Admin: Update currency rate
     */
    public function update(Request $request, $id)
    {
        $rate = ExchangeRate::find($id);

        if (!$rate) {
            return response()->json(['error' => 'Rate not found'], 404);
        }

        $request->validate([
            'currency_name' => 'string|max:100',
            'rate' => 'numeric|min:0',
            'is_active' => 'boolean',
        ]);

        $rate->update(array_merge(
            $request->only(['currency_name', 'rate', 'is_active']),
            ['updated_by' => Auth::id()]
        ));

        return response()->json([
            'success' => true,
            'message' => 'Exchange rate updated successfully',
            'rate' => $rate->fresh()->load('updatedByUser')
        ]);
    }

    /**
     * Admin: Quick update USD rate
     */
    public function updateUsdRate(Request $request)
    {
        $request->validate([
            'usd_rate' => 'nullable|numeric|min:0',
            'ngn_rate' => 'nullable|numeric|min:0',
        ]);

        $rate = ExchangeRate::where('currency_code', 'USD')->first();

        $updateData = [
            'updated_by' => Auth::id(),
        ];

        if ($request->has('usd_rate')) {
            $updateData['usd_rate'] = $request->usd_rate;
        }
        if ($request->has('ngn_rate')) {
            $updateData['ngn_rate'] = $request->ngn_rate;
            $updateData['rate'] = $request->ngn_rate; // Keep rate in sync
        }

        if (!$rate) {
            $rate = ExchangeRate::create(array_merge([
                'currency_code' => 'USD',
                'currency_name' => 'US Dollar',
                'usd_rate' => $request->usd_rate ?? 1,
                'ngn_rate' => $request->ngn_rate ?? 1600,
                'rate' => $request->ngn_rate ?? 1600,
                'is_active' => true,
            ], $updateData));
        } else {
            $rate->update($updateData);
        }

        return response()->json([
            'success' => true,
            'message' => 'USD rate updated successfully',
            'rate' => $rate->fresh()
        ]);
    }

    /**
     * Admin: Delete currency rate
     */
    public function destroy($id)
    {
        $rate = ExchangeRate::find($id);

        if (!$rate) {
            return response()->json(['error' => 'Rate not found'], 404);
        }

        if ($rate->currency_code === 'USD') {
            return response()->json(['error' => 'Cannot delete USD rate'], 400);
        }

        $rate->delete();

        return response()->json([
            'success' => true,
            'message' => 'Exchange rate deleted successfully'
        ]);
    }
}
