<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\BankAccountModel;
use App\Models\CashAccountModel;
use App\Models\ChartOfAccountModel;
use App\Models\CostCenterModel;
use App\Models\ExpenseModel;
use Modules\Accounting\Services\ExpenseService;

class ExpenseController extends BaseController
{
    protected ExpenseModel $expenses;
    protected ExpenseService $service;
    protected ChartOfAccountModel $accounts;
    protected BankAccountModel $banks;
    protected CashAccountModel $cash;
    protected CostCenterModel $costCenters;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->expenses    = new ExpenseModel();
        $this->service     = new ExpenseService();
        $this->accounts    = new ChartOfAccountModel();
        $this->banks       = new BankAccountModel();
        $this->cash        = new CashAccountModel();
        $this->costCenters = new CostCenterModel();
    }

    public function index()
    {
        $search = trim((string) $this->request->getGet('q'));
        $status = $this->request->getGet('status') ?: null;

        $expenses = $this->expenses
            ->scopeForList($search ?: null, $status)
            ->orderBy('expenses.expense_date', 'DESC')
            ->orderBy('expenses.id', 'DESC')
            ->findAll();

        $expenses = array_map(fn (array $e) => $this->enrichExpense($e), $expenses);

        return view('Modules\Accounting\Views\expenses\index', array_merge($this->baseViewData(), [
            'title'    => 'Expenses',
            'expenses' => $expenses,
            'filters'  => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Accounting\Views\expenses\create', array_merge($this->baseViewData(), [
            'title'         => 'New Expense',
            'coaAccounts'   => $this->accounts->getActivePostable(),
            'bankAccounts'  => $this->banks->getActive(),
            'cashAccounts'  => $this->cash->getActive(),
            'costCenters'   => $this->costCenters->getActive(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'expense_date'       => 'required|valid_date',
            'amount'             => 'required|decimal',
            'expense_account_id' => 'required|is_natural_no_zero',
            'pay_from_type'      => 'required|in_list[bank,cash]',
            'pay_from_id'        => 'required|is_natural_no_zero',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->create($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/accounting/expenses')->with('success', 'Expense created.');
    }

    public function show(int $id)
    {
        $expense = $this->expenses
            ->select('expenses.*, chart_of_accounts.code as account_code, chart_of_accounts.name as account_name, cost_centers.code as cost_center_code, cost_centers.name as cost_center_name')
            ->join('chart_of_accounts', 'chart_of_accounts.id = expenses.expense_account_id', 'left')
            ->join('cost_centers', 'cost_centers.id = expenses.cost_center_id', 'left')
            ->find($id);

        if (! $expense) {
            return redirect()->to('/accounting/expenses')->with('error', 'Expense not found.');
        }

        return view('Modules\Accounting\Views\expenses\show', array_merge($this->baseViewData(), [
            'title'   => 'Expense ' . $expense['number'],
            'expense' => $this->enrichExpense($expense),
        ]));
    }

    public function editForm(int $id)
    {
        $expense = $this->expenses->find($id);
        if (! $expense) {
            return redirect()->to('/accounting/expenses')->with('error', 'Expense not found.');
        }
        if ($expense['status'] !== 'draft') {
            return redirect()->to('/accounting/expenses/' . $id)->with('error', 'Only draft expenses can be edited.');
        }

        return view('Modules\Accounting\Views\expenses\edit', array_merge($this->baseViewData(), [
            'title'        => 'Edit Expense',
            'expense'      => $expense,
            'coaAccounts'  => $this->accounts->getActivePostable(),
            'bankAccounts' => $this->banks->getActive(),
            'cashAccounts' => $this->cash->getActive(),
            'costCenters'  => $this->costCenters->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'expense_date'       => 'required|valid_date',
            'amount'             => 'required|decimal',
            'expense_account_id' => 'required|is_natural_no_zero',
            'pay_from_type'      => 'required|in_list[bank,cash]',
            'pay_from_id'        => 'required|is_natural_no_zero',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->update($id, $this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/accounting/expenses')->with('success', 'Expense updated.');
    }

    public function approve(int $id)
    {
        $result = $this->service->approve($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->to('/accounting/expenses/' . $id)->with('success', 'Expense approved.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->delete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/accounting/expenses')->with('error', $result['error']);
        }

        return redirect()->to('/accounting/expenses')->with('success', 'Expense deleted.');
    }

    protected function enrichExpense(array $expense): array
    {
        $expense['pay_from_label'] = $this->sideLabel($expense['pay_from_type'], (int) $expense['pay_from_id']);
        if (! empty($expense['account_code'])) {
            $expense['account_label'] = $expense['account_code'] . ' · ' . ($expense['account_name'] ?? '');
        }
        if (! empty($expense['cost_center_code'])) {
            $expense['cost_center_label'] = $expense['cost_center_code'] . ' · ' . ($expense['cost_center_name'] ?? '');
        }

        return $expense;
    }

    protected function sideLabel(string $type, int $id): string
    {
        if ($type === 'bank') {
            $row = $this->banks->find($id);

            return $row ? ($row['code'] . ' · ' . $row['name'] . ' (Bank)') : 'Bank #' . $id;
        }
        if ($type === 'cash') {
            $row = $this->cash->find($id);

            return $row ? ($row['code'] . ' · ' . $row['name'] . ' (Cash)') : 'Cash #' . $id;
        }

        return '#';
    }
}
