<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\ChartOfAccountModel;
use App\Models\FiscalYearModel;
use App\Models\JournalEntryLineModel;
use App\Models\JournalEntryModel;
use Modules\Accounting\Services\JournalEntryService;

class JournalEntryController extends BaseController
{
    protected JournalEntryModel $journals;
    protected JournalEntryLineModel $lines;
    protected JournalEntryService $service;
    protected ChartOfAccountModel $accounts;
    protected FiscalYearModel $periods;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->journals = new JournalEntryModel();
        $this->lines    = new JournalEntryLineModel();
        $this->service  = new JournalEntryService();
        $this->accounts = new ChartOfAccountModel();
        $this->periods  = new FiscalYearModel();
    }

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

        $journals = $this->journals
            ->scopeForList($search ?: null, $status, $dateFrom, $dateTo)
            ->orderBy('journal_entries.entry_date', 'DESC')
            ->orderBy('journal_entries.id', 'DESC')
            ->findAll();

        return view('Modules\Accounting\Views\journal_entries\index', array_merge($this->baseViewData(), [
            'title'    => 'Journal Entries',
            'journals' => $journals,
            'filters'  => compact('search', 'status', 'dateFrom', 'dateTo'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Accounting\Views\journal_entries\create', array_merge($this->baseViewData(), [
            'title'    => 'New Journal Entry',
            'accounts' => $this->accounts->getActivePostable(),
            'periods'  => $this->periods->getOpen(),
            'lines'    => [
                ['account_id' => '', 'description' => '', 'debit' => '', 'credit' => ''],
                ['account_id' => '', 'description' => '', 'debit' => '', 'credit' => ''],
            ],
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'entry_date' => 'required|valid_date',
        ])) {
            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/journal-entries/' . $result['id'])->with('success', 'Journal entry created.');
    }

    public function show(int $id)
    {
        $journal = $this->journals->scopeForList()->where('journal_entries.id', $id)->first();
        if (! $journal) {
            return redirect()->to('/accounting/journal-entries')->with('error', 'Journal entry not found.');
        }

        return view('Modules\Accounting\Views\journal_entries\show', array_merge($this->baseViewData(), [
            'title'   => 'Journal Entry',
            'journal' => $journal,
            'lines'   => $this->lines->getForJournalEntry($id),
        ]));
    }

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

        $lines = $this->lines->getForJournalEntry($id);
        if (count($lines) < 2) {
            $lines = [
                ['account_id' => '', 'description' => '', 'debit' => '', 'credit' => ''],
                ['account_id' => '', 'description' => '', 'debit' => '', 'credit' => ''],
            ];
        }

        return view('Modules\Accounting\Views\journal_entries\edit', array_merge($this->baseViewData(), [
            'title'    => 'Edit Journal Entry',
            'journal'  => $journal,
            'accounts' => $this->accounts->getActivePostable(),
            'periods'  => $this->periods->getOpen(),
            'lines'    => $lines,
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'entry_date' => 'required|valid_date',
        ])) {
            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/journal-entries/' . $id)->with('success', 'Journal entry 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()->back()->with('success', 'Journal entry posted.');
    }

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

        return redirect()->back()->with('success', 'Journal entry unposted.');
    }

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

        return redirect()->to('/accounting/journal-entries')->with('success', 'Journal entry deleted.');
    }
}
