<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\DailyRate;
use App\Models\HomeCurrency;
use App\Models\Currency;
use Exception;

class DailyRateController extends Controller
{
    // Show form and list
    public function create_rate()
    {
        // Fetch the selected home currency: latest entry or first
        $homeCurrency = HomeCurrency::latest()->first();
        // If none exists, user must create a HomeCurrency entry first
        // Foreign currencies list: exclude the currency referenced by homeCurrency
        if ($homeCurrency) {
            $homeCurrencyId = $homeCurrency->id;
            $homeCurrencyCurrencyId = $homeCurrency->currency; // references currencies.id
            // All Currency entries except the home currency's referenced currency
            $foreignCurrencies = Currency::where('id', '!=', $homeCurrencyCurrencyId)->get();
        } else {
            $foreignCurrencies = collect(); // empty
        }

        // Fetch existing daily rate records, with related data, most recent first
        $records = DailyRate::with(['homeCurrencyRelation.currencyRelation','foreignCurrencyRelation'])
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($rate) {
                // homeCurrencyRelation gives HomeCurrency; to get its code or the linked Currency:
                $homeCur = $rate->homeCurrencyRelation;
                $homeCode = $homeCur->code ?? '';
                // Optionally also get the linked Currency data:
                $linkedCurrency = $homeCur->currencyRelation ?? null;
                $homeSymbolOrCode = $linkedCurrency ? ($linkedCurrency->symbol ?? $linkedCurrency->code) : $homeCode;

                $foreignCur = $rate->foreignCurrencyRelation;
                $foreignCode = $foreignCur->code ?? '';
                $foreignSymbol = $foreignCur->symbol ?? '';

                return (object)[
                    'id' => $rate->id,
                    'created_at' => $rate->created_at,
                    'home_currency_id' => $rate->home_currency,
                    'home_currency_code' => $homeCode,
                    'home_currency_symbol' => $homeSymbolOrCode,
                    'home_rate' => $rate->home_rate,
                    'foreign_currency_id' => $rate->foreign_currency,
                    'foreign_currency_code' => $foreignCode,
                    'foreign_currency_symbol' => $foreignSymbol,
                    'foreign_rate' => $rate->foreign_rate,
                    'description' => $rate->description,
                ];
            });

        return view('maintanance.chart_of_accounts.create_rates', compact(
            'records',
            'homeCurrency',
            'foreignCurrencies'
        ));
    }

    // Store new daily rate
    public function store_rate(Request $request)
    {
        try {
            // Validate only foreign inputs; home is determined in background
            $request->validate([
                'foreign_currency' => 'required|integer|exists:currencies,id',
                'foreign_rate'     => 'required|numeric',
                'description'      => 'nullable|string|max:255',
            ]);

            // Fetch selected home currency entry
            $homeCurrency = HomeCurrency::latest()->first();
            if (! $homeCurrency) {
                return redirect()->route('daily_rates.create')
                    ->withErrors(['error' => 'No home currency configured. Please add a home currency first.']);
            }
            $homeCurrencyId = $homeCurrency->id;

            // Determine home_rate from previous DailyRate for this home_currency, if any
            $latestHomeRateRecord = DailyRate::where('home_currency', $homeCurrencyId)
                ->orderBy('created_at', 'desc')
                ->first();
            $home_rate = $latestHomeRateRecord ? $latestHomeRateRecord->home_rate : 1;

            $rate = new DailyRate();
            $rate->home_currency    = $homeCurrencyId;
            $rate->foreign_currency = $request->foreign_currency;
            $rate->home_rate        = $home_rate;
            $rate->foreign_rate     = $request->foreign_rate;
            $rate->description      = $request->description;
            $rate->save();

            return redirect()->route('daily_rates.create')->with('success', 'Daily rate saved successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Edit existing daily rate
    public function edit_rate(Request $request)
    {
        try {
            $request->validate([
                'id'               => 'required|integer|exists:daily_rates,id',
                'foreign_currency' => 'required|integer|exists:currencies,id',
                'foreign_rate'     => 'required|numeric',
                'description'      => 'nullable|string|max:255',
            ]);

            $rate = DailyRate::findOrFail($request->id);

            // Fetch selected home currency entry
            $homeCurrency = HomeCurrency::latest()->first();
            if (! $homeCurrency) {
                return redirect()->route('daily_rates.create')
                    ->withErrors(['error' => 'No home currency configured.']);
            }
            $homeCurrencyId = $homeCurrency->id;

            // Determine home_rate as latest for this home_currency
            $latestHomeRateRecord = DailyRate::where('home_currency', $homeCurrencyId)
                ->where('id', '!=', $rate->id) // exclude current record perhaps
                ->orderBy('created_at', 'desc')
                ->first();
            $home_rate = $latestHomeRateRecord ? $latestHomeRateRecord->home_rate : 1;

            // Update fields
            $rate->home_currency    = $homeCurrencyId;
            $rate->home_rate        = $home_rate;
            $rate->foreign_currency = $request->foreign_currency;
            $rate->foreign_rate     = $request->foreign_rate;
            $rate->description      = $request->description;
            $rate->save();

            return redirect()->route('daily_rates.create')->with('success', 'Daily rate updated successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Delete a daily rate
    public function delete_rate($id)
    {
        try {
            $rate = DailyRate::findOrFail($id);
            $rate->delete();
            return redirect()->route('daily_rates.create')->with('success', 'Daily rate deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('daily_rates.create')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
}