<?php

namespace Modules\Sale\Controllers;

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

class DeliveryTrackingController 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'));
        $status = $this->request->getGet('status') ?: null;

        $builder = $this->deliveries->scopeForList($search ?: null, $status);
        if (! $status) {
            $builder->whereIn('deliveries.status', ['dispatched', 'in_transit', 'delivered']);
        }

        $deliveries = $builder
            ->orderBy('deliveries.delivery_date', 'DESC')
            ->findAll();

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

    public function update(int $id)
    {
        if (! $this->validate([
            'status' => 'required|in_list[dispatched,in_transit,delivered,cancelled]',
        ])) {
            return redirect()->back()->with('error', 'Invalid tracking status.');
        }

        $result = $this->service->updateTracking(
            $id,
            (string) $this->request->getPost('status'),
            $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 tracking updated.');
    }
}
