<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use Modules\Procurement\Services\ApprovalQueueService;

class ApprovalQueueController extends BaseController
{
    protected ApprovalQueueService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->service = new ApprovalQueueService();
    }

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

        return view('Modules\Procurement\Views\approval_queue\index', array_merge($this->baseViewData(), [
            'title'   => 'Approval Queue',
            'items'   => $items,
            'filters' => compact('search'),
        ]));
    }

    public function approve()
    {
        $type = (string) $this->request->getPost('type');
        $id   = (int) $this->request->getPost('id');

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

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

    public function reject()
    {
        $type   = (string) $this->request->getPost('type');
        $id     = (int) $this->request->getPost('id');
        $reason = (string) $this->request->getPost('rejection_reason');

        $result = $this->service->reject($type, $id, $reason, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error'] ?? 'Rejection failed.');
        }

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