<?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\PaymentVoucherModel;
use Modules\Accounting\Services\PaymentVoucherService;

class PaymentVoucherController extends BaseController
{
    protected PaymentVoucherModel $vouchers;
    protected PaymentVoucherService $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->vouchers    = new PaymentVoucherModel();
        $this->service     = new PaymentVoucherService();
        $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;

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

        $vouchers = array_map(fn (array $v) => $this->enrichVoucher($v), $vouchers);

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

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

    public function store()
    {
        if (! $this->validate([
            'voucher_date'  => 'required|valid_date',
            'amount'        => 'required|decimal',
            '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/payment-vouchers')->with('success', 'Payment voucher created.');
    }

    public function show(int $id)
    {
        $voucher = $this->vouchers
            ->select('payment_vouchers.*, 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 = payment_vouchers.account_id', 'left')
            ->join('cost_centers', 'cost_centers.id = payment_vouchers.cost_center_id', 'left')
            ->find($id);

        if (! $voucher) {
            return redirect()->to('/accounting/payment-vouchers')->with('error', 'Payment voucher not found.');
        }

        return view('Modules\Accounting\Views\payment_vouchers\show', array_merge($this->baseViewData(), [
            'title'   => 'Payment Voucher ' . $voucher['number'],
            'voucher' => $this->enrichVoucher($voucher),
        ]));
    }

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

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

    public function update(int $id)
    {
        if (! $this->validate([
            'voucher_date'  => 'required|valid_date',
            'amount'        => 'required|decimal',
            '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/payment-vouchers')->with('success', 'Payment voucher updated.');
    }

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

        return redirect()->to('/accounting/payment-vouchers/' . $id)->with('success', 'Payment voucher posted.');
    }

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

        return redirect()->to('/accounting/payment-vouchers')->with('success', 'Payment voucher deleted.');
    }

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

        return $voucher;
    }

    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 '#';
    }
}
