<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SuratPengantarPerkawinanResource\Pages;
use App\Models\SuratPengantarPerkawinan;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Filament\Notifications\Notification;
use Barryvdh\DomPDF\Facade\Pdf;
use Filament\Support\RawJs;
use Illuminate\Support\HtmlString;

class SuratPengantarPerkawinanResource extends Resource
{
    protected static ?string $model = SuratPengantarPerkawinan::class;

    protected static ?string $navigationIcon = 'heroicon-o-heart'; // Contoh ikon
    protected static ?string $navigationGroup = 'Kelola Surat';
    protected static ?string $navigationLabel = 'Surat Pengantar Perkawinan';
    protected static ?int $navigationSort = 12; // Sesuaikan urutan navigasi
    protected static bool $shouldRegisterNavigation = false;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Data Calon Mempelai Pria')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('nama_pria')
                            ->label('Nama Lengkap Pria')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama lengkap calon pria'),
                        Forms\Components\TextInput::make('nik_pria')
                            ->label('NIK Pria')
                            ->required()
                            ->numeric()
                            ->placeholder('Masukkan NIK pria'),
                        Forms\Components\TextInput::make('tempat_lahir_pria')
                            ->label('Tempat Lahir Pria')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: Tasikmalaya'),
                        Forms\Components\DatePicker::make('tanggal_lahir_pria')
                            ->label('Tanggal Lahir Pria')
                            ->required()
                            ->maxDate(now())
                            ->placeholder('Pilih tanggal lahir pria'),
                        Forms\Components\Select::make('agama_pria')
                            ->label('Agama Pria')
                            ->options([
                                'Islam' => 'Islam',
                                'Kristen Protestan' => 'Kristen Protestan',
                                'Kristen Katolik' => 'Kristen Katolik',
                                'Hindu' => 'Hindu',
                                'Buddha' => 'Buddha',
                                'Konghucu' => 'Konghucu',
                            ])
                            ->required()
                            ->placeholder('Pilih agama pria'),
                        Forms\Components\TextInput::make('pekerjaan_pria')
                            ->label('Pekerjaan Pria')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: Karyawan Swasta'),
                        Forms\Components\Textarea::make('alamat_pria')
                            ->label('Alamat Pria')
                            ->required()
                            ->rows(3)
                            ->maxLength(65535)
                            ->columnSpanFull()
                            ->placeholder('Contoh: Jl. Anggrek No. 10, RT 001 RW 002, Desa Raksajaya'),
                        Forms\Components\Select::make('status_perkawinan_pria')
                            ->label('Status Perkawinan Pria (Sebelumnya)')
                            ->options([
                                'Jejaka' => 'Jejaka',
                                'Duda' => 'Duda',
                            ])
                            ->required()
                            ->placeholder('Pilih status perkawinan pria'),
                        Forms\Components\TextInput::make('nama_ayah_pria')
                            ->label('Nama Ayah Pria')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Nama lengkap ayah calon pria'),
                        Forms\Components\TextInput::make('nama_ibu_pria')
                            ->label('Nama Ibu Pria')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Nama lengkap ibu calon pria'),
                    ]),

                Forms\Components\Section::make('Data Calon Mempelai Wanita')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('nama_wanita')
                            ->label('Nama Lengkap Wanita')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama lengkap calon wanita'),
                        Forms\Components\TextInput::make('nik_wanita')
                            ->label('NIK Wanita')
                            ->required()
                            ->numeric()
                            ->placeholder('Masukkan NIK wanita'),
                        Forms\Components\TextInput::make('tempat_lahir_wanita')
                            ->label('Tempat Lahir Wanita')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: Bandung'),
                        Forms\Components\DatePicker::make('tanggal_lahir_wanita')
                            ->label('Tanggal Lahir Wanita')
                            ->required()
                            ->maxDate(now())
                            ->placeholder('Pilih tanggal lahir wanita'),
                        Forms\Components\Select::make('agama_wanita')
                            ->label('Agama Wanita')
                            ->options([
                                'Islam' => 'Islam',
                                'Kristen Protestan' => 'Kristen Protestan',
                                'Kristen Katolik' => 'Kristen Katolik',
                                'Hindu' => 'Hindu',
                                'Buddha' => 'Buddha',
                                'Konghucu' => 'Konghucu',
                            ])
                            ->required()
                            ->placeholder('Pilih agama wanita'),
                        Forms\Components\TextInput::make('pekerjaan_wanita')
                            ->label('Pekerjaan Wanita')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: Ibu Rumah Tangga'),
                        Forms\Components\Textarea::make('alamat_wanita')
                            ->label('Alamat Wanita')
                            ->required()
                            ->rows(3)
                            ->maxLength(65535)
                            ->columnSpanFull()
                            ->placeholder('Contoh: Jl. Melati No. 5, RT 003 RW 004, Desa Raksajaya'),
                        Forms\Components\Select::make('status_perkawinan_wanita')
                            ->label('Status Perkawinan Wanita (Sebelumnya)')
                            ->options([
                                'Perawan' => 'Perawan',
                                'Janda' => 'Janda',
                            ])
                            ->required()
                            ->placeholder('Pilih status perkawinan wanita'),
                        Forms\Components\TextInput::make('nama_ayah_wanita')
                            ->label('Nama Ayah Wanita')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Nama lengkap ayah calon wanita'),
                        Forms\Components\TextInput::make('nama_ibu_wanita')
                            ->label('Nama Ibu Wanita')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Nama lengkap ibu calon wanita'),
                    ]),

                Forms\Components\Section::make('Detail Rencana Pernikahan')
                    ->columns(2)
                    ->schema([
                        Forms\Components\DatePicker::make('tanggal_rencana_nikah')
                            ->label('Tanggal Rencana Akad Nikah')
                            ->required()
                            ->placeholder('Pilih tanggal rencana pernikahan'),
                        Forms\Components\TextInput::make('tempat_rencana_nikah')
                            ->label('Tempat Rencana Akad Nikah')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: KUA Kecamatan Sodonghilir, Masjid Al-Ikhlas'),
                    ]),

                Forms\Components\Section::make('Dokumen Pendukung')
                    ->columns(2)
                    ->schema([
                        Forms\Components\FileUpload::make('file_n1_path')
                            ->label('Formulir N1 (Surat Pengantar Nikah)')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('spp_dokumen/n1')
                            ->required()
                            ->helperText('Unggah Formulir N1 yang sudah diisi dan ditandatangani.'),
                        Forms\Components\FileUpload::make('file_n4_path')
                            ->label('Formulir N4 (Surat Persetujuan Mempelai)')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('spp_dokumen/n4')
                            ->required()
                            ->helperText('Unggah Formulir N4 yang sudah diisi dan ditandatangani.'),
                        Forms\Components\FileUpload::make('file_n5_path')
                            ->label('Formulir N5 (Surat Izin Orang Tua) - Jika Usia < 21 Tahun')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('spp_dokumen/n5')
                            ->nullable()
                            ->required(fn (Forms\Get $get): bool =>
                                ($form->getModelInstance()->calculateAge('tanggal_lahir_pria') < 21) ||
                                ($form->getModelInstance()->calculateAge('tanggal_lahir_wanita') < 21)
                            )
                            ->helperText('Diperlukan jika salah satu atau kedua calon pengantin berusia di bawah 21 tahun.'),
                        Forms\Components\FileUpload::make('file_n6_path')
                            ->label('Formulir N6 (Surat Pernyataan Belum Pernah Menikah) - Opsional')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('spp_dokumen/n6')
                            ->nullable()
                            ->helperText('Opsional: Jika ada, unggah Formulir N6 yang sudah diisi dan ditandatangani.'),
                        Forms\Components\FileUpload::make('foto_ktp_pria_path')
                            ->label('Foto KTP Pria')
                            ->image()
                            ->disk('public')
                            ->directory('spp_dokumen/ktp_pria')
                            ->required()
                            ->helperText('Unggah foto KTP calon pria.'),
                        Forms\Components\FileUpload::make('foto_kk_pria_path')
                            ->label('Foto Kartu Keluarga (KK) Pria')
                            ->acceptedFileTypes(['image/*', 'application/pdf'])
                            ->disk('public')
                            ->directory('spp_dokumen/kk_pria')
                            ->required()
                            ->helperText('Unggah foto KK calon pria.'),
                        Forms\Components\FileUpload::make('foto_ktp_wanita_path')
                            ->label('Foto KTP Wanita')
                            ->image()
                            ->disk('public')
                            ->directory('spp_dokumen/ktp_wanita')
                            ->required()
                            ->helperText('Unggah foto KTP calon wanita.'),
                        Forms\Components\FileUpload::make('foto_kk_wanita_path')
                            ->label('Foto Kartu Keluarga (KK) Wanita')
                            ->acceptedFileTypes(['image/*', 'application/pdf'])
                            ->disk('public')
                            ->directory('spp_dokumen/kk_wanita')
                            ->required()
                            ->helperText('Unggah foto KK calon wanita.'),
                        Forms\Components\FileUpload::make('file_akta_lahir_pria_path')
                            ->label('File Akta Kelahiran Pria')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('spp_dokumen/akta_lahir_pria')
                            ->required()
                            ->helperText('Unggah file Akta Kelahiran calon pria.'),
                        Forms\Components\FileUpload::make('file_akta_lahir_wanita_path')
                            ->label('File Akta Kelahiran Wanita')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('spp_dokumen/akta_lahir_wanita')
                            ->required()
                            ->helperText('Unggah file Akta Kelahiran calon wanita.'),
                        Forms\Components\FileUpload::make('file_sertifikat_bimbingan_perkawinan_path')
                            ->label('File Sertifikat Bimbingan Perkawinan (Optional)')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('spp_dokumen/sertifikat_bimbingan')
                            ->nullable()
                            ->helperText('Unggah sertifikat bimbingan perkawinan jika ada.'),
                            
                        Forms\Components\Section::make('Link Dokumen Terunggah')
                            ->description('Klik link di bawah untuk melihat atau mengunduh dokumen yang telah diunggah.')
                            ->visibleOn('edit') // Hanya tampil di halaman edit
                            ->columns(2)
                            ->schema([
                                Forms\Components\Placeholder::make('download_n1_placeholder')
                                    ->label('Formulir N1')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->file_n1_path) {
                                            $url = Storage::url($record->file_n1_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat N1</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                                Forms\Components\Placeholder::make('download_n4_placeholder')
                                    ->label('Formulir N4')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->file_n4_path) {
                                            $url = Storage::url($record->file_n4_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat N4</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                                Forms\Components\Placeholder::make('download_n5_placeholder')
                                    ->label('Formulir N5')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->file_n5_path) {
                                            $url = Storage::url($record->file_n5_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat N5</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                                Forms\Components\Placeholder::make('download_n6_placeholder')
                                    ->label('Formulir N6')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->file_n6_path) {
                                            $url = Storage::url($record->file_n6_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat N6</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                                Forms\Components\Placeholder::make('download_ktp_pria_placeholder')
                                    ->label('Foto KTP Pria')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->foto_ktp_pria_path) {
                                            $url = Storage::url($record->foto_ktp_pria_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat KTP Pria</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                                Forms\Components\Placeholder::make('download_kk_pria_placeholder')
                                    ->label('Foto KK Pria')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->foto_kk_pria_path) {
                                            $url = Storage::url($record->foto_kk_pria_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat KK Pria</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                                Forms\Components\Placeholder::make('download_ktp_wanita_placeholder')
                                    ->label('Foto KTP Wanita')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->foto_ktp_wanita_path) {
                                            $url = Storage::url($record->foto_ktp_wanita_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat KTP Wanita</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                                Forms\Components\Placeholder::make('download_kk_wanita_placeholder')
                                    ->label('Foto KK Wanita')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->foto_kk_wanita_path) {
                                            $url = Storage::url($record->foto_kk_wanita_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat KK Wanita</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                                Forms\Components\Placeholder::make('download_akta_lahir_pria_placeholder')
                                    ->label('Akta Kelahiran Pria')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->file_akta_lahir_pria_path) {
                                            $url = Storage::url($record->file_akta_lahir_pria_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat Akta Pria</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                                Forms\Components\Placeholder::make('download_akta_lahir_wanita_placeholder')
                                    ->label('Akta Kelahiran Wanita')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->file_akta_lahir_wanita_path) {
                                            $url = Storage::url($record->file_akta_lahir_wanita_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat Akta Wanita</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                                Forms\Components\Placeholder::make('download_sertifikat_bimbingan_perkawinan_placeholder')
                                    ->label('Sertifikat Bimbingan')
                                    ->content(function (?SuratPengantarPerkawinan $record) {
                                        if ($record && $record->file_sertifikat_bimbingan_perkawinan_path) {
                                            $url = Storage::url($record->file_sertifikat_bimbingan_perkawinan_path);
                                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat Sertifikat</a>");
                                        }
                                        return 'Belum diunggah.';
                                    }),
                            ])
                    ]),

                Forms\Components\Section::make('Informasi Surat')
                    ->columns(1)
                    ->schema([
                        Forms\Components\TextInput::make('nomor_surat')
                            ->label('Nomor Surat')
                            ->disabledOn('create')
                            ->helperText('Nomor surat akan dibuat otomatis saat disetujui oleh admin desa.')
                            ->placeholder('Nomor surat akan terisi otomatis'),
                        Forms\Components\DatePicker::make('tanggal_dikeluarkan')
                            ->label('Tanggal Surat Dibuat')
                            ->required()
                            ->maxDate(now())
                            ->placeholder('Pilih tanggal surat dibuat'),
                    ]),

                Forms\Components\Select::make('status')
                    ->options([
                        'menunggu_acc_admin_desa' => 'Menunggu Persetujuan Admin Desa',
                        'disetujui' => 'Disetujui',
                        'ditolak' => 'Ditolak',
                    ])
                    ->visible(fn (): bool => Auth::user()->role !== 'warga')
                    ->disabledOn('create')
                    ->visibleOn('edit')
                    ->placeholder('Pilih status surat'),

                Forms\Components\Textarea::make('catatan_penolakan')
                    ->label('Catatan Penolakan')
                    ->visible(fn (string $operation, Forms\Get $get): bool => $get('status') === 'ditolak' && $operation === 'edit')
                    ->placeholder('Masukkan alasan penolakan surat'),

                Forms\Components\Placeholder::make('file_spp_surat')
                    ->label('File Surat Pengantar Perkawinan')
                    ->content(function (?SuratPengantarPerkawinan $record) {
                        if ($record && $record->file_path) {
                            $url = Storage::url($record->file_path);
                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh Surat SPP</a>");
                        }
                        return 'Belum ada file surat SPP.';
                    })
                    ->visibleOn('edit'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('nomor_surat')
                    ->label('No. Surat')
                    ->placeholder('Belum Tersedia')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('nama_pria')
                    ->label('Nama Pria')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('nama_wanita')
                    ->label('Nama Wanita')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('tanggal_rencana_nikah')
                    ->label('Tgl. Rencana Nikah')
                    ->date('d M Y')
                    ->sortable(),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'menunggu_acc_admin_desa' => 'warning',
                        'disetujui' => 'success',
                        'ditolak' => 'danger',
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('disetujuiOleh.name')
                    ->label('Disetujui Oleh')
                    ->placeholder('Belum Disetujui')
                    ->sortable(),
                Tables\Columns\TextColumn::make('tanggal_disetujui')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->options([
                        'menunggu_acc_admin_desa' => 'Menunggu Persetujuan Admin Desa',
                        'disetujui' => 'Disetujui',
                        'ditolak' => 'Ditolak',
                    ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\Action::make('download_draft')
                        ->label('Unduh Draft PDF')
                        ->icon('heroicon-o-arrow-down-tray')
                        ->color('info')
                        ->action(function (SuratPengantarPerkawinan $record) {
                            if (!$record->file_path) {
                                $html = view('pdf.surat_pengantar_perkawinan', compact('record'))->render();
                                $pdf = Pdf::loadHtml($html);
                                $filePath = 'surat_pengantar_perkawinan/' . uniqid() . '.pdf';
                                Storage::disk('public')->put($filePath, $pdf->output());
                                $record->update(['file_path' => $filePath]);
                                Notification::make()->title('Draft PDF berhasil digenerate.')->success()->send();
                            }
                            return response()->download(Storage::disk('public')->path($record->file_path));
                        }),

                    Tables\Actions\Action::make('setujui_surat')
                        ->label('Setujui & Unggah PDF')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->modalSubmitActionLabel('Unggah & Setujui')
                        ->form([
                            Forms\Components\TextInput::make('nomor_surat_acc')
                                ->label('Nomor Surat Resmi')
                                ->required()
                                ->unique('surat_pengantar_perkawinan', 'nomor_surat', ignoreRecord: true)
                                ->placeholder('Contoh: 470/SPP.001/DS.RKJ/V/2025'),
                            Forms\Components\FileUpload::make('signed_pdf')
                                ->label('Unggah PDF Bertanda Tangan')
                                ->acceptedFileTypes(['application/pdf'])
                                ->directory('surat_pengantar_perkawinan')
                                ->required(),
                        ])
                        ->action(function (array $data, SuratPengantarPerkawinan $record) {
                            DB::transaction(function () use ($data, $record) {
                                $record->update([
                                    'status' => 'disetujui',
                                    'nomor_surat' => $data['nomor_surat_acc'],
                                    'file_path' => $data['signed_pdf'],
                                    'disetujui_oleh' => Auth::id(),
                                    'tanggal_disetujui' => now(),
                                ]);

                                Notification::make()
                                    ->title('Surat Pengantar Perkawinan berhasil disetujui.')
                                    ->success()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratPengantarPerkawinan $record): bool => Auth::user()->role !== 'warga' && $record->status === 'menunggu_acc_admin_desa'),

                    Tables\Actions\Action::make('tolak_surat')
                        ->label('Tolak Surat')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->modalSubmitActionLabel('Tolak')
                        ->form([
                            Forms\Components\Textarea::make('catatan_penolakan')
                                ->label('Alasan Penolakan')
                                ->required()
                                ->rows(5),
                        ])
                        ->action(function (array $data, SuratPengantarPerkawinan $record) {
                            DB::transaction(function () use ($data, $record) {
                                $record->update([
                                    'status' => 'ditolak',
                                    'catatan_penolakan' => $data['catatan_penolakan'],
                                    'disetujui_oleh' => Auth::id(),
                                    'tanggal_disetujui' => now(),
                                ]);

                                Notification::make()
                                    ->title('Surat Pengantar Perkawinan berhasil ditolak.')
                                    ->danger()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratPengantarPerkawinan $record): bool => Auth::user()->role !== 'warga' && $record->status === 'menunggu_acc_admin_desa'),
                ]),
                Tables\Actions\DeleteAction::make()->visible(fn (): bool => Auth::user()->role === 'admin_desa'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()->visible(fn (): bool => Auth::user()->role === 'admin_desa'),
                ]),
            ]);
    }

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

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                //
            ]);
    }

    public static function afterCreate(SuratPengantarPerkawinan $record): void
    {
        try {
            $html = view('pdf.surat_pengantar_perkawinan', compact('record'))->render();
            $pdf = Pdf::loadHtml($html);
            $filePath = 'surat_pengantar_perkawinan/' . uniqid() . '.pdf';
            Storage::disk('public')->put($filePath, $pdf->output());

            $record->update(['file_path' => $filePath]);
            Notification::make()->title('Draft PDF surat Pengantar Perkawinan berhasil digenerate.')->success()->send();
        } catch (\Throwable $th) {
            Notification::make()->title('Gagal mengenerate draft PDF surat Pengantar Perkawinan.')->danger()->body($th->getMessage())->send();
            report($th);
        }
    }
}