<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\QuotationModel;
use Modules\Sale\Services\QuotationService;

class QuotationApprovalController extends BaseController
{
    protected QuotationModel $quotations;
    protected QuotationService $service;

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

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

        $quotations = $this->quotations
            ->scopeForList($search ?: null, 'pending_approval')
            ->orderBy('quotations.quotation_date', 'ASC')
            ->orderBy('quotations.id', 'ASC')
            ->findAll();

        return view('Modules\Sale\Views\quotation_approval\index', array_merge($this->baseViewData(), [
            'title'      => 'Approval Workflow',
            'quotations' => $quotations,
            'filters'    => compact('search'),
        ]));
    }

    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', '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', 'Quotation rejected.');
    }
}
