<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\PurchaseOrderLineModel;
use App\Models\PurchaseOrderModel;
use App\Models\SupplierModel;
use Modules\Procurement\Services\PurchaseOrderService;

class PurchaseOrderController extends BaseController
{
    protected PurchaseOrderModel $orders;
    protected PurchaseOrderLineModel $lines;
    protected PurchaseOrderService $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->orders    = new PurchaseOrderModel();
        $this->lines     = new PurchaseOrderLineModel();
        $this->service   = new PurchaseOrderService();
        $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;

        $orders = $this->orders
            ->scopeForList($search ?: null, $status, $supplierId ? (int) $supplierId : null)
            ->orderBy('purchase_orders.order_date', 'DESC')
            ->orderBy('purchase_orders.id', 'DESC')
            ->findAll();

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

    public function createForm()
    {
        return view('Modules\Procurement\Views\purchase_orders\create', array_merge($this->baseViewData(), [
            'title'     => 'New Purchase Order',
            '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',
            'order_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-orders')->with('success', 'Purchase order created.');
    }

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

        return view('Modules\Procurement\Views\purchase_orders\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Purchase Order',
            'order'     => $order,
            'suppliers' => $this->suppliers->getActive(),
            'lines'     => $this->lines->getForPurchaseOrder($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',
            'order_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-orders')->with('success', 'Purchase order updated.');
    }

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

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

    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 order approved.');
    }

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

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

    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 order 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-orders')->with('error', $result['error']);
        }

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