<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\SupplierBillLineModel;
use App\Models\SupplierBillModel;
use App\Models\SupplierModel;
use Modules\Accounting\Services\SupplierBillService;

class SupplierBillController extends BaseController
{
    protected SupplierBillModel $bills;
    protected SupplierBillLineModel $lines;
    protected SupplierBillService $service;
    protected SupplierModel $suppliers;

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

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

        $bills = $this->bills
            ->scopeForList($search ?: null, $status, $supplierId ? (int) $supplierId : null)
            ->orderBy('supplier_bills.bill_date', 'DESC')
            ->orderBy('supplier_bills.id', 'DESC')
            ->findAll();

        return view('Modules\Accounting\Views\supplier_bills\index', array_merge($this->baseViewData(), [
            'title'     => 'Supplier Bills',
            'bills'     => $bills,
            'suppliers' => $this->suppliers->getActive(),
            'filters'   => compact('search', 'status', 'supplierId'),
        ]));
    }

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

    public function store()
    {
        if (! $this->validate([
            'supplier_id' => 'required|is_natural_no_zero',
            'bill_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/supplier-bills/' . $result['id'])->with('success', 'Supplier bill created.');
    }

    public function show(int $id)
    {
        $bill = $this->bills->scopeForList()->where('supplier_bills.id', $id)->first();
        if (! $bill) {
            return redirect()->to('/accounting/supplier-bills')->with('error', 'Supplier bill not found.');
        }

        return view('Modules\Accounting\Views\supplier_bills\show', array_merge($this->baseViewData(), [
            'title' => 'Supplier Bill',
            'bill'  => $bill,
            'lines' => $this->lines->getForBill($id),
        ]));
    }

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

        return view('Modules\Accounting\Views\supplier_bills\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Supplier Bill',
            'bill'      => $bill,
            'suppliers' => $this->suppliers->getActive(),
            'lines'     => $this->lines->getForBill($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',
            'bill_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/supplier-bills/' . $id)->with('success', 'Supplier bill 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', 'Supplier bill 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', 'Supplier bill cancelled.');
    }

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

        return redirect()->to('/accounting/supplier-bills')->with('success', 'Supplier bill deleted.');
    }
}
