<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\GoodsReceiptModel;
use App\Models\PurchaseOrderModel;
use App\Models\SupplierModel;
use App\Models\VendorBillLineModel;
use App\Models\VendorBillModel;
use Modules\Procurement\Services\VendorBillService;

class VendorBillController extends BaseController
{
    protected VendorBillModel $bills;
    protected VendorBillLineModel $lines;
    protected VendorBillService $service;
    protected SupplierModel $suppliers;
    protected PurchaseOrderModel $orders;
    protected GoodsReceiptModel $receipts;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->bills     = new VendorBillModel();
        $this->lines     = new VendorBillLineModel();
        $this->service   = new VendorBillService();
        $this->suppliers = new SupplierModel();
        $this->orders    = new PurchaseOrderModel();
        $this->receipts  = new GoodsReceiptModel();
    }

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

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

    public function createForm()
    {
        return view('Modules\Procurement\Views\vendor_bills\create', array_merge($this->baseViewData(), [
            'title'     => 'New Vendor Bill',
            'suppliers' => $this->suppliers->getActive(),
            'orders'    => $this->orders->whereNotIn('status', ['draft', 'cancelled'])->orderBy('order_date', 'DESC')->findAll(),
            'receipts'  => $this->receipts->where('status', 'posted')->orderBy('receipt_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',
            '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('/procurement/vendor-bills')->with('success', 'Vendor bill created.');
    }

    public function editForm(int $id)
    {
        $bill = $this->bills->find($id);
        if (! $bill) {
            return redirect()->to('/procurement/vendor-bills')->with('error', 'Vendor bill not found.');
        }

        return view('Modules\Procurement\Views\vendor_bills\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Vendor Bill',
            'bill'      => $bill,
            'suppliers' => $this->suppliers->getActive(),
            'orders'    => $this->orders->whereNotIn('status', ['draft', 'cancelled'])->orderBy('order_date', 'DESC')->findAll(),
            'receipts'  => $this->receipts->where('status', 'posted')->orderBy('receipt_date', 'DESC')->findAll(),
            '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('/procurement/vendor-bills')->with('success', 'Vendor bill 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', 'Vendor bill 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', 'Vendor bill cancelled.');
    }

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

        return redirect()->to('/procurement/vendor-bills')->with('success', 'Vendor bill deleted.');
    }
}
