<?php

namespace App\Filament\Resources\Orders\RelationManagers;

use App\Filament\Resources\DeliveryAssignments\DeliveryAssignmentActions;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;

/**
 * Shows an order's delivery assignments (one per vendor) right on the order
 * edit page, with the same Assign-courier / Mark-delivered override actions
 * as the standalone Deliveries resource.
 */
class DeliveryAssignmentsRelationManager extends RelationManager
{
    protected static string $relationship = 'deliveryAssignments';

    protected static ?string $title = 'Deliveries';

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('id')
            ->columns([
                TextColumn::make('stops_count')->counts('stops')->label('Stores')->badge(),
                TextColumn::make('partner.name')->label('Courier')->placeholder('— unassigned'),
                TextColumn::make('status')->badge()
                    ->formatStateUsing(fn($state) => ucwords(str_replace('_', ' ', (string) $state)))
                    ->color(fn($state) => match ($state) {
                        'delivered'               => 'success',
                        'cancelled'               => 'danger',
                        'pending_assignment'      => 'warning',
                        'offered'                 => 'info',
                        'picked_up', 'on_the_way' => 'primary',
                        default                   => 'gray',
                    }),
                TextColumn::make('cod_amount')->label('COD')->money('PKR'),
                TextColumn::make('partner_earning')->label('Rider fee')->money('PKR'),
            ])
            ->recordActions([
                DeliveryAssignmentActions::assignCourier(),
                DeliveryAssignmentActions::markDelivered(),
                DeliveryAssignmentActions::markReturned(),
            ]);
    }
}
