<?php

namespace App\Filament\Resources\InvoiceResource\RelationManagers;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class OrdersRelationManager extends RelationManager
{
    protected static string $relationship = 'orders';

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('customer_po')
                    ->required()
                    ->maxLength(100),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('customer_po')
            ->columns([
                Tables\Columns\TextColumn::make('customer_po')
                    ->color('code')
                    ->weight('bold')
                    ->extraHeaderAttributes(['class' => 'w-full']),
                Tables\Columns\TextColumn::make('total_product_quantity')
                    ->label('Total QTY')
                    ->alignRight(),
                Tables\Columns\TextColumn::make('total_service_price')
                    ->alignRight()
                    ->label('Total price')
                    ->money('usd'),
            ])
            ->filters([
                //
            ])
            ->headerActions([
                Tables\Actions\AssociateAction::make()
                    ->multiple()
                    ->preloadRecordSelect()
                    ->recordSelectOptionsQuery(fn (Builder $query) => $query->where('customer_id', $this->ownerRecord->customer->id))
                    ->after(function () {
                        $this->ownerRecord->calculateTotals();
                    }),
            ])
            ->actions([
                Tables\Actions\DissociateAction::make()
                    ->after(function () {
                        $this->ownerRecord->calculateTotals();
                    }),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DissociateBulkAction::make(),
                ]),
            ])
            ->inverseRelationship('invoice');
    }
}
