<?php

namespace App\Filament\App\Resources;

use App\Filament\App\Resources\AgendaRapatResource\Pages;
use App\Filament\App\Resources\AgendaRapatResource\RelationManagers;
use App\Mail\KirimPesan;
use App\Models\AgendaRapat;
use App\Models\HasilRapat;
use App\Models\Log;
use App\Models\Pesan;
use App\Models\PesertaRapat;
use App\Models\User;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Carbon\Carbon;
use Exception;
use Filament\Forms;
use Filament\Forms\Components\Tabs\Tab;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Support\Enums\FontWeight;
use Filament\Tables;
use Filament\Tables\Columns\Layout\Split;
use Filament\Tables\Columns\Layout\Stack;
use Filament\Tables\Table;
use HusamTariq\FilamentTimePicker\Forms\Components\TimePickerField;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Validation\Rule;
use Filament\Infolists;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Infolist;
use Illuminate\Support\Facades\Auth;
use Filament\Infolists\Components\Section;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\HtmlString;

use function Laravel\Prompts\alert;

class AgendaRapatResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = AgendaRapat::class;
    protected static ?int $navigationSort = -2;
    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static bool $shouldRegisterNavigation = false;

    public static function getPermissionPrefixes(): array
    {
        return [
            'view',
            'view_any',
            'create',
            'update',
            'delete',
            'delete_any',
            'persetujuan',
            'backdate',
            'edit_hasil_rapat',
            'lihat_hasil_rapat',
        ];
    }

    public static function form(Form $form): Form
    {
        $user = User::find(Auth::id());
        return $form
            ->schema([
                Forms\Components\TextInput::make('judul')
                    ->label('Judul Rapat')
                    ->required()
                    ->maxLength(255)
                    ->columnSpanFull(),
                Forms\Components\Textarea::make('keterangan')
                    ->columnSpanFull(),
                Forms\Components\Textarea::make('alasan_ditolak')
                    ->visible(function ($state) {
                        return $state != 'belum';
                    })
                    ->columnSpanFull()
                    ->disabled(),
                Forms\Components\DatePicker::make('tanggal')
                    ->required()
                    ->displayFormat('d/m/Y')
                    ->native(false)
                    ->live()
                    ->minDate(
                        $user->can('backdate_agenda::rapat')
                            ? null
                            : Carbon::today()
                    )
                    ->afterStateUpdated(function (callable $set) {
                        $set('selesai', null);
                    }),
                Forms\Components\Select::make('ruangan_id')
                    ->label('Ruangan')
                    ->relationship('ruangan', 'name')
                    ->required()
                    ->searchable()
                    ->preload()
                    ->afterStateUpdated(function (callable $set) {
                        $set('selesai', null);
                    }),
                TimePickerField::make('mulai')
                    ->label('Waktu Mulai')
                    ->required()
                    ->okLabel('Ok')
                    ->cancelLabel('Batal')
                    ->afterStateUpdated(function (callable $set) {
                        $set('selesai', null);
                    }),
                TimePickerField::make('selesai')
                    ->label('Waktu Selesai')
                    ->required()
                    ->okLabel('Ok')
                    ->cancelLabel('Batal')
                    ->live()
                    ->reactive()
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $tanggal = Carbon::parse($get('tanggal'))->toDateString(); // hasil: 'YYYY-MM-DD';
                        $mulai = $get('mulai');
                        $ruangan = $get('ruangan_id');
                        $selesai = $state;

                        $currentId = $get('id');
                        $isEditing = !empty($currentId);

                        if ($tanggal && $mulai && $ruangan && $selesai) {
                            $isRoomAvailable = !AgendaRapat::where('ruangan_id', $ruangan)
                                ->where('tanggal', $tanggal)
                                ->when($isEditing, fn($q) => $q->where('id', '!=', $currentId)) // <--- exclude jika sedang edit
                                ->when($currentId, fn($q) => $q->where('id', '!=', $currentId))
                                ->where(function ($query) use ($mulai, $selesai) {
                                    $query->whereBetween('mulai', [$mulai, $selesai])
                                        ->orWhereBetween('selesai', [$mulai, $selesai])
                                        ->orWhere(function ($query) use ($mulai, $selesai) {
                                            $query->where('mulai', '<=', $mulai)
                                                ->where('selesai', '>=', $selesai);
                                        });
                                })
                                ->exists();
                            if (!$isRoomAvailable) {
                                Notification::make()
                                    ->danger()
                                    ->title('Ruangan dipakai!')
                                    ->body('Ruangan sudah dipakai rapat lain pada waktu tersebut. Silahkan pilih waktu atau ruangan lain.')
                                    ->send();
                                $set('selesai', null);
                            }
                        } elseif ($tanggal == null) {
                            Notification::make()
                                ->danger()
                                ->title('Tanggal belum diisi!')
                                ->body('Tanggal, ruangan, waktu mulai, dan waktu selesai harus diisi.')
                                ->send();
                            $set('selesai', null);
                        } elseif ($ruangan == null) {
                            Notification::make()
                                ->danger()
                                ->title('Ruangan belum diisi!')
                                ->body('Tanggal, ruangan, waktu mulai, dan waktu selesai harus diisi.')
                                ->send();
                            $set('selesai', null);
                        } elseif ($mulai == null) {
                            Notification::make()
                                ->danger()
                                ->title('Waktu mulai belum diisi!')
                                ->body('Tanggal, ruangan, waktu mulai, dan waktu selesai harus diisi.')
                                ->send();
                            $set('selesai', null);
                        }
                    }),
                Forms\Components\Select::make('pelaksanaan')
                    ->required()
                    ->options([
                        'Daring' => 'Daring',
                        'Luring' => 'Luring',
                        'Hybrid' => 'Hybrid',
                    ])
                    ->live()
                    ->reactive()
                    ->default('daring'),
                Forms\Components\TextInput::make('link')
                    ->label('Link Rapat')
                    ->required(fn(Get $get): bool => $get('pelaksanaan') == 'Daring' || $get('pelaksanaan') == 'Hybrid')
                    ->visible(fn(Get $get): bool => $get('pelaksanaan') == 'Daring' || $get('pelaksanaan') == 'Hybrid'),
                Forms\Components\Select::make('notulen')
                    ->options(function () {
                        return User::all()->pluck('name', 'id');
                    })
                    ->columnSpanFull()
                    ->preload()
                    ->optionsLimit(10)
                    ->searchable()
                    ->label('Notulen')
                    ->required(),
                Forms\Components\Select::make('pic')
                    ->options(function () {
                        return User::all()->pluck('name', 'id');
                    })
                    ->columnSpanFull()
                    ->preload()
                    ->optionsLimit(10)
                    ->searchable()
                    ->label('Penanggung Jawab')
                    ->required(),
                Forms\Components\Select::make('dari')
                    ->options(function () {
                        return User::all()->pluck('name', 'id');
                    })
                    ->columnSpanFull()
                    ->preload()
                    ->optionsLimit(10)
                    ->searchable()
                    ->label('Bertanda Tangan')
                    ->required(),
                Forms\Components\FileUpload::make('bahan_rapat')
                    ->label('Bahan Rapat')
                    ->maxSize(1024 * 1024 * 2)
                    ->disk('public')
                    ->directory('bahan-rapat')
                    ->downloadable()
                    ->columnSpanFull(),
                // ->hidden(fn(string $context): bool => $context === 'create'),
            ]);
    }

    public static function table(Table $table): Table
    {
        $user = User::find(Auth::user()->id);
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('judul')
                    // ->weight(FontWeight::Bold)
                    // ->size('lg')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->searchable(),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->tooltip(function ($record) {
                        if ($record->status == 'Ditolak') {
                            return $record->alasan_ditolak;
                        }
                        return null;
                    })
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->color(fn(string $state): string => match ($state) {
                        'Draft' => 'gray',
                        'Pengajuan' => 'warning',
                        'Terjadwal' => 'info',
                        'Ditolak' => 'danger',
                        'Selesai' => 'success',
                    }),
                Tables\Columns\TextColumn::make('tindak_lanjut')
                    ->badge()
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->color(fn(string $state): string => match ($state) {
                        'Belum' => 'gray',
                        'Menunggu' => 'info',
                        'Review' => 'warning',
                        'Selesai' => 'success',
                    }),
                Tables\Columns\TextColumn::make('pelaksanaan')
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->badge()
                    ->color(fn(string $state): string => match ($state) {
                        'Daring' => 'violet',
                        'Luring' => 'sky',
                        'Hybrid' => 'fuchsia',
                    }),
                Tables\Columns\TextColumn::make('ruangan.name')
                    ->icon('heroicon-o-building-office-2')
                    ->label('Ruangan')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->searchable(),
                Tables\Columns\TextColumn::make('tanggal')
                    ->icon('heroicon-o-calendar-days')
                    ->date('d-m-Y')
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->sortable(),
                Tables\Columns\TextColumn::make('mulai')
                    ->icon('heroicon-o-clock')
                    ->time('H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: false),
                Tables\Columns\TextColumn::make('selesai')
                    ->icon('heroicon-o-clock')
                    ->time('H:i')
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->sortable(),
                Tables\Columns\TextColumn::make('Penanggungjawab.name')
                    ->label('Penanggung Jawab')
                    ->default('-')
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->searchable(),
                Tables\Columns\TextColumn::make('Notulensi.name')
                    ->label('Notulen')
                    ->default('-')
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->searchable(),
                Tables\Columns\TextColumn::make('TandaTangan.name')
                    ->label('Bertanda Tangan')
                    ->default('-')
                    ->toggleable(isToggledHiddenByDefault: false)
                    ->searchable(),
                Tables\Columns\TextColumn::make('keterangan')
                    ->limit(50)
                    ->default('-')
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->formatStateUsing(function ($state, $record) {
                        if ($record->status == 'Ditolak') {
                            return '';
                        }
                        return $state;
                    })
                    ->tooltip(function (Tables\Columns\TextColumn $column): ?string {
                        $state = $column->getState();

                        if (strlen($state) <= $column->getCharacterLimit()) {
                            return null;
                        }

                        // Only render the tooltip if the column content exceeds the length limit.
                        return $state;
                    }),
            ])
            ->filters([
                //
            ])
            ->actions([
                self::TombolEditAgendaRapat($user),
                self::TombolTerimaPengajuan($user),
                self::TombolTolakPengajuan($user),
                self::TombolSelesaiRapat($user),
                self::TombolEditHasilRapat($user),
                //self::TombolAjukanTindakLanjutRapat($user),
                self::TombolLihatTindakLanjutRapat($user),
                Tables\Actions\ActionGroup::make([
                    self::TombolLihatDetailAgendaRapat($user),
                    self::TombolAdminEdit($user),
                    self::TombolSelesaiDanAjukan($user),
                    self::TombolLog($user),
                    self::TombolSettings($user),
                    Tables\Actions\DeleteAction::make()
                        ->label('Hapus')
                        ->button()
                        ->visible(function () use ($user) {
                            return $user->can('delete_agenda::rapat') || $user->can('delete_any_agenda::rapat');
                        })
                ])->dropdownPlacement('bottom-start')
                    ->button()
                    ->label('Aksi Lain')
                    ->size('sm'),


            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ])->visible(function () use ($user) {
                    return $user->can('delete_agenda::rapat') || $user->can('delete_any_agenda::rapat');
                }),
            ]);
    }

    public static function infolist(Infolists\Infolist $infolist): Infolists\Infolist
    {
        return $infolist
            ->schema([
                Section::make('Agenda Rapat')
                    ->columns(2)
                    ->schema([
                        Infolists\Components\TextEntry::make('judul')
                            ->view('custom-text')
                            ->label('Judul Rapat')
                            ->columnSpanFull(),
                        Infolists\Components\TextEntry::make('pelaksanaan')
                            ->view('custom-text')
                            ->label('Mode Pelaksanaan'),
                        Infolists\Components\TextEntry::make('link')
                            ->view('custom-text')
                            ->label('Link Rapat')
                            ->formatStateUsing(function ($state) {
                                if ($state != null) {
                                    return $state;
                                }
                                return '-';
                            })
                            ->url(fn($record) => $record->link),
                        Infolists\Components\TextEntry::make('status')
                            ->view('custom-text')
                            ->label('Status'),
                        Infolists\Components\TextEntry::make('tindak_lanjut')
                            ->view('custom-text')
                            ->label('Tindak Lanjut'),
                        Infolists\Components\TextEntry::make('alasan_ditolak')
                            ->visible(function ($state) {
                                return $state != 'belum';
                            })
                            ->view('custom-text')
                            ->columnSpanFull(),
                        Infolists\Components\TextEntry::make('keterangan')
                            ->view('custom-text')
                            ->columnSpanFull(),
                        Infolists\Components\TextEntry::make('ruangan.name')
                            ->view('custom-text')
                            ->label('Ruangan'),
                        Infolists\Components\TextEntry::make('tanggal')
                            ->view('custom-text')
                            ->date('d-m-Y')
                            ->label('Tanggal'),
                        Infolists\Components\TextEntry::make('mulai')
                            ->view('custom-time')
                            ->formatStateUsing(fn($state) => Carbon::parse($state)->format('H:i'))
                            ->label('Waktu Mulai')
                            ->since()
                            ->default('-'),
                        Infolists\Components\TextEntry::make('selesai')
                            ->view('custom-time')
                            ->label('Waktu Selesai'),
                        Infolists\Components\TextEntry::make('Penanggungjawab.name')
                            ->view('custom-text')
                            ->label('Penanggung Jawab'),
                        Infolists\Components\TextEntry::make('Notulensi.name')
                            ->view('custom-text')
                            ->label('Notulen'),
                        Infolists\Components\TextEntry::make('bahan_rapat')
                            ->view('custom-text')
                            ->label('Bahan Rapat')
                            ->icon('heroicon-o-document-arrow-down')
                            ->formatStateUsing(function ($state) {
                                if ($state != null) {
                                    return "Unduh Dokumen";
                                }
                                return '-';
                            })
                            ->url(fn($record) => url('/storage/' . $record->bahan_rapat)),
                        Infolists\Components\TextEntry::make('creator.name')
                            ->view('custom-text')
                            ->label('Pembuat'),
                    ]),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAgendaRapats::route('/'),
            'terjadwal' => Pages\RapatTerjadwal::route('/terjadwal'),
            'pengajuan' => Pages\RapatPengajuan::route('/pengajuan'),
            'selesai' => Pages\RapatSelesai::route('/selesai'),
            'create' => Pages\CreateAgendaRapat::route('/create'),
            'tindak-lanjut' => Pages\ViewTindakLanjutAgendaRapat::route('/tindak-lanjut-rapat/{record}'),
            'konfirmasi' => Pages\ViewKonfirmasiAgendaRapat::route('/konfirmasi/{record}'),
            'view' => Pages\ViewAgendaRapat::route('/{record}'),
            'edit' => Pages\EditAgendaRapat::route('/{record}/edit'),
            'log' => Pages\ViewLogAgendaRapat::route('/{record}/log'),

        ];
    }

    /**
     * Tombol untuk mengedit agenda rapat
     *
     * @param User $user
     * @return Tables\Actions\EditAction
     */
    public static function TombolEditAgendaRapat($user)
    {
        return Tables\Actions\EditAction::make()
            ->button()
            ->hidden(function (AgendaRapat  $record) use ($user) {
                if ($record->user_id == $user->id && $record->status == "Draft" || $record->status == "Ditolak") {
                    return false;
                }
                return true;
            });
    }

    /**
     * Tombol untuk melihat detail agenda rapat
     *
     * @param User $user
     * @return Tables\Actions\ViewAction
     */
    public static function TombolLihatDetailAgendaRapat($user)
    {
        return Tables\Actions\ViewAction::make()
            ->label('Detail')
            ->button()
            ->color('success')
            ->hidden(function (AgendaRapat $record) {
                // if ($record->status == "Selesai" || $record->status == "Terjadwal") {
                //     return false;
                // }
                // return true;

                return false;
            });
    }

    /**
     * Tombol untuk mengajukan agenda rapat
     *
     * @param User $user
     * @return Tables\Actions\Action
     */
    public static function TombolSelesaiDanAjukan($user)
    {
        return Tables\Actions\Action::make('Selesai & Ajukan')
            ->label('Ajukan')
            ->modalHeading('Konfirmasi Pengajuan')
            ->modalWidth('sm')
            ->requiresConfirmation()
            ->button()
            ->color('success')
            ->action(function (AgendaRapat  $record) {
                $record->update(['status' => 'Pengajuan']);
                Log::create([
                    'agenda_rapat_id' => $record->id,
                    'user_id' => Auth::id(),
                    'log' => "Agenda rapat diajukan",
                ]);
                Notification::make()
                    ->success()
                    ->title('Agenda Rapat Diajukan')
                    ->body('Agenda rapat anda akan review oleh admin')
                    ->send();
            })
            ->requiresConfirmation()
            ->color('success')
            ->hidden(function (AgendaRapat  $record) use ($user) {
                if ($record->user_id == $user->id && $record->status == "Draft") {
                    return false;
                }
                return true;
            });
    }

    /**
     * Tombol untuk menerima pengajuan agenda rapat
     *
     * @param User $user
     * @return Tables\Actions\Action
     */
    public static function TombolTerimaPengajuan($user)
    {
        return Tables\Actions\Action::make('Terima')
            ->button()
            ->color('success')
            ->icon('heroicon-c-check')
            ->requiresConfirmation()
            ->hidden(function (AgendaRapat $record) use ($user) {
                if ($user->can('persetujuan_agenda::rapat') && $record->status == "Pengajuan") {
                    return false;
                }
                return true;
            })
            ->action(function (AgendaRapat $record) {

                $list = PesertaRapat::where('agenda_rapat_id', $record->id)->get();
                $nomer = "1";
                $agendaRapatTerakhir = AgendaRapat::whereMonth('accepted', Carbon::now()->month)
                    ->whereYear('accepted', Carbon::now()->year)
                    ->orderByDesc('accepted')
                    ->first();

                if ($agendaRapatTerakhir != null) {
                    $nomer = $agendaRapatTerakhir->nomer + 1;
                }
                $record->update([
                    'nomer' => $nomer,
                    'status' => 'Terjadwal',
                    'accepted' => now()
                ]);


                foreach ($list as $item) {

                    //buat pesan
                    Pesan::create([
                        'user_id' => $item->user_id,
                        'type' => 'Konfirmasi',
                        'title' => 'Undangan Rapat',
                        'body' => 'Agenda rapat dengan judul "' . $record->judul . '" telah dijadwalkan. Silakan cek detailnya.',
                        'action' => route('filament.app.resources.agenda-rapats.konfirmasi', [
                            'record' => $record->id,
                        ])
                    ]);

                    //ambil email
                    $email = User::where('id', $item->user_id)->first()->email;

                    try {
                        // kirim email
                        Mail::to($email)->send(new KirimPesan([
                            'type' => 'Konfirmasi',
                            'title' => 'Undangan Rapat',
                            'body' => 'Agenda rapat dengan judul "' . $record->judul . '" telah dijadwalkan. Silakan cek detailnya.',
                            'action' => route('filament.app.resources.agenda-rapats.konfirmasi', [
                                'record' => $record->id,
                            ])
                        ]));
                    } catch (Exception $ex) {
                        continue;
                    }
                }

                Log::create([
                    'agenda_rapat_id' => $record->id,
                    'user_id' => Auth::id(),
                    'log' => "Agenda rapat disetujui",
                ]);

                Notification::make()
                    ->success()
                    ->title('Berhasil menjadwalkan agenda rapat')
                    ->body('Anda menjadwalkan agenda rapat dan mengirim pemberitahuan ke peserta rapat')
                    ->send();
            });
    }


    /**
     * Tombol untuk menolak pengajuan agenda rapat
     *
     * @param User $user
     * @return Tables\Actions\Action
     */
    public static function TombolTolakPengajuan($user)
    {
        return Tables\Actions\Action::make('Tolak')
            ->button()
            ->color('danger')
            ->icon('heroicon-c-x-mark')
            ->requiresConfirmation()
            ->hidden(function (AgendaRapat $record) use ($user) {
                if ($user->can('persetujuan_agenda::rapat') && $record->status == "Pengajuan") {
                    return false;
                }
                return true;
            })
            ->form([
                Forms\Components\Textarea::make('alasan_ditolak')
                    ->label('Alasan Ditolak')
                    ->required()
                    ->placeholder('Masukkan alasan penolakan agenda rapat')
                    ->columnSpanFull(),
            ])
            ->action(function (array $data, AgendaRapat $record) {

                $record->update([
                    'status' => 'Ditolak',
                    'alasan_ditolak' => $data['alasan_ditolak']
                ]);
                Log::create([
                    'agenda_rapat_id' => $record->id,
                    'user_id' => Auth::id(),
                    'log' => "Agenda rapat ditolak",
                ]);
                Notification::make()
                    ->danger()
                    ->title('Berhasil menolak agenda rapat')
                    ->send();
            });
    }
    /**
     * Tombol untuk menyelesaikan agenda rapat
     *
     * @param User $user
     * @return Tables\Actions\Action
     */
    public static function TombolSelesaiRapat($user)
    {
        return Tables\Actions\Action::make('Selesai')
            ->button()
            ->color('success')
            ->icon('heroicon-c-check-badge')
            ->requiresConfirmation()
            ->hidden(function (AgendaRapat $record) use ($user) {
                if ($record->user_id == $user->id && $record->status == "Terjadwal") {
                    return false;
                }
                if ($user->can('persetujuan_agenda::rapat') && $record->status == "Terjadwal") {
                    return false;
                }
                return true;
            })
            ->action(function (AgendaRapat $record) {
                $hasilRapat = HasilRapat::create([
                    'agenda_rapat_id' => $record->id
                ]);
                $record->update([
                    'status' => 'Selesai',
                    'hasil_rapat_id' => $hasilRapat->id
                ]);
                Log::create([
                    'agenda_rapat_id' => $record->id,
                    'user_id' => Auth::id(),
                    'log' => "Agenda rapat selesai",
                ]);
                Notification::make()
                    ->success()
                    ->title('Berhasil memperbarui status agenda rapat')
                    ->send();
            });
    }
    /**
     * Tombol untuk mengedit hasil rapat
     *
     * @param User $user
     * @return Tables\Actions\Action
     */
    public static function TombolEditHasilRapat($user)
    {
        return Tables\Actions\Action::make('Hasil Rapat')
            ->button()
            ->color('warning')
            ->icon('heroicon-c-pencil-square')
            ->hidden(function (AgendaRapat $record) use ($user) {
                if ($record->user_id == $user->id && $record->status == "Selesai" && $record->tindak_lanjut == "Belum") {
                    return false;
                }
                if ($user->can('edit_hasil_rapat_agenda::rapat') && $record->status == "Selesai" && $record->tindak_lanjut == "Belum") {
                    return false;
                }
                return true;
            })
            ->url(fn(AgendaRapat $record): string => route('filament.app.resources.hasil-rapats.edit', [
                'record' => $record->hasil_rapat_id,
            ]));
    }

    /**
     * Tombol untuk mengajukan tindak lanjut agenda rapat
     *
     * @param User $user
     * @return Tables\Actions\Action
     */
    public static function TombolAjukanTindakLanjutRapat($user)
    {
        return Tables\Actions\Action::make('Ajukan Tindak Lanjut')
            ->button()
            ->label('Ajukan Tindak Lanjut')
            ->color('success')
            ->icon('heroicon-o-document-text')
            ->requiresConfirmation()
            ->hidden(function (AgendaRapat $record) use ($user) {
                if ($record->user_id == $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(function (AgendaRapat $record) {

                $record->update([
                    'tindak_lanjut' => 'Menunggu'
                ]);
                Log::create([
                    'agenda_rapat_id' => $record->id,
                    'user_id' => Auth::id(),
                    'log' => "Tindak lanjut rapat diajukan",
                ]);
                Notification::make()
                    ->success()
                    ->title('Berhasil memperbarui status agenda rapat')
                    ->send();
            });
    }

    /**
     * Tombol untuk melihat tindak lanjut agenda rapat
     *
     * @param User $user
     * @return Tables\Actions\Action
     */

    public static function TombolLihatTindakLanjutRapat($user)
    {
        return Tables\Actions\Action::make('Tindak Lanjut')
            ->button()
            ->color('warning')
            ->icon('heroicon-c-eye')
            ->hidden(function (AgendaRapat $record) use ($user) {
                if ($record->user_id == $user->id && $record->status == "Selesai" && $record->tindak_lanjut != "Belum") {
                    return false;
                }
                if ($user->can('lihat_hasil_rapat_agenda::rapat') && $record->status == "Selesai" && $record->tindak_lanjut != "Belum") {
                    return false;
                }
                return true;
            })
            ->url(fn(AgendaRapat $record): string => route('filament.app.resources.agenda-rapats.tindak-lanjut', [
                'record' => $record->id,
            ]));
    }

    /**
     * Tombol untuk mengedit status dan tindak lanjut agenda rapat
     *
     * @param User $user
     * @return Tables\Actions\Action
     */
    public static function TombolSettings($user)
    {
        return Tables\Actions\Action::make('Settings')
            ->modalWidth('md')
            ->button()
            ->label('Status')
            ->icon('heroicon-m-cog-8-tooth')
            ->color('gray')
            ->modalSubmitActionLabel('Ubah')
            ->fillForm(fn(AgendaRapat $record): array => [
                'status' => $record->status,
                'tindak_lanjut' => $record->tindak_lanjut,
            ])
            ->form([
                Forms\Components\Select::make('status')
                    ->label('Status')
                    ->options([
                        'Draft' => 'Draft',
                        'Pengajuan' => 'Pengajuan',
                        'Terjadwal' => 'Terjadwal',
                        'Ditolak' => 'Ditolak',
                        'Selesai' => 'Selesai',
                    ])
                    ->required(),
                Forms\Components\Select::make('tindak_lanjut')
                    ->label('Tindak Lanjut')
                    ->options([
                        'Belum' => 'Belum',
                        'Menunggu' => 'Menunggu',
                        'Review' => 'Review',
                        'Selesai' => 'Selesai',
                    ])
                    ->required(),
            ])
            ->hidden(function (AgendaRapat $record) use ($user) {
                if ($user->can('persetujuan_agenda::rapat')) {
                    return false;
                }
                return true;
            })
            ->action(function (array $data, AgendaRapat $record) {
                if ($data['status'] == 'Terjadwal') {
                    $nomer = "1";
                    $agendaRapatTerakhir = AgendaRapat::whereMonth('accepted', Carbon::now()->month)
                        ->whereYear('accepted', Carbon::now()->year)
                        ->orderByDesc('accepted')
                        ->first();

                    if ($agendaRapatTerakhir != null) {
                        $nomer = $agendaRapatTerakhir->nomer + 1;
                    }
                    $record->update([
                        'nomer' => $nomer,
                        'status' => 'Terjadwal',
                        'accepted' => now()
                    ]);
                }
                $record->update([
                    'status' => $data['status'],
                    'tindak_lanjut' => $data['tindak_lanjut']
                ]);
                Log::create([
                    'agenda_rapat_id' => $record->id,
                    'user_id' => Auth::id(),
                    'log' => "Status agenda rapat diubah",
                ]);
                Notification::make()
                    ->success()
                    ->title('Berhasil memperbarui status agenda rapat')
                    ->send();
            });
    }
    public static function TombolAdminEdit($user)
    {
        return Tables\Actions\Action::make('AdminUbah')
            ->label('Ubah')
            ->icon('heroicon-c-pencil')
            ->color('info')
            ->button()
            ->visible(function ($record) use ($user) {
                return $user->can('persetujuan_agenda::rapat') && $record->status == "Pengajuan";
            })
            ->url(function ($record) {
                return route('filament.app.resources.agenda-rapats.edit', $record);
            });
    }
    public static function TombolLog($user)
    {
        return Tables\Actions\Action::make('Log')
            ->button()
            ->color('warning')
            ->icon('heroicon-c-document-text')
            ->hidden(function (AgendaRapat $record) use ($user) {
                if ($user->can('persetujuan_agenda::rapat')) {
                    return false;
                }
                return true;
            })->url(fn(AgendaRapat $record): string => route('filament.app.resources.agenda-rapats.log', [
                'record' => $record->id,
            ]));
    }
}
