<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\CurrencyModel;

class CurrencyController extends BaseController
{
    public function index()
    {
        $model = new CurrencyModel();
        $currencies = $model->forCompany($this->currentCompanyId())->orderBy('is_default', 'DESC')->orderBy('code', 'ASC')->findAll();

        return view('admin/currencies/index', ['currencies' => $currencies]);
    }

    public function create()
    {
        return view('admin/currencies/form', ['currency' => null]);
    }

    public function store()
    {
        $companyId = $this->currentCompanyId();
        if (! $companyId) {
            return redirect()->to('/admin/currencies')->with('error', 'اختر شركة نشطة أولاً.');
        }

        $model = new CurrencyModel();
        $data = $this->currencyData();
        $data['company_id'] = $companyId;

        if (! empty($data['is_default'])) {
            $model->forCompany($companyId)->set(['is_default' => 0])->update();
        }

        if (! $model->insert($data)) {
            return redirect()->back()->withInput()->with('error', implode(' | ', $model->errors() ?: ['فشل الحفظ - تأكد إن كود العملة غير مكرر']));
        }

        return redirect()->to('/admin/currencies')->with('message', lang('App.saved_successfully'));
    }

    public function edit($id)
    {
        $currency = (new CurrencyModel())->forCompany($this->currentCompanyId())->find($id);
        if (! $currency) return redirect()->to('/admin/currencies');

        return view('admin/currencies/form', ['currency' => $currency]);
    }

    public function update($id)
    {
        $companyId = $this->currentCompanyId();
        $model = new CurrencyModel();
        $data = $this->currencyData();

        if (! empty($data['is_default'])) {
            $model->forCompany($companyId)->set(['is_default' => 0])->update();
        }

        $model->update($id, $data);

        return redirect()->to('/admin/currencies')->with('message', lang('App.saved_successfully'));
    }

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

    private function currencyData(): array
    {
        return [
            'code' => strtoupper((string) $this->request->getPost('code')),
            'name' => $this->request->getPost('name'),
            'symbol' => $this->request->getPost('symbol'),
            'is_default' => $this->request->getPost('is_default') ? 1 : 0,
            'is_active' => $this->request->getPost('is_active') ? 1 : 0,
        ];
    }
}
