<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\DeliveryModel;
use Modules\Sale\Services\DeliveryService;

class DispatchController extends BaseController
{
    protected DeliveryModel $deliveries;
    protected DeliveryService $service;

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

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

        $deliveries = $this->deliveries
            ->scopeForList($search ?: null, null)
            ->whereIn('deliveries.status', ['ready', 'draft'])
            ->orderBy('deliveries.delivery_date', 'ASC')
            ->findAll();

        return view('Modules\Sale\Views\dispatch\index', array_merge($this->baseViewData(), [
            'title'      => 'Dispatch',
            'deliveries' => $deliveries,
            'filters'    => compact('search'),
        ]));
    }

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

        return redirect()->back()->with('success', 'Delivery dispatched.');
    }
}
