<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\SupplierModel;
use App\Models\SupplierQuotationLineModel;
use App\Models\SupplierQuotationModel;
use Modules\Procurement\Services\PurchaseOrderService;
use Modules\Procurement\Services\SupplierQuotationService;

class SupplierQuotationController extends BaseController
{
    protected SupplierQuotationModel $quotations;
    protected SupplierQuotationLineModel $lines;
    protected SupplierQuotationService $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->quotations = new SupplierQuotationModel();
        $this->lines      = new SupplierQuotationLineModel();
        $this->service    = new SupplierQuotationService();
        $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;

        $quotations = $this->quotations
            ->scopeForList($search ?: null, $status, $supplierId ? (int) $supplierId : null)
            ->orderBy('supplier_quotations.quotation_date', 'DESC')
            ->orderBy('supplier_quotations.id', 'DESC')
            ->findAll();

        return view('Modules\Procurement\Views\supplier_quotations\index', array_merge($this->baseViewData(), [
            'title'      => 'Supplier Quotations',
            'quotations' => $quotations,
            'suppliers'  => $this->suppliers->getActive(),
            'filters'    => compact('search', 'status', 'supplierId'),
        ]));
    }

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

    public function store()
    {
        if (! $this->validate([
            'supplier_id'    => 'required|is_natural_no_zero',
            'quotation_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/supplier-quotations')->with('success', 'Supplier quotation created.');
    }

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

        return view('Modules\Procurement\Views\supplier_quotations\edit', array_merge($this->baseViewData(), [
            'title'      => 'Edit Supplier Quotation',
            'quotation'  => $quotation,
            'suppliers'  => $this->suppliers->getActive(),
            'rfqs'       => $this->listRfqs(),
            'lines'      => $this->lines->getForSupplierQuotation($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',
            'quotation_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/supplier-quotations')->with('success', 'Supplier quotation 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', 'Supplier quotation 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', 'Supplier quotation 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', 'Supplier quotation rejected.');
    }

    public function convert(int $id)
    {
        $orderService = new PurchaseOrderService();
        $result = $orderService->createFromSupplierQuotation($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error'] ?? 'Could not convert supplier quotation.');
        }

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

    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 quotation cancelled.');
    }

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

        return redirect()->to('/procurement/supplier-quotations')->with('success', 'Supplier quotation deleted.');
    }

    protected function listRfqs(): array
    {
        return db_connect()->table('rfqs')
            ->select('id, number, status')
            ->orderBy('number', 'DESC')
            ->get()
            ->getResultArray();
    }
}
