<?php

namespace App\Filament\Resources\SuratUtamaResource\Pages;

use App\Filament\Resources\SuratUtamaResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Storage;
use Barryvdh\DomPDF\Facade\Pdf; // Import DomPDF
use Filament\Notifications\Notification; // Import Notification
use Carbon\Carbon; // Import Carbon untuk tanggal


class CreateSuratUtama extends CreateRecord
{
    protected static string $resource = SuratUtamaResource::class;
    
    
    protected function afterCreate(): void
    {
        $record = $this->getRecord(); // Mengambil record yang baru dibuat

        try {
            // Tentukan view Blade berdasarkan tipe surat
            $viewName = 'pdf.surat_template'; // Kita akan membuat view ini

            // Render HTML dari view Blade
            $html = view($viewName, compact('record'))->render();

            // Buat PDF
            $pdf = Pdf::loadHtml($html);

            // Tentukan path penyimpanan
            $folderName = str_replace('surat_', '', $record->id_tipe_surat); // misal: 'kelahiran', 'kematian'
            $fileName = $folderName . '_' . uniqid() . '.pdf';
            $filePath = 'surat_dokumen/' . $folderName . '/' . $fileName; // Path: surat_dokumen/kelahiran/xxx.pdf

            // Simpan PDF ke storage
            Storage::disk('public')->put($filePath, $pdf->output());

            // Update kolom file_path di record SuratUtama
            $record->update(['file_path' => $filePath]);

            Notification::make()->title('Draft PDF surat berhasil digenerate.')->success()->send();
        } catch (\Throwable $th) {
            Notification::make()->title('Gagal mengenerate draft PDF surat.')
                ->danger()
                ->body($th->getMessage())
                ->send();
            report($th); // Laporkan error ke log Laravel
        }
    }
}
