<?php

namespace App\Filament\App\Resources\HasilRapatResource\Pages;

use App\Filament\App\Resources\HasilRapatResource;
use App\Models\Log;
use App\Models\User;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\Facades\Auth;

class EditHasilRapat extends EditRecord
{
    protected static string $resource = HasilRapatResource::class;

    protected static ?string $title = 'Hasil Rapat';

    protected function getHeaderActions(): array
    {
        return [
            Actions\Action::make('Kembali')
                ->url(function () {
                    return route('filament.app.resources.agenda-rapats.selesai');
                })
                ->button()
                ->color('info'),
        ];
    }

    protected function getFormActions(): array
    {
        return [
            $this->getSaveFormAction(),
            Actions\Action::make('Simpan dan Ajukan')
                ->hidden(function () {
                    $record = $this->record->agendaRapat;
                    $user = User::find(Auth::user()->id);
                    if ($user->id == $record->user_id && $record->status == "Selesai" && $record->tindak_lanjut == "Belum") {
                        return false;
                    }
                    if ($user->can('persetujuan_agenda::rapat') && $record->status == "Selesai" && $record->tindak_lanjut == "Belum") {
                        return false;
                    }
                    return true;
                })
                ->action('simpanDanAjukan')
                ->color('success'),
            $this->getCancelFormAction(),
        ];
    }

    /**
     * Simpan perubahan hasil rapat dan ajukan ke admin.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function simpanDanAjukan()
    {
        $this->record->save();
        $agendaRapat = $this->record->agendaRapat;

        $agendaRapat->update([
            'tindak_lanjut' => 'Menunggu'
        ]);

        Log::create([
            'agenda_rapat_id' => $agendaRapat->id,
            'user_id' => Auth::id(),
            'log' => "Tindak lanjut rapat diajukan",
        ]);

        Notification::make()
            ->success()
            ->title('Berhasil memperbarui status agenda rapat')
            ->send();
        Notification::make()
            ->success()
            ->title('Agenda Rapat Diajukan')
            ->body('Agenda rapat anda akan review oleh admin')
            ->send();

        return redirect()->route('filament.app.resources.agenda-rapats.tindak-lanjut', ['record' => $agendaRapat->id]);
    }
}
