| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199 | <?php
namespace App\Filament\Company\Resources\Accounting;
use App\Filament\Company\Resources\Accounting\BudgetResource\Pages;
use App\Filament\Forms\Components\CustomSection;
use App\Models\Accounting\Account;
use App\Models\Accounting\Budget;
use App\Models\Accounting\BudgetItem;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Carbon;
class BudgetResource extends Resource
{
    protected static ?string $model = Budget::class;
    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Budget Details')
                    ->columns()
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->required()
                            ->maxLength(255),
                        Forms\Components\Select::make('interval_type')
                            ->label('Budget Interval')
                            ->options([
                                'day' => 'Daily',
                                'week' => 'Weekly',
                                'month' => 'Monthly',
                                'quarter' => 'Quarterly',
                                'year' => 'Yearly',
                            ])
                            ->default('month')
                            ->required()
                            ->live(),
                        Forms\Components\DatePicker::make('start_date')
                            ->required()
                            ->default(now()->startOfYear())
                            ->live(),
                        Forms\Components\DatePicker::make('end_date')
                            ->required()
                            ->default(now()->endOfYear())
                            ->live(),
                        Forms\Components\Textarea::make('notes')->columnSpanFull(),
                    ]),
                Forms\Components\Section::make('Budget Items')
                    ->schema([
                        Forms\Components\Repeater::make('budgetItems')
                            ->relationship()
                            ->columns(4)
                            ->hiddenLabel()
                            ->schema([
                                Forms\Components\Select::make('account_id')
                                    ->label('Account')
                                    ->options(Account::query()->pluck('name', 'id'))
                                    ->searchable()
                                    ->columnSpan(1)
                                    ->required(),
                                CustomSection::make('Budget Allocations')
                                    ->contained(false)
                                    ->columns(4)
                                    ->schema(static fn (Forms\Get $get) => self::getAllocationFields($get('../../start_date'), $get('../../end_date'), $get('../../interval_type'))),
                            ])
                            ->defaultItems(1)
                            ->addActionLabel('Add Budget Item'),
                    ]),
            ]);
    }
    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                //
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }
    private static function getAllocationFields(?string $startDate, ?string $endDate, ?string $intervalType): array
    {
        if (! $startDate || ! $endDate || ! $intervalType) {
            return [];
        }
        $start = Carbon::parse($startDate);
        $end = Carbon::parse($endDate);
        $fields = [];
        while ($start->lte($end)) {
            $label = match ($intervalType) {
                'month' => $start->format('M'), // Example: Jan, Feb, Mar
                'quarter' => 'Q' . $start->quarter, // Example: Q1, Q2, Q3
                'year' => (string) $start->year, // Example: 2024, 2025
                default => '',
            };
            $fields[] = Forms\Components\TextInput::make("amounts.{$label}")
                ->label($label)
                ->numeric()
                ->required();
            // Move to the next period
            match ($intervalType) {
                'month' => $start->addMonth(),
                'quarter' => $start->addQuarter(),
                'year' => $start->addYear(),
                default => null,
            };
        }
        return $fields;
    }
    /**
     * Generates an array of interval labels (e.g., Jan 2024, Q1 2024, etc.).
     */
    private static function generateIntervals(string $startDate, string $endDate, string $intervalType): array
    {
        $start = Carbon::parse($startDate);
        $end = Carbon::parse($endDate);
        $intervals = [];
        while ($start->lte($end)) {
            if ($intervalType === 'month') {
                $intervals[] = $start->format('M Y'); // Example: Jan 2024
                $start->addMonth();
            } elseif ($intervalType === 'quarter') {
                $intervals[] = 'Q' . $start->quarter . ' ' . $start->year; // Example: Q1 2024
                $start->addQuarter();
            } elseif ($intervalType === 'year') {
                $intervals[] = $start->year; // Example: 2024
                $start->addYear();
            }
        }
        return $intervals;
    }
    /**
     * Saves budget allocations correctly in `budget_allocations` table.
     */
    public static function saveBudgetAllocations(BudgetItem $record, array $data): void
    {
        $record->update($data);
        $intervals = self::generateIntervals($data['start_date'], $data['end_date'], $data['interval_type']);
        foreach ($intervals as $interval) {
            $record->allocations()->updateOrCreate(
                ['period' => $interval],
                [
                    'interval_type' => $data['interval_type'],
                    'start_date' => Carbon::parse($interval)->startOfMonth(),
                    'end_date' => Carbon::parse($interval)->endOfMonth(),
                    'amount' => $data['allocations'][$interval] ?? 0,
                ]
            );
        }
    }
    public static function getRelations(): array
    {
        return [
            //
        ];
    }
    public static function getPages(): array
    {
        return [
            'index' => Pages\ListBudgets::route('/'),
            'create' => Pages\CreateBudget::route('/create'),
            'view' => Pages\ViewBudget::route('/{record}'),
            'edit' => Pages\EditBudget::route('/{record}/edit'),
        ];
    }
}
 |