<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\SalesOrderModel;
use Modules\Sale\Services\SalesOrderService;

class OrderApprovalController extends BaseController
{
    protected SalesOrderModel $orders;
    protected SalesOrderService $service;

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

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

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

        return view('Modules\Sale\Views\order_approval\index', array_merge($this->baseViewData(), [
            'title'   => 'Order Approval',
            'orders'  => $orders,
            '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', 'Sales 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', 'Sales order rejected.');
    }
}
