<?php

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

use App\Models\Feed;
use App\Models\FeedPurchaseItem;

trait HasCart
{
    public array $cart = [];

    public function loadCartFromDb(): void
    {
        $id = isset($this->record) ? $this->record->id : null;

        $this->cart = FeedPurchaseItem::where('feed_purchase_id', $id)
            ->get()
            ->pluck('quantity', 'feed_id')
            ->map(fn ($qty) => ['qty' => (int) $qty])
            ->toArray();
    }

    public function addFeed(int $feedId): void
    {
        $feed = Feed::find($feedId);
        if (! $feed) {
            return;
        }

        $id = isset($this->record) ? $this->record->id : null;

        $item = FeedPurchaseItem::where('feed_purchase_id', $id)
            ->where('feed_id', $feedId)
            ->first();

        if ($item) {
            $item->increment('quantity', 1);
            $item->update(['subtotal' => $item->quantity * $item->unit_price]);
        } else {
            FeedPurchaseItem::create([
                'feed_purchase_id' => $id,
                'feed_id' => $feedId,
                'quantity' => 1,
                'unit_price' => $feed->price,
                'subtotal' => $feed->price,
            ]);
        }

        // Update stock if editing
        if ($id) {
            $feed->increment('stock', 1);
        }

        $this->loadCartFromDb();
        $this->dispatch('cart-updated');
    }

    public function decreaseQty(int $feedId): void
    {
        $id = isset($this->record) ? $this->record->id : null;

        $item = FeedPurchaseItem::where('feed_purchase_id', $id)
            ->where('feed_id', $feedId)
            ->first();

        if ($item) {
            if ($item->quantity > 1) {
                $item->decrement('quantity', 1);
                $item->update(['subtotal' => $item->quantity * $item->unit_price]);
            } else {
                $item->delete();
            }

            // Update stock if editing
            if ($id) {
                $item->feed?->decrement('stock', 1);
            }

            $this->loadCartFromDb();
            $this->dispatch('cart-updated');
        }
    }

    public function removeCartItem(int $itemId): void
    {
        $id = isset($this->record) ? $this->record->id : null;
        $item = FeedPurchaseItem::find($itemId);

        if ($item && $item->feed_purchase_id == $id) {
            // Revert stock if editing
            if ($id) {
                $item->feed?->decrement('stock', $item->quantity);
            }

            $item->delete();
        }

        $this->loadCartFromDb();
        $this->dispatch('cart-updated');
    }
}
