<?php

namespace App\Filament\Resources\Branches\RelationManagers;

use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\CreateAction;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use App\Models\Account;
use Filament\Forms;
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(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('branch_id')
                    ->required()
                    ->maxLength(255),
            ]);
    }

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