<?php

namespace App\Filament\Resources\SerahTerimaResource\Pages;

use App\Filament\Resources\SerahTerimaResource;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Auth;

class CreateSerahTerima extends CreateRecord
{
    protected static string $resource = SerahTerimaResource::class;

    protected function getCreatedNotification(): ?Notification
    {
        return null;
    }

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        unset($data['barang']);
        return $data;
    }

    protected function afterCreate(): void
    {
        $recipient = Auth::user();
        $barang = $this->form->getState()['barang'] ?? [];

        foreach ($barang as $index => $item) {
            if (empty($item['asal_usul'])) {
                throw new \Exception("Asal usul harus diisi");
            }
            if (empty($item['kepemilikan'])) {
                throw new \Exception("Kepemilikan harus diisi");
            }

            $createdItem = $this->record->barang()->create([
                'inventaris_id' => $item['inventaris_id'] ?? null,
                'kode_barang' => $item['kode_barang'],
                'nama_barang' => $item['nama_barang'],
                'merk' => $item['merk'] ?? null,
                'tahun' => $item['tahun'] ?? null,
                'asal_usul' => $item['asal_usul'],
                'satuan' => $item['satuan'] ?? null,
                'kepemilikan' => $item['kepemilikan'],
                'jumlah' => $item['jumlah'],
                'keterangan' => $item['keterangan'] ?? null,
            ]);
        }

        $title = $this->record->status === 'menerima'
            ? 'Penerimaan Berhasil Dibuat'
            : 'Penyerahan Berhasil Dibuat';

        $body = $this->record->status === 'menerima'
            ? "Penerimaan untuk {$this->record->nama_penerima} berhasil dibuat"
            : "Penyerahan kepada {$this->record->nama_penerima} berhasil dibuat";

        Notification::make()
            ->title($title)
            ->success()
            ->body($body)
            ->sendToDatabase($recipient);
    }

    protected function getRedirectUrl(): string
    {
        $url = $this->getResource()::getUrl('index');
        return $url;
    }
}
