<?php

namespace Modules\Sale\Controllers;

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

class InvoiceController extends BaseController
{
    protected InvoiceModel $invoices;
    protected InvoiceLineModel $lines;
    protected InvoiceService $service;
    protected CompanyModel $companies;
    protected SalesOrderModel $orders;

    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->lines     = new InvoiceLineModel();
        $this->service   = new InvoiceService();
        $this->companies = new CompanyModel();
        $this->orders    = new SalesOrderModel();
    }

    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('invoices.invoice_date', 'DESC')
            ->orderBy('invoices.id', 'DESC')
            ->findAll();

        return view('Modules\Sale\Views\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\Sale\Views\invoices\create', array_merge($this->baseViewData(), [
            'title'     => 'New Invoice',
            'companies' => $this->companies->getActive(),
            'orders'    => $this->orders->whereIn('status', ['approved', 'confirmed', 'in_progress', 'fulfilled'])->orderBy('order_date', 'DESC')->findAll(),
            '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('/sale/invoices')->with('success', 'Invoice created.');
    }

    public function createFromOrder(int $orderId)
    {
        $result = $this->service->createFromOrder($orderId, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error'] ?? 'Could not create invoice.');
        }

        return redirect()->to('/sale/invoices/' . $result['id'] . '/edit')->with('success', 'Invoice created from sales order.');
    }

    public function editForm(int $id)
    {
        $invoice = $this->invoices->find($id);
        if (! $invoice) {
            return redirect()->to('/sale/invoices')->with('error', 'Invoice not found.');
        }

        return view('Modules\Sale\Views\invoices\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Invoice',
            'invoice'   => $invoice,
            'companies' => $this->companies->getActive(),
            'orders'    => $this->orders->whereIn('status', ['approved', 'confirmed', 'in_progress', 'fulfilled'])->orderBy('order_date', 'DESC')->findAll(),
            '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('/sale/invoices')->with('success', 'Invoice updated.');
    }

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

        return redirect()->back()->with('success', 'Invoice issued.');
    }

    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', 'Invoice cancelled.');
    }

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

        return redirect()->to('/sale/invoices')->with('success', 'Invoice deleted.');
    }
}
