<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\GoodsReceiptLineModel;
use App\Models\GoodsReceiptModel;
use App\Models\PurchaseOrderModel;
use App\Models\SupplierModel;
use Modules\Procurement\Services\GoodsReceiptService;

class GoodsReceiptController extends BaseController
{
    protected GoodsReceiptModel $receipts;
    protected GoodsReceiptLineModel $lines;
    protected GoodsReceiptService $service;
    protected PurchaseOrderModel $orders;
    protected SupplierModel $suppliers;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->receipts  = new GoodsReceiptModel();
        $this->lines     = new GoodsReceiptLineModel();
        $this->service   = new GoodsReceiptService();
        $this->orders    = new PurchaseOrderModel();
        $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;

        $receipts = $this->receipts
            ->scopeForList($search ?: null, $status, $supplierId ? (int) $supplierId : null)
            ->orderBy('goods_receipts.receipt_date', 'DESC')
            ->orderBy('goods_receipts.id', 'DESC')
            ->findAll();

        return view('Modules\Procurement\Views\goods_receipts\index', array_merge($this->baseViewData(), [
            'title'     => 'Goods Receipts',
            'receipts'  => $receipts,
            'suppliers' => $this->suppliers->getActive(),
            'filters'   => compact('search', 'status', 'supplierId'),
        ]));
    }

    public function createForm()
    {
        $orders = $this->orders
            ->whereIn('status', ['approved', 'confirmed'])
            ->orderBy('order_date', 'DESC')
            ->findAll();

        return view('Modules\Procurement\Views\goods_receipts\create', array_merge($this->baseViewData(), [
            'title'     => 'New Goods Receipt',
            'orders'    => $orders,
            'suppliers' => $this->suppliers->getActive(),
            'lines'     => [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs']],
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'purchase_order_id' => 'required|is_natural_no_zero',
            'receipt_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/goods-receipts')->with('success', 'Goods receipt created.');
    }

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

        return redirect()->to('/procurement/goods-receipts/' . $result['id'] . '/edit')
            ->with('success', 'Goods receipt created from purchase order.');
    }

    public function editForm(int $id)
    {
        $receipt = $this->receipts->find($id);
        if (! $receipt) {
            return redirect()->to('/procurement/goods-receipts')->with('error', 'Goods receipt not found.');
        }
        if ($receipt['status'] !== 'draft') {
            return redirect()->to('/procurement/goods-receipts')->with('error', 'Only draft goods receipts can be edited.');
        }

        $orders = $this->orders
            ->groupStart()
                ->whereIn('status', ['approved', 'confirmed'])
                ->orWhere('id', (int) $receipt['purchase_order_id'])
            ->groupEnd()
            ->orderBy('order_date', 'DESC')
            ->findAll();

        return view('Modules\Procurement\Views\goods_receipts\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Goods Receipt',
            'receipt'   => $receipt,
            'orders'    => $orders,
            'suppliers' => $this->suppliers->getActive(),
            'lines'     => $this->lines->getForGoodsReceipt($id) ?: [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs']],
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'purchase_order_id' => 'required|is_natural_no_zero',
            'receipt_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/goods-receipts')->with('success', 'Goods receipt 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', 'Goods receipt 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', 'Goods receipt cancelled.');
    }

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

        return redirect()->to('/procurement/goods-receipts')->with('success', 'Goods receipt deleted.');
    }
}
