<?php

namespace App\Filament\Pages\Laporan;

use App\Models\Kematian;
use Carbon\Carbon;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Grid;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Pages\Page;
use Illuminate\Support\Facades\Auth;

class LaporanKematian extends Page implements HasForms
{
    use InteractsWithForms;

    protected static ?string $navigationIcon = 'heroicon-o-document-text';
    protected static ?string $navigationGroup = 'Laporan';
    protected static ?int $navigationSort = 4;
    protected static ?string $title = 'Laporan Kematian';

    protected static string $view = 'filament.pages.laporan.laporan-kematian';

    public $start_date;
    public $end_date;
    public $records;

    public function mount()
    {
        $this->form->fill([
            'start_date' => now()->subMonth(),
            'end_date' => now(),
        ]);
        $this->generateReport();
    }

    protected function getFormSchema(): array
    {
        return [
            Grid::make(2)
                ->schema([
                    DatePicker::make('start_date')
                        ->label('Tanggal Mulai')
                        ->default(now()->subMonth())
                        ->required()
                        ->reactive(),
                    DatePicker::make('end_date')
                        ->label('Tanggal Akhir')
                        ->default(now())
                        ->required()
                        ->reactive(),
                ]),
        ];
    }

    public function generateReport()
    {
        $data = $this->form->getState();
        $startDate = Carbon::parse($data['start_date'])->startOfDay();
        $endDate = Carbon::parse($data['end_date'])->endOfDay();

        $this->records = Kematian::query()
            ->with('penduduk')
            ->whereHas('penduduk', function ($q) {
                
                if (Auth::user()->role === "admin_dusun") {
                    $q->where('dusun_id', Auth::user()->dusun_id);
                }
            })
            ->whereBetween('tanggal_kematian', [$startDate, $endDate])
            ->get();
    }
}