<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\DebitNoteLineModel;
use App\Models\DebitNoteModel;
use App\Models\SupplierBillModel;
use App\Models\SupplierModel;
use Modules\Accounting\Services\DebitNoteService;

class DebitNoteController extends BaseController
{
    protected DebitNoteModel $notes;
    protected DebitNoteLineModel $lines;
    protected DebitNoteService $service;
    protected SupplierModel $suppliers;
    protected SupplierBillModel $bills;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->notes     = new DebitNoteModel();
        $this->lines     = new DebitNoteLineModel();
        $this->service   = new DebitNoteService();
        $this->suppliers = new SupplierModel();
        $this->bills     = new SupplierBillModel();
    }

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

        $notes = $this->notes
            ->scopeForList($search ?: null, $status, $supplierId ? (int) $supplierId : null)
            ->orderBy('debit_notes.debit_date', 'DESC')
            ->orderBy('debit_notes.id', 'DESC')
            ->findAll();

        return view('Modules\Accounting\Views\debit_notes\index', array_merge($this->baseViewData(), [
            'title'     => 'Debit Notes',
            'notes'     => $notes,
            'suppliers' => $this->suppliers->getActive(),
            'filters'   => compact('search', 'status', 'supplierId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Accounting\Views\debit_notes\create', array_merge($this->baseViewData(), [
            'title'     => 'New Debit Note',
            'suppliers' => $this->suppliers->getActive(),
            'bills'     => $this->bills->scopeOutstanding()->orderBy('supplier_bills.bill_date', 'DESC')->findAll(),
            'lines'     => [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'supplier_id' => 'required|is_natural_no_zero',
            'debit_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/debit-notes/' . $result['id'])->with('success', 'Debit note created.');
    }

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

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

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

        $bills = $this->bills->scopeOutstanding()->orderBy('supplier_bills.bill_date', 'DESC')->findAll();
        if (! empty($note['supplier_bill_id'])) {
            $linkedId = (int) $note['supplier_bill_id'];
            $found = false;
            foreach ($bills as $b) {
                if ((int) $b['id'] === $linkedId) {
                    $found = true;
                    break;
                }
            }
            if (! $found) {
                $linked = (new SupplierBillModel())->scopeForList()->where('supplier_bills.id', $linkedId)->first();
                if ($linked) {
                    array_unshift($bills, $linked);
                }
            }
        }

        return view('Modules\Accounting\Views\debit_notes\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Debit Note',
            'note'      => $note,
            'suppliers' => $this->suppliers->getActive(),
            'bills'     => $bills,
            'lines'     => $this->lines->getForNote($id) ?: [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'supplier_id' => 'required|is_natural_no_zero',
            'debit_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/debit-notes/' . $id)->with('success', 'Debit 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', 'Debit 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', 'Debit 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/debit-notes')->with('error', $result['error']);
        }

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