<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\CustomerInvoiceModel;
use App\Models\CustomerReceiptModel;
use Modules\Accounting\Services\CustomerReceiptService;

class ReceiptController extends BaseController
{
    protected CustomerReceiptModel $receipts;
    protected CustomerReceiptService $service;
    protected CompanyModel $companies;
    protected CustomerInvoiceModel $invoices;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->receipts  = new CustomerReceiptModel();
        $this->service   = new CustomerReceiptService();
        $this->companies = new CompanyModel();
        $this->invoices  = new CustomerInvoiceModel();
    }

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

        $receipts = $this->receipts
            ->scopeForList($search ?: null, $status, $companyId ? (int) $companyId : null)
            ->orderBy('customer_receipts.receipt_date', 'DESC')
            ->orderBy('customer_receipts.id', 'DESC')
            ->findAll();

        return view('Modules\Accounting\Views\receipts\index', array_merge($this->baseViewData(), [
            'title'     => 'Receipts',
            'receipts'  => $receipts,
            'companies' => $this->companies->getActive(),
            'filters'   => compact('search', 'status', 'companyId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Accounting\Views\receipts\create', array_merge($this->baseViewData(), [
            'title'     => 'New Receipt',
            'companies' => $this->companies->getActive(),
            'invoices'  => $this->invoices->scopeOutstanding()->orderBy('customer_invoices.invoice_date', 'DESC')->findAll(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'company_id'   => 'required|is_natural_no_zero',
            'receipt_date' => 'required|valid_date',
            'amount'       => 'required|decimal',
        ])) {
            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/receipts/' . $result['id'])->with('success', 'Receipt created.');
    }

    public function show(int $id)
    {
        $receipt = $this->receipts->scopeForList()->where('customer_receipts.id', $id)->first();
        if (! $receipt) {
            return redirect()->to('/accounting/receipts')->with('error', 'Receipt not found.');
        }

        return view('Modules\Accounting\Views\receipts\show', array_merge($this->baseViewData(), [
            'title'   => 'Receipt',
            'receipt' => $receipt,
        ]));
    }

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

        $invoices = $this->invoices->scopeOutstanding()->orderBy('customer_invoices.invoice_date', 'DESC')->findAll();
        if (! empty($receipt['customer_invoice_id'])) {
            $linkedId = (int) $receipt['customer_invoice_id'];
            $found = false;
            foreach ($invoices as $inv) {
                if ((int) $inv['id'] === $linkedId) {
                    $found = true;
                    break;
                }
            }
            if (! $found) {
                $linked = (new CustomerInvoiceModel())->scopeForList()->where('customer_invoices.id', $linkedId)->first();
                if ($linked) {
                    array_unshift($invoices, $linked);
                }
            }
        }

        return view('Modules\Accounting\Views\receipts\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Receipt',
            'receipt'   => $receipt,
            'companies' => $this->companies->getActive(),
            'invoices'  => $invoices,
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'company_id'   => 'required|is_natural_no_zero',
            'receipt_date' => 'required|valid_date',
            'amount'       => 'required|decimal',
        ])) {
            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/receipts/' . $id)->with('success', 'Receipt 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', 'Receipt posted.');
    }

    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()->back()->with('success', 'Receipt cancelled.');
    }

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

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