<?php

namespace App\Http\Controllers;

use App\Models\CurrencySetting;
use App\Models\Currency;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CurrencySettingController extends Controller
{
    /**
     * Get the current currency setting with its associated currency.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        try {
            $currencySetting = CurrencySetting::with('currency')->first();

            if (!$currencySetting) {
                return response([
                    'success' => false,
                    'message' => 'No currency setting found'
                ], 404);
            }

            return response([
                'success' => true,
                'data' => $currencySetting
            ], 200);
        } catch (\Exception $e) {
            return response([
                'success' => false,
                'message' => 'Error retrieving currency setting'
            ], 500);
        }
    }

    /**
     * Update the currency setting.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        try {
            $request->validate([
                'currency_id' => 'required|exists:currencies,id',
                'decimal' => 'required|string|max:1',
                'thousands' => 'required|string|max:1',
                'hide_trailing_zero' => 'sometimes|boolean'
            ]);

            $currencySetting = CurrencySetting::first();

            if (!$currencySetting) {
                $currencySetting = new CurrencySetting();
                $currencySetting->name = 'currency';
            }

            $currencySetting->currency_id = $request->currency_id;
            $currencySetting->decimal = $request->decimal;
            $currencySetting->thousands = $request->thousands;
            $currencySetting->hide_trailing_zero = $request->boolean('hide_trailing_zero');
            $currencySetting->save();

            return response([
                'success' => true,
                'message' => 'Currency setting updated successfully',
                'data' => $currencySetting->load('currency')
            ], 200);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response([
                'success' => false,
                'message' => 'Failed to update currency setting',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
