<?php

namespace App\Filament\Resources\Rooms\Schemas;

use Filament\Schemas\Schema;
use Filament\Schemas\Components\Section;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\CheckboxList;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\File;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Illuminate\Support\Str;
use Filament\Resources\RelationManagers\RelationManager;

use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\Alignment;
use Intervention\Image\Format;

class RoomForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('Informasi Kamar')
                    ->schema([
                        Select::make('boarding_house_id')
                            ->relationship(
                                name: 'boardingHouse',
                                titleAttribute: 'name',
                                // BARU: Filter cerdas untuk kategori dan kepemilikan
                                modifyQueryUsing: function (Builder $query) {
                                    $user = auth()->user();

                                    // Semua role (Admin/Owner) hanya melihat kategori 'kos'
                                    $query->where('category', 'kos');

                                    // Jika Owner, filter lagi HANYA miliknya sendiri
                                    if ($user->hasRole('Owner')) {
                                        $query->where('user_id', $user->id);
                                    }

                                    return $query;
                                }
                            )
                            ->required()
                            ->label('Pilih Kos')
                            ->hidden(fn($livewire) => $livewire instanceof RelationManager),

                        TextInput::make('room_type')
                            ->required()
                            ->label('Tipe Kamar (Misal: Standard AC)')
                            ->maxLength(255),

                        TextInput::make('price_per_month')
                            ->required()
                            ->numeric()
                            ->prefix('Rp')
                            ->label('Harga per Bulan'),

                        TextInput::make('size')
                            ->label('Ukuran (Misal: 3x4m)')
                            ->maxLength(255),

                        Toggle::make('is_available')
                            ->required()
                            ->default(true)
                            ->label('Kamar Tersedia?'),
                    ])->columns(2),

                // ==========================================
                // SECTION: FOTO KAMAR
                // ==========================================
                Section::make('Foto Kamar')
                    ->schema([
                        FileUpload::make('images')
                            ->image()
                            ->disk('public')
                            ->multiple()
                            ->directory('rooms/gallery')
                            ->label('Galeri Foto Kamar (Bisa pilih banyak)')
                            ->columnSpanFull()
                            ->saveUploadedFileUsing(function (TemporaryUploadedFile $file): string {
                                $folder = 'rooms/gallery';
                                $filename = Str::random(20) . '.jpg';
                                $targetPath = storage_path('app/public/' . $folder);
                                File::ensureDirectoryExists($targetPath);

                                $manager = ImageManager::usingDriver(Driver::class);
                                $image = $manager->decodePath($file->getRealPath());
                                $image->scale(width: 1080);

                                $watermarkPath = public_path('images/watermark.png');
                                if (File::exists($watermarkPath)) {
                                    $watermark = $manager->decodePath($watermarkPath);

                                    $maxWidth = $image->width() * 0.3;
                                    if ($watermark->width() > $maxWidth) {
                                        $watermark->scale(width: (int)$maxWidth);
                                    }

                                    $posX = $image->width() - $watermark->width() - 20;
                                    $posY = $image->height() - $watermark->height() - 20;

                                    $image->insert($watermark, (int)$posX, (int)$posY);
                                }

                                $encoded = $image->encodeUsingFormat(Format::JPEG, quality: 80);
                                $encoded->save($targetPath . '/' . $filename);

                                return $folder . '/' . $filename;
                            }),
                    ]),

                Section::make('Fasilitas')
                    ->description('Pilih fasilitas apa saja yang tersedia khusus di kamar tipe ini.')
                    ->schema([
                        CheckboxList::make('facilities')
                            ->relationship(
                                name: 'facilities',
                                titleAttribute: 'name',
                                modifyQueryUsing: fn(Builder $query) => $query->where('category', 'kamar')
                            )
                            ->label('Pilih Fasilitas Kamar')
                            ->columns(3)
                            ->gridDirection('row')
                            ->columnSpanFull(),
                    ]),
            ]);
    }
}
