<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\CreditNoteLineModel;
use App\Models\CreditNoteModel;
use App\Models\CustomerInvoiceModel;
use Modules\Accounting\Services\CreditNoteService;

class CreditNoteController extends BaseController
{
    protected CreditNoteModel $notes;
    protected CreditNoteLineModel $lines;
    protected CreditNoteService $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->notes     = new CreditNoteModel();
        $this->lines     = new CreditNoteLineModel();
        $this->service   = new CreditNoteService();
        $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;

        $notes = $this->notes
            ->scopeForList($search ?: null, $status, $companyId ? (int) $companyId : null)
            ->orderBy('credit_notes.credit_date', 'DESC')
            ->orderBy('credit_notes.id', 'DESC')
            ->findAll();

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

    public function createForm()
    {
        return view('Modules\Accounting\Views\credit_notes\create', array_merge($this->baseViewData(), [
            'title'     => 'New Credit Note',
            'companies' => $this->companies->getActive(),
            'invoices'  => $this->invoices->scopeOutstanding()->orderBy('customer_invoices.invoice_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',
            'credit_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/credit-notes/' . $result['id'])->with('success', 'Credit note created.');
    }

    public function show(int $id)
    {
        $note = $this->notes->scopeForList()->where('credit_notes.id', $id)->first();
        if (! $note) {
            return redirect()->to('/accounting/credit-notes')->with('error', 'Credit note not found.');
        }

        return view('Modules\Accounting\Views\credit_notes\show', array_merge($this->baseViewData(), [
            'title' => 'Credit Note',
            'note'  => $note,
            'lines' => $this->lines->getForNote($id),
        ]));
    }

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

        $invoices = $this->invoices->scopeOutstanding()->orderBy('customer_invoices.invoice_date', 'DESC')->findAll();
        if (! empty($note['customer_invoice_id'])) {
            $linkedId = (int) $note['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\credit_notes\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Credit Note',
            'note'      => $note,
            'companies' => $this->companies->getActive(),
            'invoices'  => $invoices,
            'lines'     => $this->lines->getForNote($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',
            'credit_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/credit-notes/' . $id)->with('success', 'Credit note 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', 'Credit note 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', 'Credit note cancelled.');
    }

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

        return redirect()->to('/accounting/credit-notes')->with('success', 'Credit note deleted.');
    }
}
