<?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\CreateRecord;
use Livewire\Attributes\On;

class CreateFeedPurchase extends CreateRecord
{
    use HasCart;

    protected static string $resource = FeedPurchaseResource::class;

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

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

    public function mount(): void
    {
        parent::mount();

        $this->loadCartFromDb();
    }

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

    protected function syncTotalPriceFromCart(): void
    {
        $total = (int) FeedPurchaseItem::whereNull('feed_purchase_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 mutateFormDataBeforeCreate(array $data): array
    {
        $total = FeedPurchaseItem::whereNull('feed_purchase_id')->sum('subtotal');
        $data['total_price'] = $total;

        return $data;
    }

    protected function afterCreate(): void
    {
        FeedPurchaseItem::whereNull('feed_purchase_id')
            ->update(['feed_purchase_id' => $this->record->id]);

        $this->record->updateFeedStock();
    }

    protected function getCreatedNotification(): ?Notification
    {
        return Notification::make()
            ->title('Data Berhasil Disimpan')
            ->body('Data baru telah berhasil ditambahkan dan disimpan oleh sistem.')
            ->success();
    }
}
