<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ExpenseModel;

class ExpenseController extends BaseController
{
    public function index()
    {
        $model = new ExpenseModel();
        $expenses = $model->forCompany($this->currentCompanyId())->orderBy('date', 'DESC')->paginate(15);
        return view('admin/expenses/index', ['expenses' => $expenses, 'pager' => $model->pager]);
    }

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

    public function store()
    {
        $data = $this->expenseData();
        $data['company_id'] = $this->currentCompanyId();
        (new ExpenseModel())->insert($data);
        return redirect()->to('/admin/expenses')->with('message', lang('App.saved_successfully'));
    }

    public function edit($id)
    {
        $expense = (new ExpenseModel())->forCompany($this->currentCompanyId())->find($id);
        return view('admin/expenses/form', ['expense' => $expense, 'currencies' => $this->activeCurrencies()]);
    }

    public function update($id)
    {
        (new ExpenseModel())->update($id, $this->expenseData());
        return redirect()->to('/admin/expenses')->with('message', lang('App.saved_successfully'));
    }

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

    private function expenseData(): array
    {
        return [
            'category' => $this->request->getPost('category'),
            'description' => $this->request->getPost('description'),
            'amount' => $this->request->getPost('amount'),
            'currency' => $this->request->getPost('currency'),
            'date' => $this->request->getPost('date'),
        ];
    }
}
