<?php

namespace App\Filament\Resources\BoardingHouses;

use App\Filament\Resources\BoardingHouses\Pages\CreateBoardingHouse;
use App\Filament\Resources\BoardingHouses\Pages\EditBoardingHouse;
use App\Filament\Resources\BoardingHouses\Pages\ListBoardingHouses;
use App\Filament\Resources\BoardingHouses\Schemas\BoardingHouseForm;
use App\Filament\Resources\BoardingHouses\Tables\BoardingHousesTable;
use App\Models\BoardingHouse;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use App\Filament\Resources\BoardingHouses\RelationManagers\RoomsRelationManager;
use Illuminate\Database\Eloquent\Builder;
use Filament\Actions\EditAction;

class BoardingHouseResource extends Resource
{
    protected static ?string $model = BoardingHouse::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedHome;

    public static function getNavigationGroup(): ?string
    {
        return 'Manajemen Properti';
    }

    public static function getNavigationSort(): ?int
    {
        return 1; // Ganti angkanya (1, 2, 3, dst) sesuai urutan yang diinginkan
    }

    public static function getModelLabel(): string
    {
        return 'Data Kos / Kontrakan';
    }

    public static function getPluralModelLabel(): string
    {
        return 'Data Kos';
    }

    public static function form(Schema $schema): Schema
    {
        return BoardingHouseForm::configure($schema);
    }

    public static function table(Table $table): Table
    {
        return BoardingHousesTable::configure($table)
            ->actions([
                EditAction::make()
                    // LOGIKA KUNCI: Kapan tombol Edit boleh muncul?
                    ->visible(
                        fn($record) =>
                        // Jika Admin, selalu muncul
                        auth()->user()->hasRole(['super_admin', 'Admin']) ||
                            // Jika Owner, muncul HANYA saat statusnya 'draft' atau 'rejected'
                            (auth()->user()->hasRole('Owner') && in_array($record->status, ['draft', 'rejected']))
                    ),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            RoomsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListBoardingHouses::route('/'),
            'create' => CreateBoardingHouse::route('/create'),
            'edit' => EditBoardingHouse::route('/{record}/edit'),
        ];
    }

    /**
     * LOGIKA PEMBATASAN DATA (QUERY SCOPING)
     */
    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery();

        // Jika yang login adalah Owner, filter HANYA data miliknya
        if (auth()->user()?->hasRole('Owner')) {
            $query->where('user_id', auth()->id());
        }

        return $query;
    }
}
