<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\PurchaseRequestModel;
use App\Models\RfqLineModel;
use App\Models\RfqModel;
use App\Models\RfqSupplierModel;
use App\Models\SupplierModel;
use Modules\Procurement\Services\RfqService;

class RfqController extends BaseController
{
    protected RfqModel $rfqs;
    protected RfqLineModel $lines;
    protected RfqSupplierModel $rfqSuppliers;
    protected RfqService $service;
    protected SupplierModel $suppliers;
    protected PurchaseRequestModel $purchaseRequests;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->rfqs             = new RfqModel();
        $this->lines            = new RfqLineModel();
        $this->rfqSuppliers     = new RfqSupplierModel();
        $this->service          = new RfqService();
        $this->suppliers        = new SupplierModel();
        $this->purchaseRequests = new PurchaseRequestModel();
    }

    public function index()
    {
        $search = trim((string) $this->request->getGet('q'));
        $status = $this->request->getGet('status') ?: null;

        $rfqs = $this->rfqs
            ->scopeForList($search ?: null, $status)
            ->orderBy('rfqs.rfq_date', 'DESC')
            ->orderBy('rfqs.id', 'DESC')
            ->findAll();

        return view('Modules\Procurement\Views\rfqs\index', array_merge($this->baseViewData(), [
            'title'   => 'RFQs',
            'rfqs'    => $rfqs,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Procurement\Views\rfqs\create', array_merge($this->baseViewData(), [
            'title'            => 'New RFQ',
            'suppliers'        => $this->suppliers->getActive(),
            'purchaseRequests' => $this->approvedPurchaseRequests(),
            'selectedSupplierIds' => old('supplier_ids', []) ?: [],
            'lines'            => [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'rfq_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/rfqs')->with('success', 'RFQ created.');
    }

    public function fromRequest(int $id)
    {
        $result = $this->service->createFromPurchaseRequest($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error'] ?? 'Could not create RFQ from purchase request.');
        }

        return redirect()->to('/procurement/rfqs/' . $result['id'] . '/edit')
            ->with('success', 'RFQ created from purchase request.');
    }

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

        return view('Modules\Procurement\Views\rfqs\edit', array_merge($this->baseViewData(), [
            'title'               => 'Edit RFQ',
            'rfq'                 => $rfq,
            'suppliers'           => $this->suppliers->getActive(),
            'purchaseRequests'    => $this->approvedPurchaseRequests($rfq['purchase_request_id'] ?? null),
            'selectedSupplierIds' => old('supplier_ids') ?: $this->rfqSuppliers->getSupplierIdsForRfq($id),
            'lines'               => $this->lines->getForRfq($id) ?: [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'rfq_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/rfqs')->with('success', 'RFQ 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', 'RFQ 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', 'RFQ 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', 'RFQ rejected.');
    }

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

        return redirect()->back()->with('success', 'RFQ marked as sent.');
    }

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

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

        return redirect()->to('/procurement/rfqs')->with('success', 'RFQ deleted.');
    }

    /**
     * Approved PRs for linking, plus the currently linked PR if it is no longer approved.
     */
    protected function approvedPurchaseRequests($includeId = null): array
    {
        $rows = $this->purchaseRequests
            ->where('status', 'approved')
            ->orderBy('number', 'ASC')
            ->findAll();

        if ($includeId) {
            $includeId = (int) $includeId;
            $found = false;
            foreach ($rows as $row) {
                if ((int) $row['id'] === $includeId) {
                    $found = true;
                    break;
                }
            }
            if (! $found) {
                $linked = $this->purchaseRequests->find($includeId);
                if ($linked) {
                    array_unshift($rows, $linked);
                }
            }
        }

        return $rows;
    }
}
