<?php

namespace App\Filament\Resources\BranchResource\RelationManagers;

use App\Models\Account;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;

class AccountsRelationManager extends RelationManager
{
    protected static string $relationship = 'accounts';

    public function getTableQuery(): Builder|Relation|null
    {
        return Account::query()->whereHas('balances', function (Builder $query) {
            $query->where('branch_id', $this->getOwnerRecord()->id);
        });
    }

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

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('branch_id')
            ->columns([
                Tables\Columns\TextColumn::make('account'),
                Tables\Columns\TextColumn::make('branch_id'),
                Tables\Columns\TextColumn::make('normal_balance'),
                Tables\Columns\TextColumn::make('starting_balance'),
                Tables\Columns\TextColumn::make('current_balance'),
            ])
            ->filters([
                //
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make(),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }
}
