<?php

namespace App\Filament\Resources\BoardingHouses\Pages;

use App\Filament\Resources\BoardingHouses\BoardingHouseResource;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;

class EditBoardingHouse extends EditRecord
{
    protected static string $resource = BoardingHouseResource::class;

    // KODE BARU: Variabel penampung
    public string $submitType = 'draft';

    protected function getFormActions(): array
    {
        if (auth()->user()->hasRole(['super_admin', 'Admin'])) {
            return parent::getFormActions();
        }

        return [
            Action::make('submit_review')
                ->label('Submit Properti')
                ->color('primary')
                ->action(function () {
                    $this->submitType = 'pending';
                    $this->save();
                }),

            Action::make('save_draft')
                ->label('Simpan Draft')
                ->color('gray')
                ->action(function () {
                    $this->submitType = 'draft';
                    $this->save();
                }),

            $this->getCancelFormAction(),
        ];
    }

    protected function getHeaderActions(): array
    {
        return [
            DeleteAction::make()
                ->after(function ($record) {
                    if ($record->user) {
                        $record->user->increment('listing_quota');
                    }
                })
        ];
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        if (auth()->user()->hasRole('Owner')) {
            $data['user_id'] = auth()->id();
            // KODE BARU: Suntikkan status secara paksa saat diedit
            $data['status'] = $this->submitType;
        }

        return $data;
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }
}
