<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\VatReturnModel;
use Modules\Accounting\Services\TaxReportService;
use Modules\Accounting\Services\VatReturnService;

class VatReturnController extends BaseController
{
    protected VatReturnModel $returns;
    protected VatReturnService $service;
    protected TaxReportService $taxReports;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->returns    = new VatReturnModel();
        $this->service    = new VatReturnService();
        $this->taxReports = new TaxReportService();
    }

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

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

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

    public function createForm()
    {
        return view('Modules\Accounting\Views\vat_returns\create', array_merge($this->baseViewData(), [
            'title' => 'New VAT Return',
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'period_from' => 'required|valid_date',
            'period_to'   => '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/vat-returns/' . $result['id'])->with('success', 'VAT return created.');
    }

    public function show(int $id)
    {
        $row = $this->returns->find($id);
        if (! $row) {
            return redirect()->to('/accounting/vat-returns')->with('error', 'VAT return not found.');
        }

        $breakdown = $this->taxReports->summary($row['period_from'], $row['period_to']);

        return view('Modules\Accounting\Views\vat_returns\show', array_merge($this->baseViewData(), [
            'title'     => 'VAT Return',
            'return'    => $row,
            'breakdown' => $breakdown,
        ]));
    }

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

        return view('Modules\Accounting\Views\vat_returns\edit', array_merge($this->baseViewData(), [
            'title'  => 'Edit VAT Return',
            'return' => $row,
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'period_from' => 'required|valid_date',
            'period_to'   => '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/vat-returns/' . $id)->with('success', 'VAT return updated.');
    }

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

        return redirect()->back()->with('success', 'VAT amounts recalculated.');
    }

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

        return redirect()->back()->with('success', 'VAT return submitted.');
    }

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

        return redirect()->back()->with('success', 'VAT return filed.');
    }

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

        return redirect()->to('/accounting/vat-returns/' . $id)->with('success', 'VAT return cancelled.');
    }

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

        return redirect()->to('/accounting/vat-returns')->with('success', 'VAT return deleted.');
    }
}
