<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ExchangeRateModel;

class ExchangeRateController extends BaseController
{
    public function index()
    {
        $model = new ExchangeRateModel();
        $rates = $model->orderBy('date', 'DESC')->paginate(15);
        return view('admin/exchange_rates/index', ['rates' => $rates, 'pager' => $model->pager]);
    }

    public function create()
    {
        return view('admin/exchange_rates/form', ['rate' => null, 'currencies' => $this->activeCurrencies()]);
    }

    public function store()
    {
        (new ExchangeRateModel())->insert($this->rateData());
        return redirect()->to('/admin/exchange-rates')->with('message', lang('App.saved_successfully'));
    }

    public function edit($id)
    {
        $rate = (new ExchangeRateModel())->find($id);
        return view('admin/exchange_rates/form', ['rate' => $rate, 'currencies' => $this->activeCurrencies()]);
    }

    public function update($id)
    {
        (new ExchangeRateModel())->update($id, $this->rateData());
        return redirect()->to('/admin/exchange-rates')->with('message', lang('App.saved_successfully'));
    }

    public function delete($id)
    {
        (new ExchangeRateModel())->delete($id);
        return redirect()->to('/admin/exchange-rates')->with('message', lang('App.deleted_successfully'));
    }

    private function rateData(): array
    {
        return [
            'currency_from' => $this->request->getPost('currency_from'),
            'currency_to' => $this->request->getPost('currency_to'),
            'rate' => $this->request->getPost('rate'),
            'date' => $this->request->getPost('date'),
        ];
    }
}
