<?php

namespace Modules\Sale\Controllers;

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

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

        $builder = $this->orders->scopeForList($search ?: null, $status);
        if (! $status) {
            $builder->whereIn('sales_orders.status', ['approved', 'confirmed', 'in_progress', 'fulfilled']);
        }

        $orders = $builder
            ->orderBy('sales_orders.order_date', 'DESC')
            ->findAll();

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

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

        $result = $this->service->updateTracking(
            $id,
            (string) $this->request->getPost('status'),
            $this->request->getPost('tracking_notes'),
            (int) $this->session->get('user_id')
        );

        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Order tracking updated.');
    }
}
