<?php

namespace App\Http\Controllers;

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

class HomeCurrencyController extends Controller
{
    // Show form and list of home currencies
    public function create()
    {
        $records = HomeCurrency::all();
        $currencies = Currency::all(); // Used for dropdown
        return view('maintanance.chart_of_accounts.createHomeCurrency', compact('records', 'currencies'));
    }

    // Store new home currency
    public function store(Request $request)
    {
        try {
            $request->validate([
                'code' => 'required|string|max:255|unique:home_currencies,code',
                'currency' => 'required|integer|exists:currencies,id',
                'description' => 'required|string|max:255',
            ]);

            $homeCurrency = new HomeCurrency();
            $homeCurrency->code = $request->code;
            $homeCurrency->currency = $request->currency;
            $homeCurrency->description = $request->description;
            $homeCurrency->save();

            return redirect()->route('home_currency.create')->with('success', 'Home currency created successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Update existing home currency
    public function edit(Request $request)
    {
        try {
            $request->validate([
                'id' => 'required|integer|exists:home_currencies,id',
                'code' => 'required|string|max:255',
                'currency' => 'required|integer|exists:currencies,id',
                'description' => 'required|string|max:255',
            ]);

            $homeCurrency = HomeCurrency::findOrFail($request->id);
            $homeCurrency->code = $request->code;
            $homeCurrency->currency = $request->currency;
            $homeCurrency->description = $request->description;
            $homeCurrency->save();

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

    // Delete home currency
    public function delete($id)
    {
        try {
            $homeCurrency = HomeCurrency::findOrFail($id);
            $homeCurrency->delete();

            return redirect()->route('home_currency.create')->with('success', 'Home currency deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('home_currency.create')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
}
