<?php

namespace App\Filament\Resources\TintoreriaResource\RelationManagers;

use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;

class CobrosRelationManager extends RelationManager
{
    protected static string $relationship = 'cobros';
    protected static ?string $recordTitleAttribute = 'id';

    public function table(Tables\Table $table): Tables\Table
    {
        return $table
            ->columns([
                TextColumn::make('id')->label('#'),
                TextColumn::make('cantidad')->label('Cantidad'),
                TextColumn::make('valor')->label('Valor')->money('USD'),
                TextColumn::make('usuario.name')->label('Usuario'),
                TextColumn::make('notas')->limit(80)->wrap(),
                TextColumn::make('created_at')->label('Fecha')->dateTime(),
            ])
            ->filters([])
            ->headerActions([
                Tables\Actions\CreateAction::make()->form([
                    \Filament\Forms\Components\TextInput::make('cantidad')->numeric()->required()->minValue(1),
                    \Filament\Forms\Components\TextInput::make('valor')->numeric()->required()->minValue(0),
                    \Filament\Forms\Components\Textarea::make('notas'),
                ])->action(function (array $data) {
                    $owner = $this->getOwnerRecord();
                    try {
                        $owner->registerCobro((int)$data['cantidad'], (float)$data['valor'], $data['notas'] ?? null, auth()->id() ?? null);
                        \Filament\Notifications\Notification::make()->success()->title('Cobro registrado')->send();
                    } catch (\Throwable $e) {
                        \Filament\Notifications\Notification::make()->danger()->title('Error')->body($e->getMessage())->send();
                    }
                }),
            ])
            ->actions([])
            ->bulkActions([]);
    }
}
