<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
use App\Models\User;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Hash;

class UserResource extends Resource
{
    protected static ?string $model = User::class;
    protected static ?string $modelLabel = "使用者管理";
    protected static ?string $navigationIcon = 'heroicon-o-user-circle';
    protected static ?string $navigationLabel = "使用者管理";

    public static function form(Form $form): Form
    {
        return $form
        ->schema([
            //
            TextInput::make("name")->required()->autocomplete(false),
            TextInput::make("email")->required()->email()->unique(ignoreRecord: true)->autocomplete(false),
            TextInput::make("password")
            ->password()
            ->dehydrateStateUsing(fn (string $state): string => Hash::make($state))
            ->dehydrated(fn (?string $state): bool => filled($state))
            ->required(fn (string $operation): bool => $operation === 'create'),
            Select::make('roles')->label("權限選擇")
                ->relationship(
                name: 'roles',
                titleAttribute: 'name',
                //modifyQueryUsing: fn (Builder $query) => $query->whereNotIn("id", [1,2]),
                )
                ->multiple()
                ->preload()
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make("name")->label("使用者名稱"),
                TextColumn::make("email")->label("E-Mail"),
                TextColumn::make('created_at')->label("建立時間")->date()
            ])->query(function (User $query) {
                return $query->where('email', '!=', env("SUPER_ADMIN_ACCOUNT", "admin@ogilvy.com"));
            })
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListUsers::route('/'),
            'create' => Pages\CreateUser::route('/create'),
            'edit' => Pages\EditUser::route('/{record}/edit'),
        ];
    }
}
