<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\CustomerInvoiceLineModel;
use App\Models\CustomerInvoiceModel;
use Modules\Accounting\Services\CustomerInvoiceService;

class CustomerInvoiceController extends BaseController
{
    protected CustomerInvoiceModel $invoices;
    protected CustomerInvoiceLineModel $lines;
    protected CustomerInvoiceService $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 CustomerInvoiceModel();
        $this->lines     = new CustomerInvoiceLineModel();
        $this->service   = new CustomerInvoiceService();
        $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;

        $invoices = $this->invoices
            ->scopeForList($search ?: null, $status, $companyId ? (int) $companyId : null)
            ->orderBy('customer_invoices.invoice_date', 'DESC')
            ->orderBy('customer_invoices.id', 'DESC')
            ->findAll();

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

    public function createForm()
    {
        return view('Modules\Accounting\Views\customer_invoices\create', array_merge($this->baseViewData(), [
            'title'     => 'New Customer Invoice',
            'companies' => $this->companies->getActive(),
            'lines'     => [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'company_id'   => 'required|is_natural_no_zero',
            'invoice_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/customer-invoices/' . $result['id'])->with('success', 'Customer invoice created.');
    }

    public function show(int $id)
    {
        $invoice = $this->invoices->scopeForList()->where('customer_invoices.id', $id)->first();
        if (! $invoice) {
            return redirect()->to('/accounting/customer-invoices')->with('error', 'Customer invoice not found.');
        }

        return view('Modules\Accounting\Views\customer_invoices\show', array_merge($this->baseViewData(), [
            'title'   => 'Customer Invoice',
            'invoice' => $invoice,
            'lines'   => $this->lines->getForInvoice($id),
        ]));
    }

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

        return view('Modules\Accounting\Views\customer_invoices\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Customer Invoice',
            'invoice'   => $invoice,
            'companies' => $this->companies->getActive(),
            'lines'     => $this->lines->getForInvoice($id) ?: [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'company_id'   => 'required|is_natural_no_zero',
            'invoice_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/customer-invoices/' . $id)->with('success', 'Customer invoice 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', 'Customer invoice 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', 'Customer invoice cancelled.');
    }

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

        return redirect()->to('/accounting/customer-invoices')->with('success', 'Customer invoice deleted.');
    }
}
