<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\InvoiceModel;
use Modules\Sale\Services\InvoiceService;

class PaymentStatusController extends BaseController
{
    protected InvoiceModel $invoices;
    protected InvoiceService $service;
    protected CompanyModel $companies;

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

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

        $builder = $this->invoices->scopeForList($search ?: null, $status, $companyId ? (int) $companyId : null);
        if (! $status) {
            $builder->whereIn('invoices.status', ['issued', 'partially_paid', 'paid', 'overdue']);
        }

        $invoices = $builder
            ->orderBy('invoices.due_date', 'ASC')
            ->orderBy('invoices.id', 'DESC')
            ->findAll();

        return view('Modules\Sale\Views\payment_status\index', array_merge($this->baseViewData(), [
            'title'     => 'Payment Status',
            'invoices'  => $invoices,
            'companies' => $this->companies->getActive(),
            'filters'   => compact('search', 'status', 'companyId'),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'amount_paid' => 'required|decimal',
        ])) {
            return redirect()->back()->with('error', 'Invalid payment amount.');
        }

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

        return redirect()->back()->with('success', 'Payment status updated.');
    }
}
