<?php

namespace App\Filament\Resources\Feed\FeedPurchases\Pages;

use App\Filament\Actions\BackAction;
use App\Filament\Resources\Feed\FeedPurchases\FeedPurchaseResource;
use App\Filament\Resources\Feed\FeedPurchases\Traits\HasCart;
use App\Models\FeedPurchaseItem;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Livewire\Attributes\On;

class EditFeedPurchase extends EditRecord
{
    use HasCart;

    protected static string $resource = FeedPurchaseResource::class;

    protected ?string $heading = 'Ubah Belanja Pakan';

    protected static ?string $title = 'Ubah Belanja Pakan';

    public function mount(int|string $record): void
    {
        parent::mount($record);

        $this->loadCartFromDb();
    }

    #[On('cart-updated')]
    public function onCartUpdated(): void
    {
        $this->syncTotalPriceFromCart();
    }

    protected function syncTotalPriceFromCart(): void
    {
        $total = (int) FeedPurchaseItem::where('feed_purchase_id', $this->record->id)->sum('subtotal');

        $this->form->fill([
            ...$this->form->getState(),
            'total_price' => $total,
        ]);
    }

    protected function getHeaderActions(): array
    {
        return [
            BackAction::make()
                ->url(ListFeedPurchases::getUrl()),
        ];
    }

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

    protected function mutateFormDataBeforeSave(array $data): array
    {
        $total = FeedPurchaseItem::where('feed_purchase_id', $this->record->id)->sum('subtotal');
        $data['total_price'] = $total;

        return $data;
    }

    protected function getSavedNotification(): ?Notification
    {
        return Notification::make()
            ->title('Perubahan Berhasil Disimpan')
            ->body('Perubahan pada data telah berhasil disimpan dan diperbarui di sistem.')
            ->success();
    }
}
