<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\GoodsReceiptModel;
use App\Models\PurchaseOrderModel;
use App\Models\PurchaseReturnLineModel;
use App\Models\PurchaseReturnModel;
use App\Models\SupplierModel;
use Modules\Procurement\Services\PurchaseReturnService;

class PurchaseReturnController extends BaseController
{
    protected PurchaseReturnModel $returns;
    protected PurchaseReturnLineModel $lines;
    protected PurchaseReturnService $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->returns   = new PurchaseReturnModel();
        $this->lines     = new PurchaseReturnLineModel();
        $this->service   = new PurchaseReturnService();
        $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;

        $returns = $this->returns
            ->scopeForList($search ?: null, $status, $supplierId ? (int) $supplierId : null)
            ->orderBy('purchase_returns.return_date', 'DESC')
            ->orderBy('purchase_returns.id', 'DESC')
            ->findAll();

        return view('Modules\Procurement\Views\purchase_returns\index', array_merge($this->baseViewData(), [
            'title'     => 'Purchase Returns',
            'returns'   => $returns,
            'suppliers' => $this->suppliers->getActive(),
            'filters'   => compact('search', 'status', 'supplierId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Procurement\Views\purchase_returns\create', array_merge($this->baseViewData(), [
            'title'     => 'New Purchase Return',
            'suppliers' => $this->suppliers->getActive(),
            'orders'    => $this->orders->whereIn('status', ['approved', 'confirmed'])->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',
            'return_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/purchase-returns')->with('success', 'Purchase return created.');
    }

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

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

        $receipts = $this->receipts
            ->groupStart()
                ->where('status', 'posted')
                ->orWhere('id', (int) ($return['goods_receipt_id'] ?? 0))
            ->groupEnd()
            ->orderBy('receipt_date', 'DESC')
            ->findAll();

        return view('Modules\Procurement\Views\purchase_returns\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Purchase Return',
            'return'    => $return,
            'suppliers' => $this->suppliers->getActive(),
            'orders'    => $orders,
            'receipts'  => $receipts,
            'lines'     => $this->lines->getForReturn($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',
            'return_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/purchase-returns')->with('success', 'Purchase return updated.');
    }

    public function submit(int $id)
    {
        $result = $this->service->submit($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Purchase return submitted.');
    }

    public function approve(int $id)
    {
        $result = $this->service->approve($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Purchase return approved.');
    }

    public function complete(int $id)
    {
        $result = $this->service->complete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Purchase return completed.');
    }

    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', 'Purchase return cancelled.');
    }

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

        return redirect()->to('/procurement/purchase-returns')->with('success', 'Purchase return deleted.');
    }
}
