<?php

class DeliveryController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('delivery', 'view');

        $deliveryModel = new Delivery();
        $board = $deliveryModel->board();

        $status = $this->input('status', 'ALL');
        $search = trim(mb_strtolower($this->input('search', '')));

        $filtered = $board;
        if ($search !== '') {
            foreach ($filtered as $key => $items) {
                $filtered[$key] = array_values(array_filter($items, function ($d) use ($search) {
                    return str_contains(mb_strtolower($d['order_number']), $search)
                        || str_contains(mb_strtolower($d['customer_name'] ?? ''), $search)
                        || str_contains(mb_strtolower($d['customer_phone'] ?? ''), $search)
                        || str_contains(mb_strtolower($d['rider_name'] ?? ''), $search);
                }));
            }
        }

        $counts = [];
        foreach ($board as $key => $items) {
            $counts[$key] = count($items);
        }
        $counts['ALL'] = array_sum($counts);

        $this->view('delivery.index', [
            'pageTitle'    => 'Delivery',
            'board'        => $filtered,
            'counts'       => $counts,
            'activeStatus' => $status,
            'search'       => $this->input('search', ''),
        ]);
    }

    public function assign(): void
    {
        Auth::requirePermission('delivery', 'edit');
        $this->verifyCsrf();

        $deliveryId = (int) $this->input('id');
        $riderId = (int) $this->input('rider_id');
        if ($deliveryId > 0 && $riderId > 0) {
            (new Delivery())->assignRider($deliveryId, $riderId, Auth::id());
        }
        $this->redirect('delivery');
    }

    public function pickedUp(): void
    {
        Auth::requirePermission('delivery', 'edit');
        $this->verifyCsrf();

        $deliveryId = (int) $this->input('id');
        (new Delivery())->markPickedUp($deliveryId, Auth::id());
        $this->redirect('delivery');
    }

    public function delivered(): void
    {
        Auth::requirePermission('delivery', 'edit');
        $this->verifyCsrf();

        $deliveryId = (int) $this->input('id');
        (new Delivery())->markDelivered($deliveryId, Auth::id());
        $this->redirect('delivery');
    }

    public function failed(): void
    {
        Auth::requirePermission('delivery', 'edit');
        $this->verifyCsrf();

        $deliveryId = (int) $this->input('id');
        $notes = trim($this->input('notes', ''));
        (new Delivery())->markFailed($deliveryId, $notes ?: 'Delivery failed', Auth::id());
        $this->redirect('delivery');
    }
}